feat: solution for 'Untitled Task'
This commit is contained in:
+2
-1
@@ -1 +1,2 @@
|
||||
langgraph\nlangchain\nopenai\npython-dotenv\n
|
||||
langchain==0.2.0
|
||||
openai==1.30.0
|
||||
+76
@@ -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()
|
||||
Reference in New Issue
Block a user