Update agent.py
Browse files
agent.py
CHANGED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from langchain_openai import ChatOpenAI
|
2 |
+
from langchain.agents import AgentExecutor, create_openai_functions_agent
|
3 |
+
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
|
4 |
+
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
|
5 |
+
from langchain_community.chat_message_histories import ChatMessageHistory # For in-memory history if not using DB for agent turn
|
6 |
+
|
7 |
+
from tools import (
|
8 |
+
GeminiTool, UMLSLookupTool, BioPortalLookupTool, QuantumTreatmentOptimizerTool
|
9 |
+
)
|
10 |
+
from config.settings import settings
|
11 |
+
from services.logger import app_logger
|
12 |
+
|
13 |
+
# Initialize LLM
|
14 |
+
llm = ChatOpenAI(model="gpt-3.5-turbo-0125", temperature=0.2, openai_api_key=settings.OPENAI_API_KEY)
|
15 |
+
# If you have gpt-4 access and budget, it's generally better for agentic tasks:
|
16 |
+
# llm = ChatOpenAI(model="gpt-4-turbo-preview", temperature=0.2, openai_api_key=settings.OPENAI_API_KEY)
|
17 |
+
|
18 |
+
|
19 |
+
# Initialize Tools
|
20 |
+
tools = [
|
21 |
+
UMLSLookupTool(),
|
22 |
+
BioPortalLookupTool(),
|
23 |
+
QuantumTreatmentOptimizerTool(),
|
24 |
+
# GeminiTool(), # Add if you want the agent to be able to call Gemini as a sub-LLM.
|
25 |
+
# Be mindful of costs and latency.
|
26 |
+
]
|
27 |
+
|
28 |
+
# Agent Prompt
|
29 |
+
# You can pull a prompt from Langchain Hub or define your own
|
30 |
+
# e.g., prompt = hub.pull("hwchase17/openai-functions-agent")
|
31 |
+
prompt = ChatPromptTemplate.from_messages([
|
32 |
+
("system", (
|
33 |
+
"You are a helpful AI assistant for healthcare professionals, named 'Quantum Health Navigator'. "
|
34 |
+
"Your goal is to assist with medical information lookup, treatment optimization queries, and general medical Q&A. "
|
35 |
+
"When using tools, be precise with your inputs. "
|
36 |
+
"Always cite the tool you used if its output is part of your response. "
|
37 |
+
"If asked about treatment for a specific patient, you MUST use the 'quantum_treatment_optimizer' tool. "
|
38 |
+
"Do not provide medical advice directly without tool usage for specific patient cases. "
|
39 |
+
"For general medical knowledge, you can answer directly or use UMLS/BioPortal for definitions and codes."
|
40 |
+
)),
|
41 |
+
MessagesPlaceholder(variable_name="chat_history"),
|
42 |
+
("human", "{input}"),
|
43 |
+
MessagesPlaceholder(variable_name="agent_scratchpad"),
|
44 |
+
])
|
45 |
+
|
46 |
+
# Create Agent
|
47 |
+
# This agent is optimized for OpenAI function calling.
|
48 |
+
agent = create_openai_functions_agent(llm, tools, prompt)
|
49 |
+
|
50 |
+
# Create Agent Executor
|
51 |
+
agent_executor = AgentExecutor(
|
52 |
+
agent=agent,
|
53 |
+
tools=tools,
|
54 |
+
verbose=True, # Set to False in production if too noisy
|
55 |
+
handle_parsing_errors=True, # Gracefully handle errors if LLM output is not parsable
|
56 |
+
# max_iterations=5, # Prevent runaway agents
|
57 |
+
)
|
58 |
+
|
59 |
+
def get_agent_executor():
|
60 |
+
"""Returns the configured agent executor."""
|
61 |
+
if not settings.OPENAI_API_KEY:
|
62 |
+
app_logger.error("OPENAI_API_KEY not set. Agent will not function.")
|
63 |
+
raise ValueError("OpenAI API Key not configured. Agent cannot be initialized.")
|
64 |
+
return agent_executor
|
65 |
+
|
66 |
+
# Example usage (for testing, not part of Streamlit app directly here)
|
67 |
+
if __name__ == "__main__":
|
68 |
+
if not settings.OPENAI_API_KEY:
|
69 |
+
print("Please set your OPENAI_API_KEY in .env file.")
|
70 |
+
else:
|
71 |
+
executor = get_agent_executor()
|
72 |
+
chat_history = [] # In a real app, this comes from DB or session state
|
73 |
+
|
74 |
+
while True:
|
75 |
+
user_input = input("You: ")
|
76 |
+
if user_input.lower() in ["exit", "quit"]:
|
77 |
+
break
|
78 |
+
|
79 |
+
# Convert simple list history to LangChain Message objects for the agent
|
80 |
+
langchain_chat_history = []
|
81 |
+
for role, content in chat_history:
|
82 |
+
if role == "user":
|
83 |
+
langchain_chat_history.append(HumanMessage(content=content))
|
84 |
+
elif role == "assistant":
|
85 |
+
langchain_chat_history.append(AIMessage(content=content))
|
86 |
+
|
87 |
+
response = executor.invoke({
|
88 |
+
"input": user_input,
|
89 |
+
"chat_history": langchain_chat_history
|
90 |
+
})
|
91 |
+
|
92 |
+
print(f"Agent: {response['output']}")
|
93 |
+
chat_history.append(("user", user_input))
|
94 |
+
chat_history.append(("assistant", response['output']))
|