Nuriza01 commited on
Commit
74adede
·
verified ·
1 Parent(s): fb34449

Update app_core.py

Browse files
Files changed (1) hide show
  1. 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("[Init] CustomAgent initialized.")
 
 
 
 
 
11
  self.client = OpenAI(
12
  base_url="https://openrouter.ai/api/v1",
13
- api_key=os.getenv("OR_TOKEN")
14
  )
15
 
16
- def run(self, question: str) -> str:
17
- print(f"[Run] Question received: {question}")
18
 
19
- # Prepare system message
20
- system_message = (
21
- "You are taking a quiz. Follow instructions precisely. "
22
- "Only return the FINAL ANSWER using digits or plain words, as requested. "
23
- "Avoid explanations, symbols, or extra text."
24
  )
25
 
26
- # Call internal LLM to expand reasoning
27
- try:
28
- llm_response = requests.post(
29
- "http://localhost:8004/ask",
30
- headers={"Content-Type": "application/json"},
31
- json={"question": f"Question: {question}\n\n1. Break into sub-questions.\n2. Answer them.\n3. Return final answer."},
32
- timeout=60
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
- # Retry loop
48
- for _ in range(3):
49
  try:
50
- print("[Run] Querying OpenRouter model...")
51
- completion = self.client.chat.completions.create(
52
  model="microsoft/mai-ds-r1:free",
53
- messages=messages,
54
  temperature=0.0,
55
  max_tokens=2048,
56
  extra_headers={
57
- "HTTP-Referer": "<YOUR_SITE_URL>",
58
- "X-Title": "<YOUR_SITE_NAME>",
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
- messages.append(tool_msg)
85
 
86
- except Exception as e:
87
- print(f"[Error] Generation failed: {e}")
88
- return "I encountered an error while trying to answer the question."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
- return "Failed to generate a valid response after retries."
 
 
 
 
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 ""