import os
from langchain_core.messages import HumanMessage
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from langgraph.checkpoint.sqlite import SqliteSaver
os.environ["OPENAI_API_KEY"] = "<OPENAI_API_KEY>"
os.environ["TAVILY_API_KEY"] = "<TAVILY_API_KEY>"
tavilySearchResults = TavilySearchResults(max_results = 2) # TAVILY API를 사용하기 위한 도구를 생성한다.
toolList = [tavilySearchResults]
chatOpenAI = ChatOpenAI(model = "gpt-4") # OPEN AI LLM 모델을 생성한다.
chatOpenAI.bind_tools(toolList) # OPEN AI LLM 모델과 도구를 바인딩한다.
sqliteSaver = SqliteSaver.from_conn_string(":memory:") # 상호 작용을 위한 메모리를 생성한다.
compiledStateGraph = create_react_agent(chatOpenAI, toolList, checkpointer = sqliteSaver) # 에이전트를 생성한다.
configurationDictionary = {"configurable" : {"thread_id" : "thread1"}} # thread_id로 세션을 구분한다.
addableValuesDict1 = compiledStateGraph.invoke({"messages" : [HumanMessage(content = "hi!")]}, configurationDictionary)
print(addableValuesDict1["messages"])
"""
[
HumanMessage(content='hi!', id='e5a65000-7bcd-4a24-bac3-27806cbe8dce'),
AIMessage(content='Hello! How can I assist you today?', response_metadata={'token_usage': {'completion_tokens': 10, 'prompt_tokens': 83, 'total_tokens': 93}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-8ff9af0d-0586-4222-966b-3a593a46fbc9-0', usage_metadata={'input_tokens': 83, 'output_tokens': 10, 'total_tokens': 93})]
"""
addableValuesDict2 = compiledStateGraph.invoke({"messages" : [HumanMessage(content = "whats the weather in sf?")]}, configurationDictionary)
print(addableValuesDict2["messages"])
"""
[
HumanMessage(content='hi!', id='e5a65000-7bcd-4a24-bac3-27806cbe8dce'),
AIMessage(content='Hello! How can I assist you today?', response_metadata={'token_usage': {'completion_tokens': 10, 'prompt_tokens': 83, 'total_tokens': 93}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-8ff9af0d-0586-4222-966b-3a593a46fbc9-0', usage_metadata={'input_tokens': 83, 'output_tokens': 10, 'total_tokens': 93}),
HumanMessage(content='whats the weather in sf?', id='a3b53bc7-8d50-448c-aa8c-5ca1cd195797'),
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_V4h5BFmGfdmSBiHP9rVaRC9p', 'function': {'arguments': '{\n "query": "current weather in San Francisco"\n}', 'name': 'tavily_search_results_json'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 23, 'prompt_tokens': 107, 'total_tokens': 130}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-c6e6a2e7-a2b3-40e9-9b25-1563b59cf83a-0', tool_calls=[{'name': 'tavily_search_results_json', 'args': {'query': 'current weather in San Francisco'}, 'id': 'call_V4h5BFmGfdmSBiHP9rVaRC9p'}], usage_metadata={'input_tokens': 107, 'output_tokens': 23, 'total_tokens': 130}), ToolMessage(content='[{"url": "https://www.weatherapi.com/", "content": "{\'location\': {\'name\': \'San Francisco\', \'region\': \'California\', \'country\': \'United States of America\', \'lat\': 37.78, \'lon\': -122.42, \'tz_id\': \'America/Los_Angeles\', \'localtime_epoch\': 1718003828, \'localtime\': \'2024-06-10 0:17\'}, \'current\': {\'last_updated_epoch\': 1718003700, \'last_updated\': \'2024-06-10 00:15\', \'temp_c\': 12.8, \'temp_f\': 55.0, \'is_day\': 0, \'condition\': {\'text\': \'Overcast\', \'icon\': \'//cdn.weatherapi.com/weather/64x64/night/122.png\', \'code\': 1009}, \'wind_mph\': 12.5, \'wind_kph\': 20.2, \'wind_degree\': 250, \'wind_dir\': \'WSW\', \'pressure_mb\': 1015.0, \'pressure_in\': 29.98, \'precip_mm\': 0.01, \'precip_in\': 0.0, \'humidity\': 93, \'cloud\': 100, \'feelslike_c\': 11.3, \'feelslike_f\': 52.3, \'windchill_c\': 10.4, \'windchill_f\': 50.8, \'heatindex_c\': 12.1, \'heatindex_f\': 53.8, \'dewpoint_c\': 10.1, \'dewpoint_f\': 50.2, \'vis_km\': 16.0, \'vis_miles\': 9.0, \'uv\': 1.0, \'gust_mph\': 14.0, \'gust_kph\': 22.6}}"}, {"url": "https://forecast.weather.gov/zipcity.php?inputstring=San+Francisco,CA", "content": "San Francisco CA 37.77\\u00b0N 122.41\\u00b0W (Elev. 131 ft) Last Update: 6:00 pm PDT Jun 7, 2024. Forecast Valid: 7pm PDT Jun 7, 2024-6pm PDT Jun 14, 2024 . Forecast Discussion . Additional Resources. Radar & Satellite Image. Hourly Weather Forecast. ... Severe Weather ; Current Outlook Maps ; Drought ; Fire Weather ; Fronts/Precipitation Maps ; Current ..."}]', name='tavily_search_results_json', id='fb4045ac-3877-4c98-ae9e-1d56267a5f69', tool_call_id='call_V4h5BFmGfdmSBiHP9rVaRC9p'),
AIMessage(content='The current weather in San Francisco, California is overcast with a temperature of 12.8°C (55°F). The wind is blowing from the west-southwest at a speed of 20.2 kph (12.5 mph). The humidity level is at 93%.', response_metadata={'token_usage': {'completion_tokens': 59, 'prompt_tokens': 691, 'total_tokens': 750}, 'model_name': 'gpt-4', 'system_fingerprint': None, 'finish_reason': 'stop', 'logprobs': None}, id='run-e0ebe54c-dc83-4dfa-abfa-d625fbd97f44-0', usage_metadata={'input_tokens': 691, 'output_tokens': 59, 'total_tokens': 750})]
"""