GoodLuckChuck commited on
Commit
0848077
·
verified ·
1 Parent(s): a04b35d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -15
app.py CHANGED
@@ -15,7 +15,6 @@ from fastapi.middleware.cors import CORSMiddleware
15
  import os
16
  import pandas as pd
17
  import openai
18
- from openai import OpenAI
19
 
20
  # Configure logging
21
  logging.basicConfig(
@@ -148,8 +147,8 @@ class LocalSearch(Tool):
148
 
149
  class ImprovedAgent:
150
  """Enhanced GAIA agent implementation"""
151
- def __init__(self, openai_client, tools: List[Tool]):
152
- self.client = openai_client
153
  self.tools = {tool.name: tool for tool in tools}
154
  self.state = AgentState()
155
  self._executor = ThreadPoolExecutor(max_workers=3)
@@ -226,7 +225,7 @@ FINAL ANSWER: [Your conclusive answer]"""
226
  async def _get_model_response(self, context: str) -> str:
227
  """Get the model's response using GPT-4"""
228
  try:
229
- response = self.client.chat.completions.create(
230
  model="gpt-4",
231
  messages=[
232
  {"role": "system", "content": self.system_prompt},
@@ -235,7 +234,7 @@ FINAL ANSWER: [Your conclusive answer]"""
235
  temperature=0.1,
236
  max_tokens=1000
237
  )
238
- return response.choices[0].message.content
239
  except Exception as e:
240
  logger.error(f"Error getting model response: {e}")
241
  return ""
@@ -339,13 +338,13 @@ FINAL ANSWER: [Your conclusive answer]"""
339
 
340
  return final_answer
341
 
342
- def create_agent(model, knowledge_base_path: Path) -> ImprovedAgent:
343
  """Factory function to create a configured agent"""
344
  tools = [
345
  Calculator(),
346
  LocalSearch(knowledge_base_path)
347
  ]
348
- return ImprovedAgent(model, tools)
349
 
350
  # Add after the create_agent function
351
  app = FastAPI(title="Improved GAIA Agent API")
@@ -359,7 +358,6 @@ app.add_middleware(
359
  )
360
 
361
  # Initialize OpenAI client and agent globally
362
- client = None
363
  agent = None
364
  try:
365
  # Get API key from environment (HF Secrets)
@@ -367,21 +365,22 @@ try:
367
  if not api_key:
368
  raise ValueError("OPENAI_API_KEY not found in environment variables")
369
 
370
- client = OpenAI(api_key=api_key)
371
- knowledge_base_path = Path(__file__).parent / "knowledge_base"
372
 
373
  # Test the API key
374
- test_response = client.chat.completions.create(
375
  model="gpt-4",
376
  messages=[{"role": "user", "content": "test"}],
377
  max_tokens=5
378
  )
379
- print("OpenAI client initialized successfully with GPT-4")
380
 
381
- # Create agent with OpenAI client
382
- agent = create_agent(client, knowledge_base_path)
 
383
  except Exception as e:
384
- print(f"Error initializing OpenAI client or agent: {e}")
385
 
386
  def run_and_submit_all(profile: gr.OAuthProfile | None):
387
  """Process questions and submit answers"""
 
15
  import os
16
  import pandas as pd
17
  import openai
 
18
 
19
  # Configure logging
20
  logging.basicConfig(
 
147
 
148
  class ImprovedAgent:
149
  """Enhanced GAIA agent implementation"""
150
+ def __init__(self, openai_module, tools: List[Tool]):
151
+ self.openai = openai_module
152
  self.tools = {tool.name: tool for tool in tools}
153
  self.state = AgentState()
154
  self._executor = ThreadPoolExecutor(max_workers=3)
 
225
  async def _get_model_response(self, context: str) -> str:
226
  """Get the model's response using GPT-4"""
227
  try:
228
+ response = self.openai.ChatCompletion.create(
229
  model="gpt-4",
230
  messages=[
231
  {"role": "system", "content": self.system_prompt},
 
234
  temperature=0.1,
235
  max_tokens=1000
236
  )
237
+ return response.choices[0].message['content']
238
  except Exception as e:
239
  logger.error(f"Error getting model response: {e}")
240
  return ""
 
338
 
339
  return final_answer
340
 
341
+ def create_agent(openai_module, knowledge_base_path: Path) -> ImprovedAgent:
342
  """Factory function to create a configured agent"""
343
  tools = [
344
  Calculator(),
345
  LocalSearch(knowledge_base_path)
346
  ]
347
+ return ImprovedAgent(openai_module, tools)
348
 
349
  # Add after the create_agent function
350
  app = FastAPI(title="Improved GAIA Agent API")
 
358
  )
359
 
360
  # Initialize OpenAI client and agent globally
 
361
  agent = None
362
  try:
363
  # Get API key from environment (HF Secrets)
 
365
  if not api_key:
366
  raise ValueError("OPENAI_API_KEY not found in environment variables")
367
 
368
+ # Configure OpenAI
369
+ openai.api_key = api_key
370
 
371
  # Test the API key
372
+ test_response = openai.ChatCompletion.create(
373
  model="gpt-4",
374
  messages=[{"role": "user", "content": "test"}],
375
  max_tokens=5
376
  )
377
+ print("OpenAI initialized successfully with GPT-4")
378
 
379
+ # Create agent
380
+ knowledge_base_path = Path(__file__).parent / "knowledge_base"
381
+ agent = create_agent(openai, knowledge_base_path)
382
  except Exception as e:
383
+ print(f"Error initializing OpenAI or agent: {e}")
384
 
385
  def run_and_submit_all(profile: gr.OAuthProfile | None):
386
  """Process questions and submit answers"""