Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,29 +7,34 @@ try:
|
|
| 7 |
except Exception:
|
| 8 |
HfApiModel = None
|
| 9 |
|
| 10 |
-
|
|
|
|
| 11 |
def get_model(prefer_openai=True):
|
| 12 |
"""
|
| 13 |
-
|
| 14 |
-
|
|
|
|
|
|
|
| 15 |
"""
|
| 16 |
last_error = None
|
| 17 |
if prefer_openai and os.getenv("OPENAI_API_KEY"):
|
| 18 |
-
model_id = os.getenv("OPENAI_MODEL", "gpt-
|
| 19 |
try:
|
| 20 |
return LiteLLMModel(
|
| 21 |
model_id=model_id,
|
| 22 |
api_key=os.getenv("OPENAI_API_KEY"),
|
| 23 |
-
base_url=os.getenv("OPENAI_BASE_URL")
|
|
|
|
| 24 |
)
|
| 25 |
except Exception as e:
|
| 26 |
last_error = f"OpenAI model init failed for '{model_id}': {e}"
|
| 27 |
-
#
|
| 28 |
try:
|
| 29 |
return LiteLLMModel(
|
| 30 |
model_id="gpt-4o-mini",
|
| 31 |
api_key=os.getenv("OPENAI_API_KEY"),
|
| 32 |
-
base_url=os.getenv("OPENAI_BASE_URL")
|
|
|
|
| 33 |
)
|
| 34 |
except Exception as e2:
|
| 35 |
last_error += f" | Fallback gpt-4o-mini failed: {e2}"
|
|
@@ -42,10 +47,15 @@ def get_model(prefer_openai=True):
|
|
| 42 |
|
| 43 |
raise RuntimeError(last_error or "No model available. Set OPENAI_API_KEY or HF_MODEL in Space secrets.")
|
| 44 |
|
|
|
|
|
|
|
| 45 |
def diag_openai_ping(prompt="Say 'pong' and nothing else."):
|
| 46 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 47 |
try:
|
| 48 |
-
model = get_model(prefer_openai=True)
|
| 49 |
|
| 50 |
@tool
|
| 51 |
def echo_tool(x: str) -> str:
|
|
@@ -61,16 +71,17 @@ def diag_openai_ping(prompt="Say 'pong' and nothing else."):
|
|
| 61 |
tools=[echo_tool],
|
| 62 |
model=model,
|
| 63 |
add_base_tools=False,
|
|
|
|
| 64 |
)
|
| 65 |
-
|
| 66 |
-
|
|
|
|
| 67 |
return f"β
OpenAI ping ok.\nModel: {getattr(model, 'model_id', 'unknown')}\nOutput: {out}"
|
| 68 |
except Exception:
|
| 69 |
return "β OpenAI ping failed:\n" + traceback.format_exc()
|
| 70 |
|
| 71 |
-
|
| 72 |
-
# Exercise 1
|
| 73 |
-
# =======================================
|
| 74 |
@tool
|
| 75 |
def add(a: float, b: float) -> float:
|
| 76 |
"""Add two numbers.
|
|
@@ -110,9 +121,8 @@ def run_ex1():
|
|
| 110 |
except Exception:
|
| 111 |
return "β Exercise 1 error:\n" + traceback.format_exc()
|
| 112 |
|
| 113 |
-
|
| 114 |
-
# Exercise 2
|
| 115 |
-
# =======================================
|
| 116 |
def run_ex2():
|
| 117 |
try:
|
| 118 |
agent = CodeAgent(
|
|
@@ -133,9 +143,8 @@ def run_ex2():
|
|
| 133 |
except Exception:
|
| 134 |
return "β Exercise 2 error:\n" + traceback.format_exc()
|
| 135 |
|
| 136 |
-
|
| 137 |
-
# Exercise 3
|
| 138 |
-
# =======================================
|
| 139 |
@tool
|
| 140 |
def validate_pr(pr: dict) -> dict:
|
| 141 |
"""Validate basic PR fields and structure.
|
|
@@ -188,8 +197,9 @@ DEFAULT_PR = json.dumps({
|
|
| 188 |
}, indent=2)
|
| 189 |
|
| 190 |
def run_ex3(pr_text):
|
|
|
|
| 191 |
try:
|
| 192 |
-
|
| 193 |
except Exception as e:
|
| 194 |
return f"Invalid JSON: {e}"
|
| 195 |
try:
|
|
@@ -204,17 +214,21 @@ def run_ex3(pr_text):
|
|
| 204 |
"1) validate_pr(pr). If ok==false, PRINT ONLY {\"error\": errors}.\n"
|
| 205 |
"2) If ok==true, call create_po(pr).\n"
|
| 206 |
"3) PRINT ONLY the resulting PO JSON. No extra text.\n"
|
| 207 |
-
"
|
|
|
|
|
|
|
| 208 |
)
|
| 209 |
-
out = agent.run(goal
|
| 210 |
return str(out)
|
| 211 |
except Exception:
|
| 212 |
return "β Exercise 3 error:\n" + traceback.format_exc()
|
| 213 |
|
|
|
|
| 214 |
# --------------------- Gradio UI ---------------------
|
| 215 |
with gr.Blocks(title="Smolagents Beginner Lab (Online)") as demo:
|
| 216 |
gr.Markdown("# Smolagents Beginner Lab (Online)")
|
| 217 |
-
gr.Markdown("Set `OPENAI_API_KEY` in Space secrets
|
|
|
|
| 218 |
|
| 219 |
with gr.Tab("Diagnostics"):
|
| 220 |
ping_btn = gr.Button("Run OpenAI ping test")
|
|
|
|
| 7 |
except Exception:
|
| 8 |
HfApiModel = None
|
| 9 |
|
| 10 |
+
|
| 11 |
+
# --------- Model factory (latest-compatible) ----------
|
| 12 |
def get_model(prefer_openai=True):
|
| 13 |
"""
|
| 14 |
+
Pick an LLM for the agent.
|
| 15 |
+
- Prefer OpenAI via LiteLLM if OPENAI_API_KEY is set.
|
| 16 |
+
- Else fall back to Hugging Face Inference (HF_MODEL).
|
| 17 |
+
NOTE: Temperature is set on the *model* in current smolagents.
|
| 18 |
"""
|
| 19 |
last_error = None
|
| 20 |
if prefer_openai and os.getenv("OPENAI_API_KEY"):
|
| 21 |
+
model_id = os.getenv("OPENAI_MODEL", "gpt-4o-mini") # safer default than gpt-5
|
| 22 |
try:
|
| 23 |
return LiteLLMModel(
|
| 24 |
model_id=model_id,
|
| 25 |
api_key=os.getenv("OPENAI_API_KEY"),
|
| 26 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 27 |
+
temperature=0 # determinism for orchestration
|
| 28 |
)
|
| 29 |
except Exception as e:
|
| 30 |
last_error = f"OpenAI model init failed for '{model_id}': {e}"
|
| 31 |
+
# one more fallback attempt
|
| 32 |
try:
|
| 33 |
return LiteLLMModel(
|
| 34 |
model_id="gpt-4o-mini",
|
| 35 |
api_key=os.getenv("OPENAI_API_KEY"),
|
| 36 |
+
base_url=os.getenv("OPENAI_BASE_URL"),
|
| 37 |
+
temperature=0
|
| 38 |
)
|
| 39 |
except Exception as e2:
|
| 40 |
last_error += f" | Fallback gpt-4o-mini failed: {e2}"
|
|
|
|
| 47 |
|
| 48 |
raise RuntimeError(last_error or "No model available. Set OPENAI_API_KEY or HF_MODEL in Space secrets.")
|
| 49 |
|
| 50 |
+
|
| 51 |
+
# --------------- Diagnostics (OpenAI ping) ---------------
|
| 52 |
def diag_openai_ping(prompt="Say 'pong' and nothing else."):
|
| 53 |
+
"""
|
| 54 |
+
Quick connectivity test to your OpenAI key/model.
|
| 55 |
+
Newer smolagents: no system_prompt arg; put instructions in the goal text.
|
| 56 |
+
"""
|
| 57 |
try:
|
| 58 |
+
model = get_model(prefer_openai=True)
|
| 59 |
|
| 60 |
@tool
|
| 61 |
def echo_tool(x: str) -> str:
|
|
|
|
| 71 |
tools=[echo_tool],
|
| 72 |
model=model,
|
| 73 |
add_base_tools=False,
|
| 74 |
+
# no temperature or system_prompt here (unsupported on latest agent ctor)
|
| 75 |
)
|
| 76 |
+
|
| 77 |
+
goal = "Reply with the user message verbatim. No extra words.\nMessage: " + prompt
|
| 78 |
+
out = agent.run(goal)
|
| 79 |
return f"β
OpenAI ping ok.\nModel: {getattr(model, 'model_id', 'unknown')}\nOutput: {out}"
|
| 80 |
except Exception:
|
| 81 |
return "β OpenAI ping failed:\n" + traceback.format_exc()
|
| 82 |
|
| 83 |
+
|
| 84 |
+
# ===================== Exercise 1 =====================
|
|
|
|
| 85 |
@tool
|
| 86 |
def add(a: float, b: float) -> float:
|
| 87 |
"""Add two numbers.
|
|
|
|
| 121 |
except Exception:
|
| 122 |
return "β Exercise 1 error:\n" + traceback.format_exc()
|
| 123 |
|
| 124 |
+
|
| 125 |
+
# ===================== Exercise 2 =====================
|
|
|
|
| 126 |
def run_ex2():
|
| 127 |
try:
|
| 128 |
agent = CodeAgent(
|
|
|
|
| 143 |
except Exception:
|
| 144 |
return "β Exercise 2 error:\n" + traceback.format_exc()
|
| 145 |
|
| 146 |
+
|
| 147 |
+
# ===================== Exercise 3 =====================
|
|
|
|
| 148 |
@tool
|
| 149 |
def validate_pr(pr: dict) -> dict:
|
| 150 |
"""Validate basic PR fields and structure.
|
|
|
|
| 197 |
}, indent=2)
|
| 198 |
|
| 199 |
def run_ex3(pr_text):
|
| 200 |
+
# Validate JSON, then inline into goal (latest run() has no additional_context kw)
|
| 201 |
try:
|
| 202 |
+
_ = json.loads(pr_text)
|
| 203 |
except Exception as e:
|
| 204 |
return f"Invalid JSON: {e}"
|
| 205 |
try:
|
|
|
|
| 214 |
"1) validate_pr(pr). If ok==false, PRINT ONLY {\"error\": errors}.\n"
|
| 215 |
"2) If ok==true, call create_po(pr).\n"
|
| 216 |
"3) PRINT ONLY the resulting PO JSON. No extra text.\n"
|
| 217 |
+
"The PR object you must operate on is provided below as JSON. "
|
| 218 |
+
"Parse it into a Python dict variable named `pr` before calling tools.\n\n"
|
| 219 |
+
"PR JSON:\n```json\n" + pr_text + "\n```\n"
|
| 220 |
)
|
| 221 |
+
out = agent.run(goal)
|
| 222 |
return str(out)
|
| 223 |
except Exception:
|
| 224 |
return "β Exercise 3 error:\n" + traceback.format_exc()
|
| 225 |
|
| 226 |
+
|
| 227 |
# --------------------- Gradio UI ---------------------
|
| 228 |
with gr.Blocks(title="Smolagents Beginner Lab (Online)") as demo:
|
| 229 |
gr.Markdown("# Smolagents Beginner Lab (Online)")
|
| 230 |
+
gr.Markdown("Set `OPENAI_API_KEY` in Space secrets (recommended). Optional: `OPENAI_MODEL` (e.g., gpt-4o-mini). "
|
| 231 |
+
"Fallback: set `HF_MODEL` (e.g., Qwen/Qwen2.5-7B-Instruct).")
|
| 232 |
|
| 233 |
with gr.Tab("Diagnostics"):
|
| 234 |
ping_btn = gr.Button("Run OpenAI ping test")
|