From 9a058f8b118e5d0699946c4d8224ed2c7fd89b1f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9A=D0=B8=D1=80=D0=B8=D0=BB=D0=BB=20=D0=A0=D0=BE=D0=BC?= =?UTF-8?q?=D0=B0=D0=BD=D0=BE=D0=B2?= Date: Thu, 7 May 2026 16:30:12 +0000 Subject: [PATCH] Add main.py --- stream-agent/main.py | 57 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 stream-agent/main.py diff --git a/stream-agent/main.py b/stream-agent/main.py new file mode 100644 index 0000000..3d9984f --- /dev/null +++ b/stream-agent/main.py @@ -0,0 +1,57 @@ +import os +from langchain_openai import ChatOpenAI +from langchain_core.prompts import PromptTemplate +from langchain_core.output_parsers import PydanticOutputParser +from langchain_core.messages import HumanMessage +from langchain_core.tools import tool +from typing import List + +# --- +# Пример задачи: вывести таблицу цен на продукты в Казани +# --- + +# 1. Определяем модель +llm = ChatOpenAI(temperature=0, model="gpt-4o") + +# 2. Создаём инструмент (псевдо‑вывод таблицы) +@tool +def get_price(product: str, city: str = "Казань") -> str: + """Возвращает строку с ценами продукта в указанном городе.""" + # Для примера фиксированные данные + prices = { + "молоко": "89", + "хлеб": "30", + "сахар": "70", + } + return f"{product} в {city}: {prices.get(product, 'не найден')} руб." + +# 3. Создаём агента +from langchain.agents import create_openai_functions_agent, AgentExecutor + +agent = create_openai_functions_agent(llm=llm, tools=[get_price]) + +# 4. Выполняем в режиме stream +executor = AgentExecutor(agent=agent, tools=[get_price], verbose=False) + +# Запускаем +input_message = "Какая цена на молоко и хлеб в Казани?" + +# Stream +stream = executor.stream( + {"messages": [HumanMessage(content=input_message)]}, + stream_mode=["messages"], +) + +step = 1 +for chunk in stream: + chunk_type, chunk_data = chunk + if chunk_type == "messages": + message, meta = chunk_data + if meta["langgraph_step"] != step: + step = meta["langgraph_step"] + print("\n---------\n") + if message.content: + print(message.content, end="", flush=True) + +# В конце выводим результат +print("\n\n---\n" + executor.run({"messages": [HumanMessage(content=input_message)]})["output"])