Keshavj-13 commited on
Commit
2d25aa3
·
1 Parent(s): d6b41a8

feat: add Groq API integration with Llama 3.1 8B support

Browse files
Files changed (3) hide show
  1. README.md +39 -7
  2. setup_groq_inference.sh +57 -0
  3. test_groq_inference.py +153 -0
README.md CHANGED
@@ -110,14 +110,24 @@ To avoid gaming the benchmark with tiny partial plans, the operational score is
110
 
111
  [inference.py](inference.py) is the required root-level inference script. It:
112
 
113
- - uses the OpenAI Python client for LLM calls
114
- - reads `API_BASE_URL`, `MODEL_NAME`, and `HF_TOKEN`
115
  - emits strict `[START]`, `[STEP]`, and `[END]` logs
116
  - runs all three tasks
117
- - falls back to a deterministic planner from [planner.py](/workspace/planner.py) if model output fails
118
 
119
  The deterministic planner is useful for reproducibility and CI smoke tests. When a model endpoint is configured, the LLM gets the task briefing and a heuristic seed plan and is asked to return strict JSON.
120
 
 
 
 
 
 
 
 
 
 
 
121
  ### Reproducible baseline scores
122
 
123
  With no LLM credentials configured, `inference.py` falls back to the deterministic heuristic planner and produces these baseline composite scores:
@@ -154,9 +164,26 @@ pip install uv
154
  uv sync
155
  ```
156
 
157
- ### Required environment variables
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
 
159
- Before running `inference.py`, define:
160
 
161
  ```bash
162
  export API_BASE_URL="https://your-llm-endpoint/v1"
@@ -164,9 +191,14 @@ export MODEL_NAME="your-model-name"
164
  export HF_TOKEN="your-secret-token"
165
  ```
166
 
167
- `OPENAI_API_KEY` is also accepted as a credential fallback when `HF_TOKEN` is not set.
 
 
 
 
 
 
168
 
169
- For local testing without an LLM endpoint, the script still runs by falling back to the deterministic planner.
170
 
171
  ## Running the environment
172
 
 
110
 
111
  [inference.py](inference.py) is the required root-level inference script. It:
112
 
113
+ - supports both **Groq API** (Llama 3.1 8B) and OpenAI-compatible endpoints
114
+ - reads `GROQ_API_KEY` for Groq inference, or `API_BASE_URL`, `MODEL_NAME`, and `HF_TOKEN` for HuggingFace
115
  - emits strict `[START]`, `[STEP]`, and `[END]` logs
116
  - runs all three tasks
117
+ - falls back to a deterministic planner from [planner.py](planner.py) if model output fails
118
 
119
  The deterministic planner is useful for reproducibility and CI smoke tests. When a model endpoint is configured, the LLM gets the task briefing and a heuristic seed plan and is asked to return strict JSON.
120
 
121
+ ### Running with Groq API (Llama 3.1 8B)
122
+
123
+ ```bash
124
+ export GROQ_API_KEY="your-groq-api-key"
125
+ python test_groq_inference.py # Test the setup
126
+ python -m inference # Run full inference
127
+ ```
128
+
129
+ See [GROQ_SETUP.md](GROQ_SETUP.md) for detailed configuration and troubleshooting.
130
+
131
  ### Reproducible baseline scores
132
 
133
  With no LLM credentials configured, `inference.py` falls back to the deterministic heuristic planner and produces these baseline composite scores:
 
164
  uv sync
165
  ```
166
 
167
+ ### Environment variables - Option 1: Groq API (Recommended)
168
+
169
+ For fast inference with Llama 3.1 8B:
170
+
171
+ ```bash
172
+ export GROQ_API_KEY="your-groq-api-key"
173
+ export GROQ_MODEL="llama-3.1-8b-instant" # optional, defaults to this
174
+ ```
175
+
176
+ Then run:
177
+ ```bash
178
+ python test_groq_inference.py # verify setup
179
+ python -m inference # run full benchmark
180
+ ```
181
+
182
+ See [GROQ_SETUP.md](GROQ_SETUP.md) for detailed guide.
183
+
184
+ ### Environment variables - Option 2: HuggingFace API
185
 
186
+ For OpenAI-compatible endpoints:
187
 
188
  ```bash
189
  export API_BASE_URL="https://your-llm-endpoint/v1"
 
191
  export HF_TOKEN="your-secret-token"
192
  ```
193
 
194
+ ### Testing without LLM
195
+
196
+ For local testing without an LLM endpoint, the script still runs by falling back to the deterministic planner:
197
+
198
+ ```bash
199
+ python -m inference # Uses heuristic baseline only
200
+ ```
201
 
 
202
 
203
  ## Running the environment
204
 
setup_groq_inference.sh ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Quick setup and test script for Groq inference
3
+
4
+ set -e
5
+
6
+ echo "🚀 Groq Inference Setup & Testing"
7
+ echo "=================================="
8
+ echo ""
9
+
10
+ # Check if GROQ_API_KEY is set
11
+ if [ -z "$GROQ_API_KEY" ]; then
12
+ echo "❌ GROQ_API_KEY not set!"
13
+ echo ""
14
+ echo "Please set your Groq API key:"
15
+ echo " export GROQ_API_KEY='your_key_here'"
16
+ echo ""
17
+ echo "Then run this script again:"
18
+ echo " bash setup_groq_inference.sh"
19
+ exit 1
20
+ fi
21
+
22
+ echo "✅ GROQ_API_KEY detected"
23
+ echo ""
24
+
25
+ # Check Python installation
26
+ echo "📦 Checking Python environment..."
27
+ python --version
28
+ echo "✅ Python available"
29
+ echo ""
30
+
31
+ # Check if groq package is installed
32
+ echo "📦 Checking groq package..."
33
+ python -c "import groq; print(f'✅ groq {groq.__version__} installed')" || {
34
+ echo "❌ groq not installed"
35
+ echo "Installing..."
36
+ pip install groq
37
+ }
38
+ echo ""
39
+
40
+ # Check inference.py
41
+ echo "🔍 Checking inference.py..."
42
+ python -m py_compile inference.py
43
+ echo "✅ inference.py syntax valid"
44
+ echo ""
45
+
46
+ # Run test script
47
+ echo "🧪 Running inference tests..."
48
+ echo "=================================="
49
+ python test_groq_inference.py
50
+ echo ""
51
+ echo "✅ Setup complete!"
52
+ echo ""
53
+ echo "📝 Next steps:"
54
+ echo " 1. Review test results above"
55
+ echo " 2. Run full tests: pytest tests/ -v"
56
+ echo " 3. Start inference: python -m inference"
57
+ echo ""
test_groq_inference.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Test script for Groq inference with Llama 3.1 8B."""
3
+
4
+ import json
5
+ import os
6
+ from groq import Groq
7
+
8
+ def test_groq_inference():
9
+ """Test basic Groq inference with Llama 3.1 8B."""
10
+ api_key = os.getenv("GROQ_API_KEY")
11
+ if not api_key:
12
+ print("❌ GROQ_API_KEY environment variable not set")
13
+ print(" Run: export GROQ_API_KEY='your-key-here'")
14
+ return False
15
+
16
+ print(f"✅ GROQ_API_KEY detected")
17
+
18
+ try:
19
+ client = Groq(api_key=api_key)
20
+ print("✅ Groq client initialized")
21
+
22
+ # Test message
23
+ test_prompt = """You are an ATC optimization expert.
24
+ Return a JSON response with exactly these keys: model, task, status.
25
+ Example: {"model": "llama-3.1-8b", "task": "atc_optimization", "status": "ready"}"""
26
+
27
+ print("\n📨 Sending test request to Groq API (llama-3.1-8b-instant)...")
28
+
29
+ completion = client.chat.completions.create(
30
+ model="llama-3.1-8b-instant",
31
+ messages=[
32
+ {
33
+ "role": "system",
34
+ "content": "You are a helpful assistant that responds with valid JSON only."
35
+ },
36
+ {
37
+ "role": "user",
38
+ "content": test_prompt
39
+ }
40
+ ],
41
+ temperature=0,
42
+ max_tokens=200,
43
+ )
44
+
45
+ response_text = completion.choices[0].message.content
46
+ print(f"\n✅ Got response from model")
47
+ print(f" Response: {response_text[:100]}...")
48
+
49
+ # Try to parse JSON
50
+ try:
51
+ # Extract JSON from response
52
+ start = response_text.find("{")
53
+ end = response_text.rfind("}") + 1
54
+ if start >= 0 and end > start:
55
+ json_str = response_text[start:end]
56
+ parsed = json.loads(json_str)
57
+ print(f"\n✅ JSON parsed successfully")
58
+ print(f" Model response: {parsed}")
59
+ return True
60
+ else:
61
+ print(f"⚠️ No JSON found in response")
62
+ return False
63
+ except json.JSONDecodeError as e:
64
+ print(f"⚠️ Failed to parse JSON: {e}")
65
+ print(f" Response text: {response_text}")
66
+ return False
67
+
68
+ except Exception as e:
69
+ print(f"❌ Error: {e}")
70
+ return False
71
+
72
+ def test_atc_inference():
73
+ """Test ATC-specific inference."""
74
+ api_key = os.getenv("GROQ_API_KEY")
75
+ if not api_key:
76
+ return False
77
+
78
+ try:
79
+ client = Groq(api_key=api_key)
80
+
81
+ print("\n\n🛫 Testing ATC inference prompt...")
82
+
83
+ atc_prompt = """{
84
+ "task": "delhi_monsoon_recovery_easy",
85
+ "briefing": "Sample ATC runway schedule conflict scenario",
86
+ "flights": 8,
87
+ "heuristic_plan": [{"flight_id": "AI001", "runway": "09L", "assigned_minute": 5}]
88
+ }
89
+
90
+ You are optimizing an ATC runway schedule. Return strict JSON with keys: rationale, proposal.
91
+ proposal is an array of objects with flight_id, runway, assigned_minute, hold_minutes."""
92
+
93
+ completion = client.chat.completions.create(
94
+ model="llama-3.1-8b-instant",
95
+ messages=[
96
+ {
97
+ "role": "system",
98
+ "content": "You are a conservative ATC planner. Output strict JSON only."
99
+ },
100
+ {
101
+ "role": "user",
102
+ "content": atc_prompt
103
+ }
104
+ ],
105
+ temperature=0,
106
+ max_tokens=500,
107
+ )
108
+
109
+ response_text = completion.choices[0].message.content
110
+ print(f"✅ ATC inference succeeded")
111
+ print(f" Response length: {len(response_text)} chars")
112
+ print(f" First 150 chars: {response_text[:150]}...")
113
+
114
+ # Verify JSON structure
115
+ start = response_text.find("{")
116
+ end = response_text.rfind("}") + 1
117
+ if start >= 0 and end > start:
118
+ json_str = response_text[start:end]
119
+ parsed = json.loads(json_str)
120
+ has_rationale = "rationale" in parsed
121
+ has_proposal = "proposal" in parsed
122
+ print(f" Has 'rationale': {has_rationale}")
123
+ print(f" Has 'proposal': {has_proposal}")
124
+
125
+ if has_rationale and has_proposal:
126
+ print(f"✅ ATC response structure valid")
127
+ return True
128
+ else:
129
+ print(f"⚠️ Missing required fields")
130
+ return False
131
+ else:
132
+ print(f"⚠️ No JSON in response")
133
+ return False
134
+
135
+ except Exception as e:
136
+ print(f"❌ ATC inference error: {e}")
137
+ return False
138
+
139
+ if __name__ == "__main__":
140
+ print("=" * 70)
141
+ print("GROQ INFERENCE TEST - Llama 3.1 8B")
142
+ print("=" * 70)
143
+
144
+ success1 = test_groq_inference()
145
+ success2 = test_atc_inference()
146
+
147
+ print("\n" + "=" * 70)
148
+ if success1 and success2:
149
+ print("✅ ALL TESTS PASSED - Groq inference is working!")
150
+ print("=" * 70)
151
+ else:
152
+ print("⚠️ Some tests failed - check configuration above")
153
+ print("=" * 70)