From 65fc4654d4c51960072a3f97052cbe9ae01f904c Mon Sep 17 00:00:00 2001 From: kuzakhmetovartur Date: Thu, 28 May 2026 15:43:03 +0300 Subject: [PATCH] feat: solution for 'Untitled Task' --- requirements.txt | 3 +- src/main.py | 76 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index b7dd493..0e74ce2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,2 @@ -langgraph\nlangchain\nopenai\npython-dotenv\n \ No newline at end of file +langchain==0.2.0 +openai==1.30.0 \ No newline at end of file diff --git a/src/main.py b/src/main.py index e69de29..6d2ce99 100644 --- a/src/main.py +++ b/src/main.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +""" +Stream-режим AI-агента с использованием LangChain. +""" + +import os +from langchain import OpenAI +from langchain.agents import create_agent, AgentType +from langchain.tools import Tool + +# Define a simple echo tool +def echo(text: str) -> str: + """Echoes the input text.""" + return text + +echo_tool = Tool( + name="Echo", + func=echo, + description="Echoes the input text." +) + +# Create the LLM +llm = OpenAI(temperature=0) + +# Create the agent with the echo tool +agent = create_agent( + llm=llm, + tools=[echo_tool], + agent_type=AgentType.OPENAI_FUNCTIONS, + verbose=False, +) + +def format_message(message) -> str: + """ + Formats a message for printing. + If the message contains content, returns it. + Otherwise, formats the tool call. + """ + if getattr(message, "content", None): + return message.content + # For tool calls + tool_call = message.tool_calls[0] + return f"{tool_call['name']}({tool_call['args']})" + +def main(): + user_input = input("Введите сообщение: ") + # Start streaming + stream = agent.stream( + {"messages": [{"role": "user", "content": user_input}]}, + stream_mode=["messages", "updates"] + ) + + step = 1 + for chunk_type, chunk_data in stream: + if chunk_type == "messages": + # chunk_data is a tuple (message, meta) + message, meta = chunk_data + # Insert separator when step changes + if meta.get("langgraph_step") != step: + step = meta.get("langgraph_step") + print("\n --- --- --- \n") + # Print the message content without newline + if getattr(message, "content", None): + print(message.content, end="", flush=True) + elif chunk_type == "updates": + # chunk_data contains information about completed steps + if chunk_data.get("model"): + last_message = chunk_data["model"]["messages"][-1] + formatted = format_message(last_message) + print(formatted, end="", flush=True) + + # Final newline after streaming is done + print() + +if __name__ == "__main__": + main() \ No newline at end of file