LangGraphの使い方メモ

# はじめに

https://github.com/langchain-ai/langgraph

# 手順

##

```bash
# インストール
!pip install -U langchain langchain_community langgraph langchain_openai langchainhub tavily-python 
```

```python

# 準備
from langchain import hub
from langchain.agents import create_openai_functions_agent
from langchain_openai.chat_models import ChatOpenAI
from langchain_community.tools.tavily_search import TavilySearchResults

import os
from google.colab import userdata
os.environ["OPENAI_API_KEY"] = userdata.get("OPENAI_API_KEY")
os.environ["TAVILY_API_KEY"] = userdata.get("TAVILY_API_KEY")
os.environ["LANGCHAIN_API_KEY"] = userdata.get("LANGCHAIN_API_KEY")
os.environ["LANGCHAIN_TRACING_V2"] = "true"
```


```python

tools = [TavilySearchResults(max_results=1)]
prompt = ""
llm = ChatOpenAI(model="gpt-3.5-turbo")

agent_runnable = create_openai_functions_agent(llm, tools, prompt)

from langchain_core.runnables import RunnablePassthrough
from langchain_core.agents import AgentFinish

agent = RunnablePassthrough.assign(
    agent_outcome = agent_runnable
)
```


```python

def execute_tools(data):
    agent_action = data.pop('agent_outcome')
    tool_to_use = {t.name: t for t in tools}[agent_action.tool]
    observation = tool_to_use.invoke(agent_action.tool_input)
    data['intermediate_steps'].append((agent_action, observation))
    return data

def should_continue(data):
    if isinstance(data['agent_outcome'], AgentFinish):
        return "exit"
    else:
        return "continue"
```


```python
# Graphの作成
from langgraph.graph import END, Graph
workflow = Graph()

# Graphを構成するnodeを追加
workflow.add_node("agent", agent)
workflow.add_node("tools", execute_tools)

# グラフの開始ノードを設定するエッジ
workflow.set_entry_point("agent")

# 条件に基づいて遷移先のノードを決定するエッジ
# (conditional_edgesを使うことで、条件分岐が可能となる)
# agent -> continue -> tools
#       -> exit -> END
workflow.add_conditional_edges(
    "agent", # start node
    should_continue,
    # should_continueの内容による条件分岐
    {
        "continue": "tools",
        "exit": END
    }
)

#　特定のノードから無条件で遷移するエッジを指定
# tools -> agent
workflow.add_edge('tools', 'agent')


#　コンパイルを行なってインスタンスへと変換
chain = workflow.compile()

```


```python

chain.invoke({"input": "AGIとは何かについて簡潔に教えてください", "intermediate_steps": []})

```

![IMG_0426.jpeg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/43766/b9986cf4-f853-4328-bfa5-d906167d3bc8.jpeg)



```python
from IPython.display import Image, display

display(Image(chain.get_graph().draw_mermaid_png()))

```

![IMG_0427.jpeg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/43766/af8adeb1-39b4-495b-b2e0-f7c874c24d8a.jpeg)




# CheckPointを使う


```python

from langgraph.graph import StateGraph, END
from langgraph.checkpoint.memory import MemorySaver

# グラフを設定
graph = StateGraph(State)
graph.add_node("add_message", add_message)
graph.add_node("llm_response", llm_response)

graph.set_entry_point("add_message")
graph.add_edge("add_message", "llm_response")
graph.add_edge("llm_response", END)

# チェックポインターを設定
checkpointer = MemorySaver()

# グラフをコンパイル
compiled_graph = graph.compile(checkpointer=checkpointer)

```

![IMG_0432.jpeg](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/43766/b2525abe-40d3-4f9c-827a-25a92e1f632b.jpeg)


```python
config = {"configurable": {"thread_id": "example-1"}}
user_query = State(query="「M1:犯人の手がかりを見つける」というミッションで、1.ナイフを見つける 2.隠された日記を見つける というタスクを完了しました")
first_response = compiled_graph.invoke(user_query, config)
first_response

```


```python
for checkpoint in checkpointer.list(config):
    print(checkpoint)
```



# 参考にした記事など

https://zenn.dev/pharmax/articles/8796b892eed183

https://zenn.dev/kun432/scraps/7ea614c804cfe7

https://zenn.dev/asap/articles/03548f844efe6f