Files
task-699cc158d6d3a5544a3ed35b/main.py
T

110 lines
3.6 KiB
Python

import os
import asyncio
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
from langchain.tools import tool
from deepagents import create_deep_agent
from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
# -------------------------------------------------
# LLM configuration (OpenRouter)
# -------------------------------------------------
llm = ChatOpenAI(
model="openai/gpt-oss-20b:free",
base_url="https://openrouter.ai/api/v1",
api_key=os.getenv("OPENAI_API_KEY"),
temperature=0.0,
)
# -------------------------------------------------
# Backend for tool execution
# -------------------------------------------------
backend = CompositeBackend(
[
LocalShellBackend(workspace_dir="./workspace"),
FilesystemBackend(),
]
)
# -------------------------------------------------
# Example tool (can be replaced with any real tool)
# -------------------------------------------------
@tool
def get_price(product: str, city: str) -> str:
"""
Return a mock price table for the given product in the specified city.
"""
# In a real scenario this could call an external API or run a script.
return f"""| Продукт | Цена (руб.) | Город |
| {product} | 89 | {city} |
"""
# -------------------------------------------------
# Create the deep agent
# -------------------------------------------------
agent = create_deep_agent(
model=llm,
tools=[get_price],
backend=backend,
system_prompt="You are a helpful assistant that can call tools when needed.",
)
# -------------------------------------------------
# Helper functions for streaming output
# -------------------------------------------------
def format_message(message) -> str:
"""
Convert a LangChain message to a printable string.
If the message contains tool calls, format them as a function call.
"""
if getattr(message, "content", None):
return message.content
# Tool call case
if getattr(message, "tool_calls", None):
tool_call = message.tool_calls[0]
name = tool_call["name"]
args = tool_call["args"]
return f"{name}({args})"
return ""
def format_chunk_message(chunk):
"""
Print token fragments from 'messages' chunks.
Insert a separator when the LangGraph step changes.
"""
message, meta = chunk
global current_step
step = meta.get("langgraph_step", 0)
if step != current_step:
current_step = step
print("\n--- --- ---\n")
if getattr(message, "content", None):
print(message.content, end="", flush=True)
# -------------------------------------------------
# Main async entry point
# -------------------------------------------------
async def main():
user_query = "Сколько стоит молоко в Казани?"
stream = agent.stream(
{"messages": [HumanMessage(content=user_query)]},
stream_mode=["messages", "updates"],
)
global current_step
current_step = -1 # initialize step counter
for chunk_type, chunk_data in stream:
if chunk_type == "messages":
format_chunk_message(chunk_data)
elif chunk_type == "updates":
# When a model update contains a finished message, print it nicely
model_info = chunk_data.get("model")
if model_info and "messages" in model_info:
last_msg = model_info["messages"][-1]
print("\n" + format_message(last_msg))
# Ensure final newline
print()
if __name__ == "__main__":
asyncio.run(main())