■ SqliteSaver 클래스 : from_conn_string 정적 메소드를 사용해 상호 작용을 위한 SqliteSaver 객체를 만드는 방법을 보여준다.
▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
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})] """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
aiohttp==3.9.5 aiosignal==1.3.1 annotated-types==0.7.0 anyio==4.4.0 async-timeout==4.0.3 attrs==23.2.0 certifi==2024.6.2 charset-normalizer==3.3.2 dataclasses-json==0.6.7 distro==1.9.0 exceptiongroup==1.2.1 frozenlist==1.4.1 greenlet==3.0.3 h11==0.14.0 httpcore==1.0.5 httpx==0.27.0 idna==3.7 jsonpatch==1.33 jsonpointer==2.4 langchain==0.2.3 langchain-community==0.2.4 langchain-core==0.2.5 langchain-openai==0.1.8 langchain-text-splitters==0.2.1 langgraph==0.0.66 langsmith==0.1.75 marshmallow==3.21.3 multidict==6.0.5 mypy-extensions==1.0.0 numpy==1.26.4 openai==1.33.0 orjson==3.10.3 packaging==23.2 pydantic==2.7.3 pydantic_core==2.18.4 PyYAML==6.0.1 regex==2024.5.15 requests==2.32.3 sniffio==1.3.1 SQLAlchemy==2.0.30 tavily-python==0.3.3 tenacity==8.3.0 tiktoken==0.7.0 tqdm==4.66.4 typing-inspect==0.9.0 typing_extensions==4.12.2 urllib3==2.2.1 yarl==1.9.4 |
※ pip install langchain langchain-community langchain-openai langgraph tavily-python 명령을 실행했다.