Spaces:
No application file
No application file
Create ai_agent.py
Browse files- ai_agent.py +68 -0
ai_agent.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from dotenv import load_dotenv
|
2 |
+
load_dotenv()
|
3 |
+
|
4 |
+
import os
|
5 |
+
from langchain_groq import ChatGroq
|
6 |
+
from langchain_community.tools.tavily_search import TavilySearchResults
|
7 |
+
from langgraph.prebuilt import create_react_agent
|
8 |
+
from langchain_core.messages import HumanMessage, SystemMessage, AIMessage
|
9 |
+
|
10 |
+
def get_response_from_ai_agent(llm_id, query, allow_search, system_prompt):
|
11 |
+
"""
|
12 |
+
Create and invoke an AI agent with optional search capabilities
|
13 |
+
"""
|
14 |
+
try:
|
15 |
+
# Initialize LLM with proper configuration
|
16 |
+
llm = ChatGroq(
|
17 |
+
api_key=os.environ.get("GROQ_API_KEY"),
|
18 |
+
model_name=llm_id
|
19 |
+
)
|
20 |
+
|
21 |
+
# Setup tools based on allow_search flag
|
22 |
+
tools = []
|
23 |
+
if allow_search:
|
24 |
+
tools.append(TavilySearchResults(
|
25 |
+
api_key=os.environ.get("TAVILY_API_KEY"),
|
26 |
+
max_results=2
|
27 |
+
))
|
28 |
+
|
29 |
+
# Create the agent
|
30 |
+
agent = create_react_agent(
|
31 |
+
model=llm,
|
32 |
+
tools=tools
|
33 |
+
)
|
34 |
+
|
35 |
+
# Prepare the initial messages
|
36 |
+
initial_messages = [
|
37 |
+
SystemMessage(content=system_prompt),
|
38 |
+
HumanMessage(content=query)
|
39 |
+
]
|
40 |
+
|
41 |
+
# Create proper state with messages
|
42 |
+
state = {
|
43 |
+
"messages": initial_messages,
|
44 |
+
"next_steps": [],
|
45 |
+
"structured_response": None
|
46 |
+
}
|
47 |
+
|
48 |
+
# Invoke agent with proper state
|
49 |
+
response = agent.invoke(state)
|
50 |
+
|
51 |
+
# Handle response
|
52 |
+
if isinstance(response, dict):
|
53 |
+
# Extract messages from response
|
54 |
+
if "messages" in response:
|
55 |
+
messages = response["messages"]
|
56 |
+
# Get the last AI message
|
57 |
+
ai_messages = [msg for msg in messages if isinstance(msg, AIMessage)]
|
58 |
+
if ai_messages:
|
59 |
+
return ai_messages[-1].content
|
60 |
+
# Check structured response
|
61 |
+
elif "structured_response" in response:
|
62 |
+
return response["structured_response"]
|
63 |
+
|
64 |
+
return "I apologize, but I couldn't generate a proper response. Please try again."
|
65 |
+
|
66 |
+
except Exception as e:
|
67 |
+
print(f"Debug - Error in get_response_from_ai_agent: {str(e)}")
|
68 |
+
raise Exception(f"Agent error: {str(e)}")
|