From b70e7e5cfdda231d0595657f8dc364b4c3e585c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D1=80=D0=B8=D1=8F=20=D0=91=D0=B5=D1=80=D0=B4?= =?UTF-8?q?=D0=BD=D0=B8=D0=BA=D0=BE=D0=B2=D0=B0?= Date: Wed, 27 May 2026 08:43:52 +0000 Subject: [PATCH] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8=D1=82?= =?UTF-8?q?=D1=8C=20solutions/69a474cdc46fd26feae69896=5F=D0=9F=D1=80?= =?UTF-8?q?=D0=B0=D0=BA=D1=82=D0=B8=D1=87=D0=B5=D1=81=D0=BA=D0=BE=D0=B5=5F?= =?UTF-8?q?=D0=B7=D0=B0=D0=B4=D0=B0=D0=BD=D0=B8=D0=B5=5F=5F3=5F=5F=D0=9F?= =?UTF-8?q?=D0=B0=D0=BC=D1=8F=D1=82=D1=8C=5F=D0=B8=5F=D0=BF=D0=BE=D0=B4?= =?UTF-8?q?=D1=82=D0=B2=D0=B5/agent=5Fwith=5Fmemory=5Fand=5Fhuman=5Fin=5Ft?= =?UTF-8?q?he=5Floop.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../agent_with_memory_and_human_in_the_loop.py | 59 +++++++++++++++---- 1 file changed, 48 insertions(+), 11 deletions(-) diff --git a/solutions/69a474cdc46fd26feae69896_Практическое_задание__3__Память_и_подтве/agent_with_memory_and_human_in_the_loop.py b/solutions/69a474cdc46fd26feae69896_Практическое_задание__3__Память_и_подтве/agent_with_memory_and_human_in_the_loop.py index 9809345..6059d68 100644 --- a/solutions/69a474cdc46fd26feae69896_Практическое_задание__3__Память_и_подтве/agent_with_memory_and_human_in_the_loop.py +++ b/solutions/69a474cdc46fd26feae69896_Практическое_задание__3__Память_и_подтве/agent_with_memory_and_human_in_the_loop.py @@ -1,4 +1,3 @@ - """ Практическое задание №3: Память и подтверждение действий @@ -23,6 +22,15 @@ import os from typing import Dict, Any +# ---------- Rich — красивый вывод в консоль ---------- +from rich.console import Console +from rich.panel import Panel +from rich.prompt import Prompt +from rich.text import Text +from rich import print as rprint + +console = Console() + # ---------- 1. Подключаем LLM ---------- from langchain_openai import ChatOpenAI from langchain.agents import create_agent @@ -67,10 +75,19 @@ agent = create_agent( # ---------- 4. Чат‑цикл ---------- def main(): - print("🤖 Агент готов! Введите запрос (или 'exit' для выхода).") + console.print( + Panel( + "[bold green]🤖 Агент готов![/bold green] Введите запрос или [italic]'exit'[/italic] для выхода.", + title="Добро пожаловать", + border_style="green", + ) + ) + while True: - user_input = input("\nВы: ") + user_input = Prompt.ask("\n[bold cyan]Вы[/bold cyan]") + if user_input.lower() in {"exit", "quit"}: + console.print("[yellow]До свидания! 👋[/yellow]") break # Запускаем потоковый ответ @@ -84,29 +101,49 @@ def main(): msg: AIMessage | HumanMessage | SystemMessage = data # выводим только текст (без tool_calls) if hasattr(msg, "content") and msg.content: - print(msg.content, end="", flush=True) + console.print(msg.content, end="") elif chunk_type == "updates": # Обрабатываем вызовы инструментов и подтверждения for update in data: if "tool_calls" in update: - # Выводим запрос к пользователю о подтверждении tool_name = update["tool_calls"][0]["name"] args = update["tool_calls"][0]["args"] - print(f"\n\n⚠️ Нужно вызвать инструмент: {tool_name}({args})") - decision = input("Разрешить? (y/n): ").strip().lower() + + # Выводим предупреждение через rich Panel + console.print( + Panel( + f"[bold yellow]Инструмент:[/bold yellow] [cyan]{tool_name}[/cyan]\n" + f"[bold yellow]Аргументы:[/bold yellow] {args}", + title="⚠️ Запрос на вызов инструмента", + border_style="yellow", + ) + ) + + decision = Prompt.ask( + "[bold]Разрешить вызов?[/bold]", + choices=["y", "n"], + default="y", + ) + if decision == "y": + console.print("[green]✅ Вызов разрешён.[/green]") # Продолжаем выполнение, передавая решение agent.invoke( {"messages": [{"role": "human", "content": user_input}]}, config={"configurable": {"thread_id": "chat-1"}}, ) else: - print("⚠️ Вызов инструмента отклонён.") - # Можно завершить цикл, если не нужно продолжать + console.print( + Panel( + "[red]Вызов инструмента отклонён пользователем.[/red]", + border_style="red", + ) + ) break - print("\n\n--- Конец ответа ---") + console.rule("[dim]Конец ответа[/dim]") + if __name__ == "__main__": - main() + main() \ No newline at end of file