Files
LangGraph/cli.py
T
2026-06-04 16:41:50 +00:00

106 lines
4.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
CLI для агента с retry через try/except
Демонстрирует цикл: generate → валидация → (retry при ошибке) → END
"""
import argparse
import sys
from graph import build_retry_graph
from state import ReflectState
DEMO_QUESTION = "Объясни студенту разницу между tool и resource в MCP"
def run_agent(question: str, max_rounds: int = 3, verbose: bool = True):
"""Запускает агента с retry-логикой"""
if verbose:
print("\n" + "="*80)
print(f"🤖 ЗАПУСК АГЕНТА С RETRY (TRY/EXCEPT)")
print(f"📋 Вопрос: {question}")
print(f"🔄 Макс. попыток: {max_rounds}")
print("="*80)
# Создаём граф
app = build_retry_graph(max_rounds=max_rounds)
# Состояние
initial_state: ReflectState = {
"question": question,
"draft": "",
"error": None,
"round": 1,
"max_rounds": max_rounds
}
# Запуск
final_state = app.invoke(initial_state)
# Вывод
if verbose:
print("\n" + "="*80)
if final_state["error"] is None:
print("✅ ФИНАЛЬНЫЙ РЕЗУЛЬТАТ")
print("="*80)
print(f"📝 Итоговый ответ (попытка {final_state['round']}):")
print("-"*80)
print(final_state["draft"])
print("-"*80)
print(f"🎉 Успешно сгенерировано за {final_state['round']} попыток!")
else:
print("❌ ОШИБКА ГЕНЕРАЦИИ")
print("="*80)
print(f"Достигнут лимит попыток ({max_rounds})")
print(f"Последняя ошибка: {final_state['error']}")
return final_state
def interactive_mode():
"""Интерактивный режим"""
print("\n🎮 Интерактивный режим агента с retry (try/except)")
print("Введите 'exit' для выхода\n")
while True:
question = input("Ваш вопрос: ").strip()
if question.lower() == 'exit':
break
if not question:
continue
max_rounds = input("Макс. попыток (по умолч. 3): ").strip()
max_rounds = int(max_rounds) if max_rounds.isdigit() else 3
run_agent(question, max_rounds, verbose=True)
print("\n" + ""*80 + "\n")
def main():
parser = argparse.ArgumentParser(
description="LangGraph агент с retry через try/except",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Примеры:
python cli.py --demo # Запуск на демо-вопросе
python cli.py -q "Что такое AI?" # Свой вопрос
python cli.py -q "..." --max-rounds 5 # 5 попыток
python cli.py --interactive # Интерактивный режим
"""
)
parser.add_argument("-q", "--question", help="Вопрос для агента")
parser.add_argument("--max-rounds", type=int, default=3, help="Макс. попыток (по умолч. 3)")
parser.add_argument("--demo", action="store_true", help="Запустить демо-вопрос")
parser.add_argument("-i", "--interactive", action="store_true", help="Интерактивный режим")
parser.add_argument("--quiet", action="store_true", help="Тихий режим (только ответ)")
args = parser.parse_args()
if args.interactive:
interactive_mode()
elif args.demo or (not args.question):
run_agent(DEMO_QUESTION, args.max_rounds, verbose=not args.quiet)
elif args.question:
run_agent(args.question, args.max_rounds, verbose=not args.quiet)
else:
parser.print_help()
if __name__ == "__main__":
main()