Spaces:
No application file
No application file
Update app.py
Browse files
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 |
-
|
| 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 |
-
#
|
| 96 |
-
|
| 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.
|
| 232 |
model=LLM_MODEL,
|
| 233 |
messages=messages,
|
| 234 |
-
|
| 235 |
-
|
| 236 |
)
|
| 237 |
response_message = response.choices[0].message
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
messages.append(response_message)
|
| 239 |
|
| 240 |
-
if response_message.
|
| 241 |
self._log_step("🛠️ Assistant decided to use tools:")
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 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
|
| 310 |
-
global_agent = AIAgent(openai_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 |
|