i-dhilip commited on
Commit
30a99e4
·
verified ·
1 Parent(s): 740269f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -10
app.py CHANGED
@@ -2,6 +2,8 @@ import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
 
 
5
  from dotenv import load_dotenv
6
  from typing import List, Dict, Any, Optional
7
 
@@ -24,28 +26,54 @@ class MessagesState(TypedDict):
24
  try:
25
  with open("system_prompt.txt", "r", encoding="utf-8") as f:
26
  system_prompt = f.read()
 
27
  except FileNotFoundError:
28
  system_prompt = (
29
  "You are a helpful AI assistant that uses tools to find information and answer questions.\n"
30
  "When you don't know something, use the available tools to look up information. Be concise, direct, and provide accurate responses.\n"
31
  "Always cite your sources when using information from searches or reference materials."
32
  )
 
33
 
34
  class AdvancedAgent:
35
  def __init__(self):
36
- print("Initializing AdvancedAgent with LangGraph, Wikipedia, Arxiv, and Gemini 2.0 Flash")
37
  load_dotenv()
38
- self.graph = self.build_graph()
39
- print("Graph successfully built")
 
 
 
 
 
 
 
 
 
 
 
40
 
41
  def build_graph(self):
 
 
 
 
 
 
 
 
 
 
 
 
42
  llm = ChatOpenAI(
43
- model="google/gemini-2.0-flash-001",
44
  temperature=0,
45
  openai_api_key=os.getenv("OPENROUTER_API_KEY"),
46
- openai_api_base="https://openrouter.ai/api/v1"
 
47
  )
48
- print("LLM initialized: Gemini 2.5 Pro via OpenRouter")
49
 
50
  wikipedia_tool = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())
51
  arxiv_tool = ArxivQueryRun()
@@ -86,29 +114,44 @@ class AdvancedAgent:
86
  SystemMessage(content=system_prompt),
87
  HumanMessage(content=question)
88
  ]
 
 
 
 
89
  try:
90
  # Initial state must be a dict with "messages" key!
 
91
  result = self.graph.invoke({"messages": messages})
 
 
92
  final_messages = result["messages"]
 
93
 
94
  # Extract only AI messages from the final state
95
  ai_messages = [msg for msg in final_messages if isinstance(msg, AIMessage)]
 
96
 
97
  if not ai_messages:
 
98
  return "I wasn't able to generate a proper response. Please try again."
99
 
100
  # Get the last AI message - this should be the final answer
101
  last_message = ai_messages[-1]
102
 
103
  # Return the content of the last AI message
104
- return last_message.content if last_message.content else "I wasn't able to generate a proper response. Please try again."
 
 
 
 
105
 
106
  except Exception as e:
107
  print(f"Error running agent graph: {e}")
 
108
  return f"Sorry, I encountered an error while processing your question: {str(e)}"
109
 
110
  def run_and_submit_all(profile: gr.OAuthProfile | None):
111
- space_id = os.getenv("SPACE_ID")
112
  if profile:
113
  username = f"{profile.username}"
114
  print(f"User logged in: {username}")
@@ -119,12 +162,31 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
119
  api_url = DEFAULT_API_URL
120
  questions_url = f"{api_url}/questions"
121
  submit_url = f"{api_url}/submit"
 
 
 
 
122
 
123
  try:
124
  agent = AdvancedAgent()
125
  except Exception as e:
126
- print(f"Error instantiating agent: {e}")
127
- return f"Error initializing agent: {e}", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
130
  print(agent_code)
 
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
+ import json
6
+ import traceback
7
  from dotenv import load_dotenv
8
  from typing import List, Dict, Any, Optional
9
 
 
26
  try:
27
  with open("system_prompt.txt", "r", encoding="utf-8") as f:
28
  system_prompt = f.read()
29
+ print("Successfully loaded system prompt from file")
30
  except FileNotFoundError:
31
  system_prompt = (
32
  "You are a helpful AI assistant that uses tools to find information and answer questions.\n"
33
  "When you don't know something, use the available tools to look up information. Be concise, direct, and provide accurate responses.\n"
34
  "Always cite your sources when using information from searches or reference materials."
35
  )
36
+ print("System prompt file not found, using default prompt")
37
 
38
  class AdvancedAgent:
39
  def __init__(self):
40
+ print("Initializing AdvancedAgent with LangGraph, Wikipedia, Arxiv, and LLM via OpenRouter")
41
  load_dotenv()
42
+
43
+ # Check if OpenRouter API key is set
44
+ if not os.getenv("OPENROUTER_API_KEY"):
45
+ print("WARNING: OPENROUTER_API_KEY environment variable not set!")
46
+ print("Please set this in your HF Space secrets or .env file")
47
+
48
+ try:
49
+ self.graph = self.build_graph()
50
+ print("Graph successfully built")
51
+ except Exception as e:
52
+ print(f"Error building agent graph: {e}")
53
+ traceback.print_exc()
54
+ raise
55
 
56
  def build_graph(self):
57
+ # Add consistent headers for OpenRouter
58
+ headers = {
59
+ "HTTP-Referer": "https://huggingface.co/",
60
+ "X-Title": "HF Agent"
61
+ }
62
+
63
+ try:
64
+ # Try alternative OpenAI model if Gemini is causing issues
65
+ model_name = "google/gemini-2.0-flash-001"
66
+ # Fallback to OpenAI if needed
67
+ # model_name = "gpt-3.5-turbo"
68
+
69
  llm = ChatOpenAI(
70
+ model=model_name,
71
  temperature=0,
72
  openai_api_key=os.getenv("OPENROUTER_API_KEY"),
73
+ openai_api_base="https://openrouter.ai/api/v1",
74
+ headers=headers
75
  )
76
+ print(f"LLM initialized: {model_name} via OpenRouter")
77
 
78
  wikipedia_tool = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())
79
  arxiv_tool = ArxivQueryRun()
 
114
  SystemMessage(content=system_prompt),
115
  HumanMessage(content=question)
116
  ]
117
+
118
+ # Print message details for debugging
119
+ print(f"Sending {len(messages)} messages to the LLM")
120
+
121
  try:
122
  # Initial state must be a dict with "messages" key!
123
+ print("Invoking agent graph...")
124
  result = self.graph.invoke({"messages": messages})
125
+ print("Agent graph execution completed")
126
+
127
  final_messages = result["messages"]
128
+ print(f"Got {len(final_messages)} messages in result")
129
 
130
  # Extract only AI messages from the final state
131
  ai_messages = [msg for msg in final_messages if isinstance(msg, AIMessage)]
132
+ print(f"Found {len(ai_messages)} AI messages in the final state")
133
 
134
  if not ai_messages:
135
+ print("No AI messages found in the final state")
136
  return "I wasn't able to generate a proper response. Please try again."
137
 
138
  # Get the last AI message - this should be the final answer
139
  last_message = ai_messages[-1]
140
 
141
  # Return the content of the last AI message
142
+ if last_message.content:
143
+ return last_message.content
144
+ else:
145
+ print("Last AI message has empty content")
146
+ return "I wasn't able to generate a proper response. Please try again."
147
 
148
  except Exception as e:
149
  print(f"Error running agent graph: {e}")
150
+ traceback.print_exc()
151
  return f"Sorry, I encountered an error while processing your question: {str(e)}"
152
 
153
  def run_and_submit_all(profile: gr.OAuthProfile | None):
154
+ space_id = os.getenv("SPACE_ID", "i-dhilip/Final_Assignment_Template") # Default to your space ID
155
  if profile:
156
  username = f"{profile.username}"
157
  print(f"User logged in: {username}")
 
162
  api_url = DEFAULT_API_URL
163
  questions_url = f"{api_url}/questions"
164
  submit_url = f"{api_url}/submit"
165
+
166
+ print(f"Checking OpenRouter API key...")
167
+ if not os.getenv("OPENROUTER_API_KEY"):
168
+ return "Error: OPENROUTER_API_KEY not set. Please add this to your Space secrets.", None
169
 
170
  try:
171
  agent = AdvancedAgent()
172
  except Exception as e:
173
+ error_msg = f"Error instantiating agent: {e}"
174
+ print(error_msg)
175
+ traceback.print_exc()
176
+ return error_msg, None
177
+
178
+ # Generate a simple test question to verify the agent works
179
+ test_question = "What is the capital of France?"
180
+ print(f"Testing agent with a simple question: '{test_question}'")
181
+ try:
182
+ test_response = agent(test_question)
183
+ print(f"Test response: {test_response[:100]}...")
184
+ if "I wasn't able to generate" in test_response or "error" in test_response.lower():
185
+ print("WARNING: Agent test response indicates potential issues")
186
+ except Exception as e:
187
+ print(f"Agent test failed: {e}")
188
+ traceback.print_exc()
189
+ return f"Agent test failed: {e}", None
190
 
191
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
192
  print(agent_code)