|
1 |
| -# template-langgraph |
| 1 | +# LangGraph AI Agent Template |
| 2 | + |
| 3 | +A comprehensive template project for building AI agents using [LangGraph](https://langchain-ai.github.io/langgraph/), demonstrating various agent patterns, tool integration, and real-world use cases. |
| 4 | + |
| 5 | +## What is LangGraph? |
| 6 | + |
| 7 | +[LangGraph](https://langchain-ai.github.io/langgraph/) is a framework built on top of [LangChain](https://python.langchain.com/) that enables you to create stateful, multi-agent workflows. Unlike traditional chatbots that handle single interactions, LangGraph allows you to build complex AI systems that can: |
| 8 | + |
| 9 | +- Maintain conversation state across multiple turns |
| 10 | +- Use tools and external APIs |
| 11 | +- Implement complex reasoning patterns |
| 12 | +- Coordinate multiple AI agents |
| 13 | +- Handle cyclical workflows and conditional logic |
| 14 | + |
| 15 | +This template demonstrates these capabilities through practical examples using a fictional system called "KABUTO" for troubleshooting scenarios. |
| 16 | + |
| 17 | +## Project Overview |
| 18 | + |
| 19 | +This project showcases different AI agent patterns and architectures, from simple tool-calling agents to complex multi-agent systems. The examples use a fictional technical support scenario to demonstrate how agents can retrieve information from multiple data sources and provide structured responses. |
| 20 | + |
| 21 | +### Why This Template Exists |
| 22 | + |
| 23 | +Most AI applications need to: |
| 24 | + |
| 25 | +1. **Access external information** - LLMs don't have access to your specific data |
| 26 | +2. **Use tools** - Perform actions beyond text generation |
| 27 | +3. **Maintain context** - Remember previous interactions |
| 28 | +4. **Handle complex workflows** - Break down tasks into manageable steps |
| 29 | + |
| 30 | +This template provides working examples of all these patterns using LangGraph. |
2 | 31 |
|
3 | 32 | ## Prerequisites
|
4 | 33 |
|
5 | 34 | - [Python 3.10+](https://www.python.org/downloads/)
|
6 |
| -- [uv](https://docs.astral.sh/uv/getting-started/installation/) |
7 |
| -- [GNU Make](https://www.gnu.org/software/make/) |
| 35 | +- [uv](https://docs.astral.sh/uv/getting-started/installation/) - Modern Python package manager |
| 36 | +- [GNU Make](https://www.gnu.org/software/make/) - For running common tasks |
| 37 | +- [Docker](https://www.docker.com/) - For running vector databases (optional) |
8 | 38 |
|
9 |
| -## Getting Started |
| 39 | +## Quick Start |
10 | 40 |
|
11 |
| -### Set up local environment |
| 41 | +### 1. Environment Setup |
12 | 42 |
|
13 | 43 | ```shell
|
14 | 44 | # Clone the repository
|
15 | 45 | git clone https://github.com/ks6088ts-labs/template-langgraph.git
|
16 | 46 | cd template-langgraph
|
17 | 47 |
|
18 |
| -# Start services using Docker Compose (Requires Docker) |
19 |
| -docker compose up -d |
| 48 | +# Install Python dependencies |
| 49 | +uv sync --all-extras |
20 | 50 |
|
21 |
| -# Create a .env file based on the template |
| 51 | +# Create environment configuration |
22 | 52 | cp .env.template .env
|
23 |
| - |
24 |
| -# Install required Python packages (Requires uv) |
25 |
| -uv sync --all-extras |
| 53 | +# Edit .env with your API keys (Azure OpenAI, etc.) |
26 | 54 | ```
|
27 | 55 |
|
28 |
| -### Set up infrastructure |
| 56 | +### 2. Start Supporting Services (Optional) |
29 | 57 |
|
30 |
| -Here are some commands you can use: |
| 58 | +For full functionality, start the vector databases: |
| 59 | + |
| 60 | +```shell |
| 61 | +# Start Qdrant and Elasticsearch using Docker |
| 62 | +docker compose up -d |
| 63 | +``` |
31 | 64 |
|
32 |
| -**Create Qdrant collection:** |
| 65 | +### 3. Initialize Data Sources |
33 | 66 |
|
34 |
| -> [!NOTE] |
35 |
| -> Qdrant service is expected to be running |
| 67 | +**Set up Qdrant vector database:** |
36 | 68 |
|
37 | 69 | ```shell
|
38 | 70 | uv run python scripts/qdrant_operator.py add-documents \
|
39 | 71 | --collection-name qa_kabuto \
|
40 | 72 | --verbose
|
41 | 73 | ```
|
42 | 74 |
|
43 |
| -**Create Elasticsearch index:** |
44 |
| - |
45 |
| -> [!NOTE] |
46 |
| -> Elasticsearch service is expected to be running |
| 75 | +**Set up Elasticsearch search index:** |
47 | 76 |
|
48 | 77 | ```shell
|
49 | 78 | uv run python scripts/elasticsearch_operator.py create-index \
|
50 | 79 | --index-name docs_kabuto \
|
51 | 80 | --verbose
|
52 | 81 | ```
|
53 | 82 |
|
54 |
| -### Run applications |
| 83 | +## Project Structure |
| 84 | + |
| 85 | +### Core Components |
| 86 | + |
| 87 | +- **`data/`** - Sample data for the fictional KABUTO system (PDFs, FAQs, troubleshooting guides) |
| 88 | +- **`template_langgraph/`** - Main Python package containing all agent implementations |
| 89 | +- **`notebooks/`** - Jupyter notebooks with interactive examples and explanations |
| 90 | +- **`scripts/`** - Command-line tools for running agents |
| 91 | + |
| 92 | +### Agent Examples (`template_langgraph/agents/`) |
| 93 | + |
| 94 | +This project includes several agent implementations, each demonstrating different LangGraph patterns: |
| 95 | + |
| 96 | +#### 1. `kabuto_helpdesk_agent/` - **Start Here!** |
| 97 | + |
| 98 | +A simple agent using LangGraph's prebuilt `create_react_agent` function. This is the best starting point for understanding the basics. |
| 99 | + |
| 100 | +**Key concepts:** ReAct pattern, tool calling, prebuilt agents |
| 101 | + |
| 102 | +#### 2. `chat_with_tools_agent/` - **Core Implementation** |
| 103 | + |
| 104 | +A manual implementation of the same logic as the helpdesk agent, showing how LangGraph workflows are built from scratch. |
| 105 | + |
| 106 | +**Key concepts:** Graph construction, state management, node functions, edges |
| 107 | + |
| 108 | +#### 3. `issue_formatter_agent/` - **Structured Output** |
| 109 | + |
| 110 | +Demonstrates how to get structured data from AI responses using Pydantic models. |
| 111 | + |
| 112 | +**Key concepts:** Structured output, data validation, response formatting |
| 113 | + |
| 114 | +#### 4. `task_decomposer_agent/` - **Planning & Decomposition** |
| 115 | + |
| 116 | +Shows how to break down complex tasks into smaller, manageable steps. |
| 117 | + |
| 118 | +**Key concepts:** Task planning, multi-step reasoning, conditional workflows |
| 119 | + |
| 120 | +#### 5. `supervisor_agent/` - **Multi-Agent Coordination** |
55 | 121 |
|
56 |
| -#### LangGraph Studio |
| 122 | +Implements the supervisor pattern where one agent coordinates multiple specialized agents. |
57 | 123 |
|
58 |
| -From the command line, you can run the LangGraph Studio to interact with the application. |
| 124 | +**Key concepts:** Multi-agent systems, agent coordination, supervisor patterns |
| 125 | + |
| 126 | +### Supporting Modules |
| 127 | + |
| 128 | +- **`template_langgraph/llms/`** - LLM API wrappers (Azure OpenAI, etc.) |
| 129 | +- **`template_langgraph/tools/`** - Tool implementations for search, data retrieval |
| 130 | +- **`template_langgraph/utilities/`** - Helper functions for document loading and processing |
| 131 | + |
| 132 | +## Running the Examples |
| 133 | + |
| 134 | +### Option 1: LangGraph Studio (Recommended for Development) |
| 135 | + |
| 136 | +[LangGraph Studio](https://langchain-ai.github.io/langgraph/concepts/langgraph_studio/) provides a visual interface for developing and debugging agents: |
59 | 137 |
|
60 | 138 | ```shell
|
61 | 139 | uv run langgraph dev
|
62 | 140 | ```
|
63 | 141 |
|
| 142 | +This opens a web interface where you can: |
| 143 | + |
| 144 | +- Visualize agent workflows |
| 145 | +- Step through executions |
| 146 | +- Debug state transitions |
| 147 | +- Test different inputs |
| 148 | + |
64 | 149 | 
|
65 | 150 |
|
66 |
| -#### Jupyter Lab |
| 151 | +### Option 2: Jupyter Notebooks (Best for Learning) |
67 | 152 |
|
68 |
| -From Jupyter Lab, you can run the notebooks in the `notebooks` directory to run various applications. |
| 153 | +Interactive notebooks with explanations and examples: |
69 | 154 |
|
70 | 155 | ```shell
|
71 |
| -# Run Jupyter Lab |
72 | 156 | uv run jupyter lab
|
73 |
| - |
74 |
| -# Go to http://localhost:8888 in your browser and run notebooks/*.ipynb. |
| 157 | +# Navigate to http://localhost:8888 and open notebooks/*.ipynb |
75 | 158 | ```
|
76 | 159 |
|
77 | 160 | 
|
78 | 161 |
|
79 |
| -#### Terminal |
| 162 | +### Option 3: Command Line (Production-like) |
80 | 163 |
|
81 |
| -From the command line, you can run scripts in the `scripts` directory to run various applications. |
| 164 | +Run agents from the terminal: |
82 | 165 |
|
83 | 166 | ```shell
|
84 | 167 | uv run python scripts/agent_operator.py run \
|
85 | 168 | --name "chat_with_tools_agent" \
|
86 |
| - --question "KABUTOの起動時に、画面全体が紫色に点滅し、システムがフリーズします。KABUTO のマニュアルから、関連する情報を取得したり過去のシステムのトラブル シュート事例が蓄積されたデータベースから、関連する情報を取得して質問に答えてください" \ |
| 169 | + --question "KABUTO startup issue: screen flashes purple and system freezes" \ |
87 | 170 | --verbose
|
88 |
| -2025-08-05 11:27:40,949 [ INFO] -------------------- (agent_operator.py:104) |
89 |
| -2025-08-05 11:27:40,949 [ INFO] Event: {'chat_with_tools': {'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'index': 0, 'id': 'call_LTenxsczZMuCdIAK8IBT9e7r', 'function': {'arguments': '{"keywords": "KABUTO 起動 紫色 点滅 フリーズ"}', 'name': 'search_elasticsearch'}, 'type': 'function'}, {'index': 1, 'id': 'call_POOYozcQOSjnXEaVkbxQpTz7', 'function': {'arguments': '{"keywords": "KABUTO 起動 紫色 点滅 フリーズ"}', 'name': 'search_qdrant'}, 'type': 'function'}]}, response_metadata={'finish_reason': 'tool_calls', 'model_name': 'gpt-4o-2024-11-20', 'system_fingerprint': 'fp_ee1d74bde0'}, id='run--60587ca8-d54e-4c66-8d9c-c5a99ae479a9-0', tool_calls=[{'name': 'search_elasticsearch', 'args': {'keywords': 'KABUTO 起動 紫色 点滅 フリーズ'}, 'id': 'call_LTenxsczZMuCdIAK8IBT9e7r', 'type': 'tool_call'}, {'name': 'search_qdrant', 'args': {'keywords': 'KABUTO 起動 紫色 点滅 フリーズ'}, 'id': 'call_POOYozcQOSjnXEaVkbxQpTz7', 'type': 'tool_call'}])]}} (agent_operator.py:105) |
90 |
| -2025-08-05 11:27:41,458 [ INFO] -------------------- (agent_operator.py:104) |
91 |
| -2025-08-05 11:27:41,458 [ INFO] Event: {'tools': {'messages': [ToolMessage(content='"[ElasticsearchOutput(file_name=\'docs_kabuto.pdf\', content=\'「⻤灯」の実⾏中は、冷却システムが⼀時的に停⽌し、無⾳となる。これは内部エネルギーの流れを最適化するため\\\\nの仕様であり、異常ではない。ただし、この無⾳状態が 15 分以上継続する場合は、過熱の可能性があるため、アプリ\\\\nケーションの強制終了およびシステムの再起動が推奨される。\\\\n第 3 章 ソフトウェア・オペレーション\\\\n3.1 起動プロトコル\\\\nKABUTO の起動シーケンスは、「シノビ・プロトコル」に基づき実⾏される。このプロトコルの初期化フェーズで、\\\\n内部クロックと接続された外部周辺機器のクロックとの同期に失敗した場合、画⾯全体が紫⾊に点滅し、システムが\'), ElasticsearchOutput(file_name=\'docs_kabuto.pdf\', content=\'2.1 電源・起動システム\\\\nKABUTO の電源ランプは、通常の動作状態を以下のパターンで表⽰する。待機状態では⾚⾊点滅、稼働状態では⻘⾊\\\\n点滅が繰り返される。このパターンにない緑⾊の点滅は、システムが「禅モード」に移⾏していることを⽰す。禅モ\\\\nードでは、パフォーマンスが最⼩限に抑えられ、バックグラウンドでのシステム⾃⼰修復が実⾏される。このモード\\\\nからの強制離脱は、 KABUTO 本体に設置された「⿓⽟」ボタンを 5 秒以上⻑押しすることで可能となる。また、電源\\\\nOFF 後も微細な電流が流れ続ける「夢の海」と呼ばれる待機モードが存在し、これにより次回の起動⾼速化が図られ\'), ElasticsearchOutput(file_name=\'docs_kabuto.pdf\', content=\'フリーズする。この問題は、 KABUTO 本体の再起動前に、すべての周辺機器を 5 秒以上電源から抜くことで、外部ク\\\\nロックのキャッシュがクリアされ、同期が正常に⾏われる可能性が⾼まる。\\\\n3.2 セキュリティ・認証システム\\\\nログイン認証は、パスワード⼊⼒に加え、セキュリティモジュール「百⻤夜⾏」によるログイン試⾏者の「精神波\\\\n形」解析を伴う。パスワードが正しく⼊⼒された場合でも、精神波形が登録されたユーザーと⼀致しないと判断され\')]"', name='search_elasticsearch', id='33ac53bd-22d8-4fe1-9094-bd4869c4771a', tool_call_id='call_LTenxsczZMuCdIAK8IBT9e7r'), ToolMessage(content='"[QdrantOutput(file_name=\'./data/qa_kabuto.csv\', content=\'q: KABUTOの起動時に、画面全体が紫色に点滅し、システムがフリーズします。 a: この現象は、「シノビ・プロトコル」が初期化フェーズで、内部クロックと外部クロックの同期に失敗している場合に発生します。KABUTO本体を再起動する前に、必ず接続されているすべての周辺機器を5秒以上、電源から抜いてください。これにより、外部クロックのキャッシュがクリアされ、同期が正常に行われる可能性が高まります。\'), QdrantOutput(file_name=\'./data/qa_kabuto.csv\', content=\'q: KABUTOの電源ランプが、赤と青の交互点滅ではなく、緑色で点滅しています。 a: 通常、電源ランプは赤(待機中)と青(稼働中)の点滅を繰り返します。緑色の点滅は、KABUTOが「禅モード」に入っており、パフォーマンスを最小限に抑え、バックグラウンドでシステム自己修復を行っている状態を示します。この状態では、ユーザー操作はほとんど受け付けられません。このモードから強制的に脱出するには、KABUTO本体の「龍玉」ボタンを5秒以上長押ししてください。\'), QdrantOutput(file_name=\'./data/qa_kabuto.csv\', content=\'q: KABUTOの画面の隅に、時々「狐火」のような光の点が、不規則に現れては消えます。 a: 「狐火」は、KABUTOの演算コア「稲荷」が、膨大な量のタスクを処理しきれずに、一部の計算結果が視覚的なノイズとして現れている現象です。これは、システム負荷が高いことを示しています。この現象が頻繁に発生する場合は、バックグラウンドで動作している不要なアプリケーションを終了させるか、KABUTOを再起動してください。\')]"', name='search_qdrant', id='97878816-f478-4bd5-a78e-0b668311bf05', tool_call_id='call_POOYozcQOSjnXEaVkbxQpTz7')]}} (agent_operator.py:105) |
92 |
| -2025-08-05 11:27:45,507 [ INFO] -------------------- (agent_operator.py:104) |
93 |
| -2025-08-05 11:27:45,508 [ INFO] Event: {'chat_with_tools': {'messages': [AIMessage(content='KABUTOの起動時に画面全体が紫色に点滅し、システムがフリーズする問題について、以下の情報が得られました。\n\n### 原因\nこの現象は、「シノビ・プロトコル」が初期化フェーズで、内部クロックと外部クロックの同期に失敗している場合に発生します。\n\n### 解決方法\n1. **周辺機器の電源を切る**:\n - KABUTO本体を再起動する前に、接続されているすべての周辺機器を5秒以上電源から抜いてください。\n - これにより、外部クロックのキャッシュがクリアされ、同期が正常に行われる可能性が高まります。\n\n2. **強制再起動**:\n - 必要に応じて、KABUTO本体の「龍玉」ボタンを5秒以上長押しして強制再起動を試みてください。\n\n### 注意点\n- この問題が頻繁に発生する場合は、システムの内部エネルギー流れや冷却システムの状態を確認する必要があります。\n- 再起動後も問題が解決しない場合は、専門の技術者に相談することをお勧めします。\n\nこれらの手順を試してみてください。問題が解決しない場合は、さらに詳細な情報を提供していただければ追加のサポートを行います。', additional_kwargs={}, response_metadata={'finish_reason': 'stop', 'model_name': 'gpt-4o-2024-11-20', 'system_fingerprint': 'fp_ee1d74bde0'}, id='run--c3c0ecb8-b85f-4072-8420-eeb94f2b62a1-0')]}} (agent_operator.py:105) |
94 | 171 | ```
|
95 | 172 |
|
96 |
| -## Tutorials |
| 173 | +Example output showing the agent's reasoning process: |
| 174 | + |
| 175 | +```text |
| 176 | +Event: {'chat_with_tools': {'messages': [AIMessage(content='', tool_calls=[ |
| 177 | + {'name': 'search_elasticsearch', 'args': {'keywords': 'KABUTO startup purple flashing freeze'}}, |
| 178 | + {'name': 'search_qdrant', 'args': {'keywords': 'KABUTO startup purple flashing freeze'}} |
| 179 | +])]}} |
| 180 | +
|
| 181 | +Event: {'tools': {'messages': [ToolMessage(content='Found documentation about startup protocol...')]}} |
| 182 | +
|
| 183 | +Event: {'chat_with_tools': {'messages': [AIMessage(content=' |
| 184 | +### Problem Analysis |
| 185 | +The purple screen flashing during KABUTO startup indicates a "Shinobi Protocol" initialization failure... |
| 186 | +
|
| 187 | +### Solution |
| 188 | +1. **Disconnect peripheral devices**: Unplug all connected devices for 5+ seconds |
| 189 | +2. **Clear external clock cache**: This resolves clock synchronization issues |
| 190 | +3. **Restart KABUTO**: Use the "Dragon Ball" button for 5+ seconds if needed |
| 191 | +')]}} |
| 192 | +``` |
| 193 | + |
| 194 | +## Key Concepts Demonstrated |
| 195 | + |
| 196 | +### 1. **ReAct Pattern** (Reasoning + Acting) |
| 197 | + |
| 198 | +The foundation of modern AI agents - the ability to reason about what to do, take actions, and reason about the results. |
| 199 | + |
| 200 | +### 2. **Tool Calling** |
| 201 | + |
| 202 | +How agents can use external functions to: |
| 203 | + |
| 204 | +- Search databases (Elasticsearch, Qdrant) |
| 205 | +- Call APIs |
| 206 | +- Process files |
| 207 | +- Execute calculations |
| 208 | + |
| 209 | +### 3. **State Management** |
| 210 | + |
| 211 | +How LangGraph maintains context across multiple interaction steps, enabling complex multi-turn conversations. |
| 212 | + |
| 213 | +### 4. **Conditional Workflows** |
| 214 | + |
| 215 | +Using graph structures to create branching logic based on agent decisions or external conditions. |
| 216 | + |
| 217 | +### 5. **Multi-Agent Systems** |
| 218 | + |
| 219 | +Coordinating multiple specialized agents to handle complex tasks that require different expertise. |
| 220 | + |
| 221 | +## Data Sources Explained |
| 222 | + |
| 223 | +The project uses fictional data about a system called "KABUTO" to demonstrate real-world scenarios: |
| 224 | + |
| 225 | +- **`data/docs_kabuto.pdf`** - Technical documentation (simulates user manuals) |
| 226 | +- **`data/qa_kabuto.csv`** - FAQ database (simulates past support tickets) |
| 227 | +- **`data/docs_kabuto.md`** - Additional documentation |
| 228 | + |
| 229 | +This fictional data serves a purpose: it proves that the AI agents can work with information that isn't in the LLM's training data, demonstrating the value of retrieval-augmented generation (RAG). |
| 230 | + |
| 231 | +## Next Steps |
| 232 | + |
| 233 | +1. **Start with the basics**: Run the `kabuto_helpdesk_agent` example |
| 234 | +2. **Understand the implementation**: Compare it with `chat_with_tools_agent` |
| 235 | +3. **Explore advanced patterns**: Try the task decomposer and supervisor agents |
| 236 | +4. **Build your own**: Use this template as a starting point for your use case |
| 237 | + |
| 238 | +## Learning Resources |
| 239 | + |
| 240 | +- [LangGraph Documentation](https://langchain-ai.github.io/langgraph/) |
| 241 | +- [LangChain Documentation](https://python.langchain.com/) |
| 242 | + |
| 243 | +## Architecture Examples |
| 244 | + |
| 245 | +This template demonstrates several proven agent architectures: |
| 246 | + |
| 247 | +1. **Single Agent with Tools** - Basic tool-calling pattern |
| 248 | +2. **ReAct Agent** - Reasoning and acting in loops |
| 249 | +3. **Structured Output Agent** - Returning formatted data |
| 250 | +4. **Planning Agent** - Breaking down complex tasks |
| 251 | +5. **Supervisor Agent** - Coordinating multiple agents |
97 | 252 |
|
98 |
| -<!-- Add docs here --> |
| 253 | +Each pattern is implemented with clear examples and documentation to help you understand when and how to use them. |
0 commit comments