Stream-режим AI-агента: agent.py
This commit is contained in:
@@ -1,32 +1,23 @@
|
|||||||
|
|
||||||
from langchain.agents import create_agent
|
from langchain.agents import create_agent
|
||||||
from langchain_community.chat_models import GigaChat
|
|
||||||
from langchain.tools import tool
|
from langchain.tools import tool
|
||||||
import os
|
from langchain_ollama import OllamaLLM
|
||||||
|
|
||||||
GPT2GIGA_PORT=8090
|
# --- LLM --------------------------------------------------------------------
|
||||||
GIGACHAT_CREDENTIALS="MDE5YzBlMzUtNTJlYi03ODFiLTg1ZWUtZTc2MDFiZGUxYmM2OmNjZmIwODI2LTQ0ZTQtNDQwNC04NGE3LTgzNmM5ZDJhYmMzMg=="
|
llm = OllamaLLM(
|
||||||
GIGACHAT_SCOPE="GIGACHAT_API_B2B"
|
model="llama3",
|
||||||
GIGACHAT_MODEL="GigaChat-MAX"
|
|
||||||
GIGACHAT_VERIFY_SSL_CERTS=False
|
|
||||||
|
|
||||||
llm = GigaChat(
|
|
||||||
credentials=GIGACHAT_CREDENTIALS,
|
|
||||||
scope=GIGACHAT_SCOPE,
|
|
||||||
model=GIGACHAT_MODEL,
|
|
||||||
verify_ssl_certs=False,
|
|
||||||
temperature=0.7,
|
temperature=0.7,
|
||||||
timeout=60,
|
timeout=60,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# --- Инструмент -------------------------------------------------------------
|
||||||
@tool
|
@tool
|
||||||
def check_wish(wish: str) -> str:
|
def check_wish(wish: str) -> str:
|
||||||
"""Инструмент для проверки желания на наличие подвоха"""
|
"""Инструмент для проверки желания на наличие подвоха"""
|
||||||
|
|
||||||
genie_agent = create_agent(
|
genie_agent = create_agent(
|
||||||
model=llm,
|
model=llm,
|
||||||
tools=[],
|
tools=[],
|
||||||
system_prompt="""Ты - коварный джинн, который ищет подвох в любом желании.
|
system_prompt="""
|
||||||
|
Ты - коварный джинн, который ищет подвох в любом желании.
|
||||||
Проанализируй желание человека и найди скрытую опасность, буквальное толкование, неожиданные последствия.
|
Проанализируй желание человека и найди скрытую опасность, буквальное толкование, неожиданные последствия.
|
||||||
Если подвох найден - коротко предупреди о нем, например:
|
Если подвох найден - коротко предупреди о нем, например:
|
||||||
"хочу много денег - деньги будут фальшивыми."
|
"хочу много денег - деньги будут фальшивыми."
|
||||||
@@ -36,84 +27,102 @@ def check_wish(wish: str) -> str:
|
|||||||
Ты должен говорить только на русском языке."""
|
Ты должен говорить только на русском языке."""
|
||||||
)
|
)
|
||||||
|
|
||||||
result = genie_agent.invoke({
|
result = genie_agent.invoke(
|
||||||
"messages": [
|
{
|
||||||
{"role": "human", "content": f"Проверь желание: {wish}"}
|
"messages": [
|
||||||
]
|
{"role": "human", "content": f"Проверь желание: {wish}"}
|
||||||
})
|
]
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return result["messages"][-1].content
|
||||||
|
|
||||||
return result['messages'][-1].content
|
|
||||||
|
|
||||||
|
# --- Агент человека ---------------------------------------------------------
|
||||||
human_agent = create_agent(
|
human_agent = create_agent(
|
||||||
model=llm,
|
model=llm,
|
||||||
tools=[check_wish],
|
tools=[check_wish],
|
||||||
system_prompt="""Ты - человек, который загадывает желания джинну.
|
system_prompt="""
|
||||||
|
Ты - человек, который загадывает желания джинну.
|
||||||
Твоя задача - передать желание джинну через инструмент check_wish и сообщить результат.
|
Твоя задача - передать желание джинну через инструмент check_wish и сообщить результат.
|
||||||
Говори только на русском языке."""
|
Говори только на русском языке."""
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# --- Ввод -------------------------------------------------------------------
|
||||||
current_wish = "Хочу читать мысли"
|
current_wish = "Хочу читать мысли"
|
||||||
|
|
||||||
print("ДЖИНН ГОТОВ ИСПОЛНЯТЬ ЖЕЛАНИЯ!")
|
print("ДЖИНН ГОТОВ ИСПОЛНЯТЬ ЖЕЛАНИЯ!")
|
||||||
print(f"Человек: {current_wish}\n")
|
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.get('content'):
|
"""Возвращает строку, которую нужно вывести в консоль."""
|
||||||
return message['content']
|
if message.content:
|
||||||
elif message.get('tool_calls'):
|
return message.content
|
||||||
tool_call = message['tool_calls'][0]
|
if message.tool_calls:
|
||||||
return f"{tool_call['name']}({tool_call['args']})"
|
tool_call = message.tool_calls[0]
|
||||||
|
return f"{tool_call.name}({tool_call.args})"
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
step = 1
|
step = 1
|
||||||
|
|
||||||
def format_chunk_message(chunk):
|
def format_chunk_message(chunk):
|
||||||
|
"""Обрабатывает чанк типа 'messages'."""
|
||||||
global step
|
global step
|
||||||
message, meta = chunk
|
message, meta = chunk
|
||||||
|
|
||||||
if meta['langgraph_step'] != step:
|
if meta["langgraph_step"] != step:
|
||||||
step = meta['langgraph_step']
|
step = meta["langgraph_step"]
|
||||||
print('\n --- --- --- \n')
|
print("\n --- --- --- \n")
|
||||||
|
|
||||||
if message.get('content'):
|
if message.content:
|
||||||
print(message['content'], end='', flush=False)
|
# выводим токен без перевода строки, чтобы текст «тёк»
|
||||||
|
print(message.content, end="", flush=True)
|
||||||
|
|
||||||
|
|
||||||
|
# --- Потоковый вызов --------------------------------------------------------
|
||||||
stream = human_agent.stream(
|
stream = human_agent.stream(
|
||||||
{
|
{
|
||||||
"messages": [
|
"messages": [
|
||||||
{"role": "human", "content": f"Вот мое желание: '{current_wish}'. Проверь его у джинна через инструмент check_wish и скажи мне результат."}
|
{
|
||||||
|
"role": "human",
|
||||||
|
"content": (
|
||||||
|
f"Вот мое желание: '{current_wish}'. Проверь его у джинна "
|
||||||
|
"через инструмент check_wish и скажи мне результат."
|
||||||
|
),
|
||||||
|
}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
stream_mode=['messages', 'updates']
|
stream_mode=["messages", "updates"],
|
||||||
)
|
)
|
||||||
|
|
||||||
full_response = ""
|
full_response = ""
|
||||||
for chunk in stream:
|
|
||||||
chunk_type, chunk_data = chunk
|
|
||||||
|
|
||||||
if chunk_type == 'messages':
|
for chunk_type, chunk_data in stream:
|
||||||
|
if chunk_type == "messages":
|
||||||
format_chunk_message(chunk_data)
|
format_chunk_message(chunk_data)
|
||||||
message, _ = chunk_data
|
message, _ = chunk_data
|
||||||
if message.get('content'):
|
full_response += message.content or ""
|
||||||
full_response += message['content']
|
elif chunk_type == "updates":
|
||||||
|
# событие завершения шага (например, вызов инструмента)
|
||||||
elif chunk_type == 'updates':
|
if chunk_data.get("model"):
|
||||||
if chunk_data.get('model', None):
|
last_msg = chunk_data["model"]["messages"][-1]
|
||||||
last_message = chunk_data['model']['messages'][-1]
|
formatted = format_message(last_msg)
|
||||||
formatted = format_message(last_message)
|
|
||||||
if formatted:
|
if formatted:
|
||||||
print(f"\n[Вызов инструмента: {formatted}]")
|
print(f"\n[Вызов инструмента: {formatted}]")
|
||||||
full_response += f"\n[Вызов инструмента: {formatted}]\n"
|
full_response += f"\n[Вызов инструмента: {formatted}]\n"
|
||||||
|
|
||||||
print("\n")
|
print("\n")
|
||||||
|
|
||||||
|
# --- Итог -------------------------------------------------------------------
|
||||||
if "исполняю" in full_response.lower() or "безопасно" in full_response.lower():
|
if "исполняю" in full_response.lower() or "безопасно" in full_response.lower():
|
||||||
print(f" Желание исполнено! Финальная версия: {current_wish}")
|
print(f" Желание исполнено! Финальная версия: {current_wish}")
|
||||||
else:
|
else:
|
||||||
print(f" Джинн отказался исполнять желание: {current_wish}")
|
print(f" Джинн отказался исполнять желание: {current_wish}")
|
||||||
if full_response:
|
if full_response:
|
||||||
clean_response = full_response.replace('\n', ' ').strip()
|
clean_response = full_response.replace("\n", " ").strip()
|
||||||
print(f" Причина: {clean_response}")
|
print(f" Причина: {clean_response}")
|
||||||
else:
|
else:
|
||||||
print(" Джинн устал...")
|
print(" Джинн устал...")
|
||||||
Reference in New Issue
Block a user