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