GoodLuckChuck commited on
Commit
a6dfdae
·
verified ·
1 Parent(s): c3d7b0a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -34
app.py CHANGED
@@ -3,7 +3,7 @@ import json
3
  import requests
4
  from typing import List, Dict, Any, Optional
5
  from pydantic import BaseModel, Field
6
- from openai import OpenAI
7
  from dotenv import load_dotenv
8
  from fastapi import FastAPI, HTTPException
9
  from fastapi.middleware.cors import CORSMiddleware
@@ -92,13 +92,12 @@ try:
92
  if not OPENAI_API_KEY_VALUE:
93
  raise ValueError("OPENAI_API_KEY not found in environment variables")
94
 
95
- # Initialize OpenAI client with minimal configuration
96
- client = OpenAI(api_key=OPENAI_API_KEY_VALUE)
97
  print("OpenAI client initialized successfully.")
98
  except Exception as e:
99
  print(f"Error initializing OpenAI client: {str(e)}")
100
  print("Please ensure OPENAI_API_KEY is properly set in Hugging Face Space secrets")
101
- client = None
102
 
103
  LLM_MODEL = "gpt-3.5-turbo"
104
 
@@ -199,7 +198,7 @@ class AIAgent:
199
  if file_name:
200
  user_message_content += f" (Note: The file is located at '{file_name}')"
201
 
202
- if not self.client:
203
  self._log_step("ERROR: OpenAI client not initialized. Cannot process question.")
204
  return {
205
  "task_id": task_id,
@@ -228,42 +227,44 @@ class AIAgent:
228
  self._log_step(f"\nIteration {iteration + 1}")
229
  try:
230
  self._log_step("🤖 Assistant thinking...", {"current_messages_for_llm_count": len(messages)})
231
- response = self.client.chat.completions.create(
232
  model=LLM_MODEL,
233
  messages=messages,
234
- tools=self.tools_available,
235
- tool_choice="auto"
236
  )
237
  response_message = response.choices[0].message
 
 
 
 
238
  messages.append(response_message)
239
 
240
- if response_message.tool_calls:
241
  self._log_step("🛠️ Assistant decided to use tools:")
242
- for tool_call in response_message.tool_calls:
243
- function_name = tool_call.function.name
244
- function_args = json.loads(tool_call.function.arguments)
245
- self._log_step(f" - Tool: {function_name}, Args: {function_args}")
246
-
247
- if function_name in self.tool_executors:
248
- tool_output = self.tool_executors[function_name](function_args)
249
- self._log_step(f" ✔️ Tool Output ({function_name}): {tool_output}")
250
- messages.append({
251
- "tool_call_id": tool_call.id,
252
- "role": "tool",
253
- "name": function_name,
254
- "content": json.dumps(tool_output)
255
- })
256
- else:
257
- self._log_step(f" ⚠️ Error: Unknown tool '{function_name}'.")
258
- messages.append({
259
- "tool_call_id": tool_call.id,
260
- "role": "tool",
261
- "name": function_name,
262
- "content": json.dumps({"error": f"Tool {function_name} not found."})
263
- })
264
  else:
265
  self._log_step("✅ Assistant providing final answer (or thought process leading to it).")
266
- llm_final_content = response_message.content
267
  self._log_step("Raw LLM Final Content:\n" + "="*20 + f"\n{llm_final_content}\n" + "="*20)
268
 
269
  if "FINAL ANSWER:" in llm_final_content:
@@ -306,8 +307,8 @@ app.add_middleware(
306
  )
307
 
308
  # Initialize the AI Agent globally
309
- if OPENAI_API_KEY_VALUE and client:
310
- global_agent = AIAgent(openai_client=client)
311
  else:
312
  global_agent = None
313
 
 
3
  import requests
4
  from typing import List, Dict, Any, Optional
5
  from pydantic import BaseModel, Field
6
+ import openai
7
  from dotenv import load_dotenv
8
  from fastapi import FastAPI, HTTPException
9
  from fastapi.middleware.cors import CORSMiddleware
 
92
  if not OPENAI_API_KEY_VALUE:
93
  raise ValueError("OPENAI_API_KEY not found in environment variables")
94
 
95
+ # Set the API key for the older version syntax
96
+ openai.api_key = OPENAI_API_KEY_VALUE
97
  print("OpenAI client initialized successfully.")
98
  except Exception as e:
99
  print(f"Error initializing OpenAI client: {str(e)}")
100
  print("Please ensure OPENAI_API_KEY is properly set in Hugging Face Space secrets")
 
101
 
102
  LLM_MODEL = "gpt-3.5-turbo"
103
 
 
198
  if file_name:
199
  user_message_content += f" (Note: The file is located at '{file_name}')"
200
 
201
+ if not self.client.api_key:
202
  self._log_step("ERROR: OpenAI client not initialized. Cannot process question.")
203
  return {
204
  "task_id": task_id,
 
227
  self._log_step(f"\nIteration {iteration + 1}")
228
  try:
229
  self._log_step("🤖 Assistant thinking...", {"current_messages_for_llm_count": len(messages)})
230
+ response = self.client.ChatCompletion.create(
231
  model=LLM_MODEL,
232
  messages=messages,
233
+ functions=self.tools_available,
234
+ function_call="auto"
235
  )
236
  response_message = response.choices[0].message
237
+
238
+ # Convert the OpenAI response message to a dict for consistency
239
+ if hasattr(response_message, 'to_dict'):
240
+ response_message = response_message.to_dict()
241
  messages.append(response_message)
242
 
243
+ if response_message.get('function_call'):
244
  self._log_step("🛠️ Assistant decided to use tools:")
245
+ function_call = response_message['function_call']
246
+ function_name = function_call['name']
247
+ function_args = json.loads(function_call['arguments'])
248
+ self._log_step(f" - Tool: {function_name}, Args: {function_args}")
249
+
250
+ if function_name in self.tool_executors:
251
+ tool_output = self.tool_executors[function_name](function_args)
252
+ self._log_step(f" ✔️ Tool Output ({function_name}): {tool_output}")
253
+ messages.append({
254
+ "role": "function",
255
+ "name": function_name,
256
+ "content": json.dumps(tool_output)
257
+ })
258
+ else:
259
+ self._log_step(f" ⚠️ Error: Unknown tool '{function_name}'.")
260
+ messages.append({
261
+ "role": "function",
262
+ "name": function_name,
263
+ "content": json.dumps({"error": f"Tool {function_name} not found."})
264
+ })
 
 
265
  else:
266
  self._log_step("✅ Assistant providing final answer (or thought process leading to it).")
267
+ llm_final_content = response_message.get('content', '')
268
  self._log_step("Raw LLM Final Content:\n" + "="*20 + f"\n{llm_final_content}\n" + "="*20)
269
 
270
  if "FINAL ANSWER:" in llm_final_content:
 
307
  )
308
 
309
  # Initialize the AI Agent globally
310
+ if OPENAI_API_KEY_VALUE and openai.api_key:
311
+ global_agent = AIAgent(openai_client=openai)
312
  else:
313
  global_agent = None
314