Spaces:
Runtime error
Runtime error
Update app_core.py
Browse files- app_core.py +65 -64
app_core.py
CHANGED
@@ -1,90 +1,91 @@
|
|
1 |
import os
|
2 |
-
import requests
|
3 |
import json
|
|
|
4 |
from openai import OpenAI
|
5 |
from agent_tools import TOOLS_MAPPING
|
6 |
|
7 |
|
8 |
class CustomAgent:
|
9 |
def __init__(self):
|
10 |
-
print("[
|
|
|
|
|
|
|
|
|
|
|
11 |
self.client = OpenAI(
|
12 |
base_url="https://openrouter.ai/api/v1",
|
13 |
-
api_key=
|
14 |
)
|
15 |
|
16 |
-
def run(self,
|
17 |
-
print(f"[
|
18 |
|
19 |
-
|
20 |
-
|
21 |
-
"
|
22 |
-
"Only return the FINAL ANSWER using digits or plain words, as requested. "
|
23 |
-
"Avoid explanations, symbols, or extra text."
|
24 |
)
|
25 |
|
26 |
-
#
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
llm_response.raise_for_status()
|
35 |
-
pre_answer = llm_response.json().get("answer", "")
|
36 |
-
except Exception as e:
|
37 |
-
print(f"[Error] Failed to get reasoning: {e}")
|
38 |
-
pre_answer = ""
|
39 |
-
|
40 |
-
system_message += f"\n\nLLM helper result: {pre_answer}"
|
41 |
-
|
42 |
-
messages = [
|
43 |
-
{"role": "system", "content": system_message},
|
44 |
-
{"role": "user", "content": [{"type": "text", "text": question}]}
|
45 |
]
|
46 |
|
47 |
-
|
48 |
-
for _ in range(3):
|
49 |
try:
|
50 |
-
print("[
|
51 |
-
|
52 |
model="microsoft/mai-ds-r1:free",
|
53 |
-
messages=
|
54 |
temperature=0.0,
|
55 |
max_tokens=2048,
|
56 |
extra_headers={
|
57 |
-
"HTTP-Referer": "
|
58 |
-
"X-Title": "
|
59 |
-
}
|
60 |
-
)
|
61 |
-
|
62 |
-
response_msg = completion.choices[0].message
|
63 |
-
messages.append(response_msg)
|
64 |
-
|
65 |
-
# If final content is available, return it
|
66 |
-
if response_msg.tool_calls is None:
|
67 |
-
answer = response_msg.content or "Unable to generate response."
|
68 |
-
print(f"[Answer] {answer}")
|
69 |
-
return answer
|
70 |
-
|
71 |
-
# Handle any tool calls
|
72 |
-
for tool_call in response_msg.tool_calls:
|
73 |
-
func_name = tool_call.function.name
|
74 |
-
func_args = json.loads(tool_call.function.arguments)
|
75 |
-
tool_response = TOOLS_MAPPING[func_name](**func_args)
|
76 |
-
|
77 |
-
tool_msg = {
|
78 |
-
"role": "tool",
|
79 |
-
"tool_call_id": tool_call.id,
|
80 |
-
"name": func_name,
|
81 |
-
"content": json.dumps(tool_response),
|
82 |
}
|
|
|
83 |
|
84 |
-
|
85 |
|
86 |
-
|
87 |
-
|
88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
-
|
|
|
|
|
|
|
|
1 |
import os
|
|
|
2 |
import json
|
3 |
+
import requests
|
4 |
from openai import OpenAI
|
5 |
from agent_tools import TOOLS_MAPPING
|
6 |
|
7 |
|
8 |
class CustomAgent:
|
9 |
def __init__(self):
|
10 |
+
print("[CustomAgent] Starting up...")
|
11 |
+
|
12 |
+
token = os.getenv("OR_TOKEN")
|
13 |
+
if not token:
|
14 |
+
raise RuntimeError("Missing OpenRouter token. Set OR_TOKEN environment variable.")
|
15 |
+
|
16 |
self.client = OpenAI(
|
17 |
base_url="https://openrouter.ai/api/v1",
|
18 |
+
api_key=token
|
19 |
)
|
20 |
|
21 |
+
def run(self, prompt: str) -> str:
|
22 |
+
print(f"[Agent] Received prompt: {prompt}")
|
23 |
|
24 |
+
instructions = (
|
25 |
+
"You're solving a quiz. Only return the final result. "
|
26 |
+
"Use numbers or minimal text as requested. Avoid extra formatting or explanations."
|
|
|
|
|
27 |
)
|
28 |
|
29 |
+
# Optional reasoning helper
|
30 |
+
context_info = self._retrieve_helper_response(prompt)
|
31 |
+
if context_info:
|
32 |
+
instructions += f"\n\nBackground reference: {context_info}"
|
33 |
+
|
34 |
+
dialogue = [
|
35 |
+
{"role": "system", "content": instructions},
|
36 |
+
{"role": "user", "content": [{"type": "text", "text": prompt}]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
]
|
38 |
|
39 |
+
for attempt in range(3):
|
|
|
40 |
try:
|
41 |
+
print(f"[Agent] Attempt {attempt + 1}: requesting response...")
|
42 |
+
reply = self.client.chat.completions.create(
|
43 |
model="microsoft/mai-ds-r1:free",
|
44 |
+
messages=dialogue,
|
45 |
temperature=0.0,
|
46 |
max_tokens=2048,
|
47 |
extra_headers={
|
48 |
+
"HTTP-Referer": "https://your-app.example.com",
|
49 |
+
"X-Title": "quiz-agent"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
}
|
51 |
+
).choices[0].message
|
52 |
|
53 |
+
dialogue.append(reply)
|
54 |
|
55 |
+
if reply.tool_calls is None:
|
56 |
+
return reply.content.strip() if reply.content else "No response produced."
|
57 |
+
|
58 |
+
for tool_call in reply.tool_calls:
|
59 |
+
tool_name = tool_call.function.name
|
60 |
+
tool_input = json.loads(tool_call.function.arguments)
|
61 |
+
|
62 |
+
if tool_name in TOOLS_MAPPING:
|
63 |
+
result = TOOLS_MAPPING[tool_name](**tool_input)
|
64 |
+
dialogue.append({
|
65 |
+
"role": "tool",
|
66 |
+
"tool_call_id": tool_call.id,
|
67 |
+
"name": tool_name,
|
68 |
+
"content": json.dumps(result)
|
69 |
+
})
|
70 |
+
|
71 |
+
except Exception as err:
|
72 |
+
print(f"[Error] Attempt {attempt + 1} failed: {err}")
|
73 |
+
|
74 |
+
return "Agent could not produce a valid response after multiple attempts."
|
75 |
+
|
76 |
+
def _retrieve_helper_response(self, query: str) -> str:
|
77 |
+
"""Optionally enhance context by querying a helper LLM."""
|
78 |
+
helper_url = os.getenv("REASONING_API", "http://localhost:8004/ask")
|
79 |
+
|
80 |
+
try:
|
81 |
+
payload = {
|
82 |
+
"question": f"Question: {query}\n\n1. Break into parts.\n2. Answer.\n3. Give final result."
|
83 |
+
}
|
84 |
+
headers = {"Content-Type": "application/json"}
|
85 |
+
response = requests.post(helper_url, json=payload, headers=headers, timeout=30)
|
86 |
+
response.raise_for_status()
|
87 |
|
88 |
+
return response.json().get("answer", "")
|
89 |
+
except Exception as ex:
|
90 |
+
print(f"[Helper] Failed to retrieve context: {ex}")
|
91 |
+
return ""
|