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