from dotenv import load_dotenv
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain.agents import AgentExecutor
from langchain.agents import create_tool_calling_agent
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory
from langchain_core.messages import HumanMessage
load_dotenv()
chatOpenAI = ChatOpenAI(model = "gpt-4o-mini", temperature = 0)
toolList = [TavilySearchResults(max_results = 1)]
chatPromptTemplate = ChatPromptTemplate.from_messages(
[
("system" , "You are a helpful assistant. You may not need to use tools for every query - the user may just want to chat!"),
("placeholder", "{messages}" ),
("placeholder", "{agent_scratchpad}")
]
)
runnableSequence = create_tool_calling_agent(chatOpenAI, toolList, chatPromptTemplate)
agentExecutor = AgentExecutor(agent = runnableSequence, tools = toolList, verbose = False)
chatMessageHistory = ChatMessageHistory()
runnableWithMessageHistory = RunnableWithMessageHistory(
agentExecutor,
lambda session_id : chatMessageHistory,
input_messages_key = "messages",
output_messages_key = "output"
)
responseDictionary1 = runnableWithMessageHistory.invoke({"messages" : [HumanMessage("I'm Nemo!")]}, {"configurable" : {"session_id" : "unused"}})
print(responseDictionary1)
"""
{
'messages' : [HumanMessage(content = "I'm Nemo!", additional_kwargs = {}, response_metadata = {})],
'output' : 'Hi Nemo! How can I assist you today?'
}
"""
responseDictionary2 = runnableWithMessageHistory.invoke({"messages" : [HumanMessage("What is my name?")]}, {"configurable" : {"session_id": "unused"}})
print(responseDictionary2)
"""
{
'messages' : [
HumanMessage(content = "I'm Nemo!", additional_kwargs = {}, response_metadata = {}),
AIMessage(content = 'Hi Nemo! How can I assist you today?', additional_kwargs = {}, response_metadata = {}),
HumanMessage(content = 'What is my name?', additional_kwargs = {}, response_metadata = {})
],
'output' : 'Your name is Nemo!'
}
"""