Upload folder using huggingface_hub
Browse files- inference.py +106 -0
inference.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import asyncio
|
| 3 |
+
from typing import List
|
| 4 |
+
from openai import OpenAI
|
| 5 |
+
from sql_env_environment import SqlEnvironment
|
| 6 |
+
from models import SqlAction
|
| 7 |
+
|
| 8 |
+
API_BASE_URL = os.getenv("API_BASE_URL", "https://openrouter.ai/api/v1")
|
| 9 |
+
MODEL_NAME = os.getenv("MODEL_NAME", "meta-llama/llama-3.1-8b-instruct:free")
|
| 10 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 11 |
+
MAX_STEPS = 10
|
| 12 |
+
SUCCESS_SCORE_THRESHOLD = 0.6
|
| 13 |
+
|
| 14 |
+
if not HF_TOKEN:
|
| 15 |
+
raise ValueError("HF_TOKEN is required")
|
| 16 |
+
|
| 17 |
+
def log_start(model):
|
| 18 |
+
print(f"[START] env=sql_env model={model}", flush=True)
|
| 19 |
+
|
| 20 |
+
def log_step(step, action, reward, done, error):
|
| 21 |
+
err = error if error else "null"
|
| 22 |
+
print(f"[STEP] step={step} action={repr(action)} reward={reward:.2f} done={str(done).lower()} error={err}", flush=True)
|
| 23 |
+
|
| 24 |
+
def log_end(success, steps, score, rewards):
|
| 25 |
+
r_str = ",".join(f"{r:.2f}" for r in rewards)
|
| 26 |
+
print(f"[END] success={str(success).lower()} steps={steps} score={score:.2f} rewards={r_str}", flush=True)
|
| 27 |
+
|
| 28 |
+
def get_model_query(client, last_output: str, history: List[str]) -> SqlAction:
|
| 29 |
+
history_str = "\n".join(history[-4:]) if history else "None"
|
| 30 |
+
prompt = f"""You are an expert SQL developer working with a SQLite database.
|
| 31 |
+
|
| 32 |
+
The database has these tables:
|
| 33 |
+
- employees (id, name, department, salary)
|
| 34 |
+
- departments (id, name, budget)
|
| 35 |
+
|
| 36 |
+
LAST OUTPUT:
|
| 37 |
+
{last_output}
|
| 38 |
+
|
| 39 |
+
RECENT HISTORY:
|
| 40 |
+
{history_str}
|
| 41 |
+
|
| 42 |
+
Instructions:
|
| 43 |
+
- Write a single valid SQLite SQL query
|
| 44 |
+
- Reply with ONLY one line:
|
| 45 |
+
QUERY: <your sql here>
|
| 46 |
+
"""
|
| 47 |
+
try:
|
| 48 |
+
completion = client.chat.completions.create(
|
| 49 |
+
model=MODEL_NAME,
|
| 50 |
+
messages=[{"role": "user", "content": prompt}],
|
| 51 |
+
max_tokens=200
|
| 52 |
+
)
|
| 53 |
+
text = completion.choices[0].message.content.strip()
|
| 54 |
+
lines = {l.split(":")[0].strip(): ":".join(l.split(":")[1:]).strip()
|
| 55 |
+
for l in text.splitlines() if ":" in l}
|
| 56 |
+
query = lines.get("QUERY", "SELECT * FROM employees")
|
| 57 |
+
return SqlAction(query=query)
|
| 58 |
+
except Exception as e:
|
| 59 |
+
print(f"[DEBUG] LLM error: {e}", flush=True)
|
| 60 |
+
return SqlAction(query="SELECT * FROM employees")
|
| 61 |
+
|
| 62 |
+
async def main():
|
| 63 |
+
client = OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)
|
| 64 |
+
env = SqlEnvironment()
|
| 65 |
+
|
| 66 |
+
rewards: List[float] = []
|
| 67 |
+
history: List[str] = []
|
| 68 |
+
steps_taken = 0
|
| 69 |
+
score = 0.0
|
| 70 |
+
success = False
|
| 71 |
+
|
| 72 |
+
log_start(model=MODEL_NAME)
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
obs = env.reset()
|
| 76 |
+
last_output = obs.echoed_message
|
| 77 |
+
|
| 78 |
+
for step in range(1, MAX_STEPS + 1):
|
| 79 |
+
action = get_model_query(client, last_output, history)
|
| 80 |
+
obs = env.step(action)
|
| 81 |
+
|
| 82 |
+
metadata = obs.metadata or {}
|
| 83 |
+
reward = metadata.get("reward", 0.0)
|
| 84 |
+
error = metadata.get("error", None)
|
| 85 |
+
done = False # extend with your own done condition
|
| 86 |
+
|
| 87 |
+
rewards.append(reward)
|
| 88 |
+
steps_taken = step
|
| 89 |
+
last_output = obs.echoed_message
|
| 90 |
+
history.append(f"Step {step}: {action.query[:80]} → reward {reward:.2f}")
|
| 91 |
+
|
| 92 |
+
log_step(step=step, action=action.query[:100],
|
| 93 |
+
reward=reward, done=done, error=error)
|
| 94 |
+
|
| 95 |
+
if done:
|
| 96 |
+
break
|
| 97 |
+
|
| 98 |
+
score = sum(rewards) / max(len(rewards), 1)
|
| 99 |
+
score = min(max(score, 0.0), 1.0)
|
| 100 |
+
success = score >= SUCCESS_SCORE_THRESHOLD
|
| 101 |
+
|
| 102 |
+
finally:
|
| 103 |
+
log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
|
| 104 |
+
|
| 105 |
+
if __name__ == "__main__":
|
| 106 |
+
asyncio.run(main())
|