Stream-режим AI-агента: agent.py
This commit is contained in:
@@ -55,7 +55,6 @@ print(f"Человек: {current_wish}\n")
|
||||
print("Джинн:", end=" ", flush=True)
|
||||
|
||||
|
||||
# --- Форматирование ---------------------------------------------------------
|
||||
def format_message(message) -> str:
|
||||
"""Возвращает строку, которую нужно вывести в консоль."""
|
||||
if message.content:
|
||||
@@ -66,21 +65,7 @@ def format_message(message) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
step = 1
|
||||
|
||||
def format_chunk_message(chunk):
|
||||
"""Обрабатывает чанк типа 'messages'."""
|
||||
global step
|
||||
message, meta = chunk
|
||||
|
||||
if meta["langgraph_step"] != step:
|
||||
step = meta["langgraph_step"]
|
||||
print("\n --- --- --- \n")
|
||||
|
||||
if message.content:
|
||||
# выводим токен без перевода строки, чтобы текст «тёк»
|
||||
print(message.content, end="", flush=True)
|
||||
|
||||
full_response = ""
|
||||
|
||||
# --- Потоковый вызов --------------------------------------------------------
|
||||
stream = human_agent.stream(
|
||||
@@ -98,17 +83,19 @@ stream = human_agent.stream(
|
||||
stream_mode=["messages", "updates"],
|
||||
)
|
||||
|
||||
full_response = ""
|
||||
|
||||
for chunk_type, chunk_data in stream:
|
||||
if chunk_type == "messages":
|
||||
format_chunk_message(chunk_data)
|
||||
message, _ = chunk_data
|
||||
full_response += message.content or ""
|
||||
# chunk_data – список сообщений
|
||||
for message in chunk_data:
|
||||
text = format_message(message)
|
||||
if text:
|
||||
print(text, end="", flush=True)
|
||||
full_response += text
|
||||
elif chunk_type == "updates":
|
||||
# событие завершения шага (например, вызов инструмента)
|
||||
if chunk_data.get("model"):
|
||||
last_msg = chunk_data["model"]["messages"][-1]
|
||||
update = chunk_data.get("model")
|
||||
if update:
|
||||
last_msg = update["messages"][-1]
|
||||
formatted = format_message(last_msg)
|
||||
if formatted:
|
||||
print(f"\n[Вызов инструмента: {formatted}]")
|
||||
|
||||
Reference in New Issue
Block a user