1
- #!/usr/bin/env python
2
- # filepath: /home/runner/work/template-fastapi/template-fastapi/scripts/langgraph_agent.py
3
-
4
1
"""LangGraph Agent CLI tool."""
5
2
6
- import json
7
- from typing import Optional
8
-
9
3
import typer
10
4
from rich .console import Console
11
5
from rich .markdown import Markdown
12
6
from rich .panel import Panel
13
7
14
- from template_fastapi .core .langgraph .agent import LangGraphAgent
15
- from template_fastapi .core .langgraph .tools import get_tools
8
+ from template_fastapi .internals .langgraph .agents import LangGraphAgent
9
+ from template_fastapi .internals .langgraph .tools import get_tools
16
10
17
11
app = typer .Typer ()
18
12
console = Console ()
21
15
@app .command ()
22
16
def chat (
23
17
message : str = typer .Argument (..., help = "メッセージ" ),
24
- thread_id : Optional [ str ] = typer .Option (None , "--thread-id" , "-t" , help = "スレッドID(会話の継続用)" ),
18
+ thread_id : str | None = typer .Option (None , "--thread-id" , "-t" , help = "スレッドID(会話の継続用)" ),
25
19
verbose : bool = typer .Option (False , "--verbose" , "-v" , help = "詳細な情報を表示" ),
26
20
):
27
21
"""LangGraphエージェントとチャットする"""
28
22
console .print ("[bold green]LangGraphエージェントとチャットします[/bold green]" )
29
23
console .print (f"メッセージ: { message } " )
30
-
24
+
31
25
if thread_id :
32
26
console .print (f"スレッドID: { thread_id } " )
33
27
else :
34
28
console .print ("新しいスレッドを作成します" )
35
-
29
+
36
30
try :
37
31
# Initialize the LangGraph agent
38
32
agent = LangGraphAgent ()
39
-
33
+
40
34
# Show loading message
41
35
with console .status ("[bold green]エージェントが応答を生成中..." , spinner = "dots" ):
42
36
result = agent .chat (message = message , thread_id = thread_id )
43
-
37
+
44
38
# Display results
45
- console .print ("\n " + "=" * 50 )
39
+ console .print ("\n " + "=" * 50 )
46
40
console .print ("[bold blue]チャット結果[/bold blue]" )
47
- console .print ("=" * 50 )
48
-
41
+ console .print ("=" * 50 )
42
+
49
43
# Display user message
50
- user_panel = Panel (
51
- message ,
52
- title = "[bold cyan]あなた[/bold cyan]" ,
53
- border_style = "cyan"
54
- )
44
+ user_panel = Panel (message , title = "[bold cyan]あなた[/bold cyan]" , border_style = "cyan" )
55
45
console .print (user_panel )
56
-
46
+
57
47
# Display agent response with markdown rendering
58
48
response_content = result ["response" ]
59
49
if response_content :
60
50
try :
61
51
# Try to render as markdown for better formatting
62
52
markdown = Markdown (response_content )
63
53
agent_panel = Panel (
64
- markdown ,
65
- title = "[bold green]LangGraphエージェント[/bold green]" ,
66
- border_style = "green"
54
+ markdown , title = "[bold green]LangGraphエージェント[/bold green]" , border_style = "green"
67
55
)
68
56
except Exception :
69
57
# Fallback to plain text
70
58
agent_panel = Panel (
71
- response_content ,
72
- title = "[bold green]LangGraphエージェント[/bold green]" ,
73
- border_style = "green"
59
+ response_content , title = "[bold green]LangGraphエージェント[/bold green]" , border_style = "green"
74
60
)
75
61
console .print (agent_panel )
76
-
62
+
77
63
# Display metadata
78
64
if verbose :
79
65
console .print ("\n [bold yellow]メタデータ[/bold yellow]:" )
80
66
console .print (f"スレッドID: { result ['thread_id' ]} " )
81
67
console .print (f"作成日時: { result ['created_at' ]} " )
82
68
console .print (f"ステップ数: { result .get ('step_count' , 0 )} " )
83
-
69
+
84
70
if result .get ("tools_used" ):
85
71
console .print (f"使用ツール: { ', ' .join (result ['tools_used' ])} " )
86
72
else :
@@ -89,7 +75,7 @@ def chat(
89
75
console .print (f"\n [dim]スレッドID: { result ['thread_id' ]} [/dim]" )
90
76
if result .get ("tools_used" ):
91
77
console .print (f"[dim]使用ツール: { ', ' .join (result ['tools_used' ])} [/dim]" )
92
-
78
+
93
79
except Exception as e :
94
80
console .print (f"❌ [bold red]エラー[/bold red]: { str (e )} " )
95
81
@@ -99,41 +85,41 @@ def interactive():
99
85
"""対話モードでLangGraphエージェントとチャットする"""
100
86
console .print ("[bold green]LangGraphエージェント対話モード[/bold green]" )
101
87
console .print ("終了するには 'exit', 'quit', または 'bye' と入力してください\n " )
102
-
88
+
103
89
agent = LangGraphAgent ()
104
90
thread_id = None
105
-
91
+
106
92
while True :
107
93
try :
108
94
# Get user input
109
95
user_input = typer .prompt ("あなた" )
110
-
96
+
111
97
# Check for exit commands
112
- if user_input .lower () in [' exit' , ' quit' , ' bye' , '終了' ]:
98
+ if user_input .lower () in [" exit" , " quit" , " bye" , "終了" ]:
113
99
console .print ("[yellow]対話を終了します。ありがとうございました![/yellow]" )
114
100
break
115
-
101
+
116
102
# Process the message
117
103
with console .status ("[bold green]応答を生成中..." , spinner = "dots" ):
118
104
result = agent .chat (message = user_input , thread_id = thread_id )
119
-
105
+
120
106
# Update thread_id for conversation continuity
121
107
thread_id = result ["thread_id" ]
122
-
108
+
123
109
# Display agent response
124
110
response_panel = Panel (
125
111
Markdown (result ["response" ]) if result ["response" ] else "応答がありません" ,
126
112
title = "[bold green]エージェント[/bold green]" ,
127
- border_style = "green"
113
+ border_style = "green" ,
128
114
)
129
115
console .print (response_panel )
130
-
116
+
131
117
# Show tools used if any
132
118
if result .get ("tools_used" ):
133
119
console .print (f"[dim]使用ツール: { ', ' .join (result ['tools_used' ])} [/dim]" )
134
-
120
+
135
121
console .print () # Add spacing
136
-
122
+
137
123
except KeyboardInterrupt :
138
124
console .print ("\n [yellow]対話を終了します[/yellow]" )
139
125
break
@@ -145,36 +131,32 @@ def interactive():
145
131
def tools ():
146
132
"""利用可能なツールの一覧を表示する"""
147
133
console .print ("[bold green]利用可能なツール一覧[/bold green]" )
148
-
134
+
149
135
try :
150
136
available_tools = get_tools ()
151
-
137
+
152
138
if not available_tools :
153
139
console .print ("[yellow]利用可能なツールがありません[/yellow]" )
154
140
return
155
-
141
+
156
142
console .print (f"\n [bold blue]合計 { len (available_tools )} 個のツールが利用可能です[/bold blue]\n " )
157
-
143
+
158
144
for i , tool in enumerate (available_tools , 1 ):
159
145
tool_info = f"""
160
146
**名前:** { tool .name }
161
147
**説明:** { tool .description }
162
148
"""
163
- if hasattr (tool , ' args_schema' ) and tool .args_schema :
149
+ if hasattr (tool , " args_schema" ) and tool .args_schema :
164
150
try :
165
151
schema = tool .args_schema .model_json_schema ()
166
- if ' properties' in schema :
152
+ if " properties" in schema :
167
153
tool_info += f"**パラメータ:** { ', ' .join (schema ['properties' ].keys ())} "
168
154
except Exception :
169
155
pass
170
-
171
- panel = Panel (
172
- Markdown (tool_info ),
173
- title = f"[bold cyan]ツール { i } [/bold cyan]" ,
174
- border_style = "cyan"
175
- )
156
+
157
+ panel = Panel (Markdown (tool_info ), title = f"[bold cyan]ツール { i } [/bold cyan]" , border_style = "cyan" )
176
158
console .print (panel )
177
-
159
+
178
160
except Exception as e :
179
161
console .print (f"❌ [bold red]エラー[/bold red]: { str (e )} " )
180
162
@@ -184,38 +166,38 @@ def demo():
184
166
"""デモンストレーション用のサンプルチャット"""
185
167
console .print ("[bold green]LangGraphエージェント デモモード[/bold green]" )
186
168
console .print ("いくつかのサンプル質問でエージェントをテストします\n " )
187
-
169
+
188
170
sample_queries = [
189
171
"こんにちは!今何時ですか?" ,
190
172
"2 + 2 × 3 を計算してください" ,
191
173
"Pythonについて検索してください" ,
192
174
]
193
-
175
+
194
176
agent = LangGraphAgent ()
195
-
177
+
196
178
for i , query in enumerate (sample_queries , 1 ):
197
179
console .print (f"[bold yellow]サンプル質問 { i } :[/bold yellow] { query } " )
198
-
180
+
199
181
try :
200
182
with console .status (f"[bold green]質問 { i } を処理中..." , spinner = "dots" ):
201
183
result = agent .chat (message = query )
202
-
184
+
203
185
response_panel = Panel (
204
186
Markdown (result ["response" ]) if result ["response" ] else "応答がありません" ,
205
187
title = "[bold green]エージェントの応答[/bold green]" ,
206
- border_style = "green"
188
+ border_style = "green" ,
207
189
)
208
190
console .print (response_panel )
209
-
191
+
210
192
if result .get ("tools_used" ):
211
193
console .print (f"[dim]使用ツール: { ', ' .join (result ['tools_used' ])} [/dim]" )
212
-
194
+
213
195
console .print () # Add spacing
214
-
196
+
215
197
except Exception as e :
216
198
console .print (f"❌ [bold red]エラー[/bold red]: { str (e )} " )
217
199
console .print ()
218
200
219
201
220
202
if __name__ == "__main__" :
221
- app ()
203
+ app ()
0 commit comments