Обновить solutions/69a474cdc46fd26feae69896_Практическое_задание__3__Память_и_подтве/agent_with_memory_and_human_in_the_loop.py

This commit is contained in:
2026-05-27 08:43:52 +00:00
parent 14a7267ddc
commit b70e7e5cfd
@@ -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()