fix: main.py — Создайть просто AI агент на Python с применением langchain

This commit is contained in:
2026-07-02 07:06:28 +00:00
parent 6489fb5fc0
commit 7da640e2c7
+53 -53
View File
@@ -1,17 +1,18 @@
import os import os
import asyncio import asyncio
from typing import Any, Dict, List from typing import List, Dict, Any
from pydantic import SecretStr
from langchain_openai import ChatOpenAI from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, AIMessage, ToolMessage from langchain_core.messages import HumanMessage, BaseMessage
from langchain.tools import tool from langchain.tools import tool
from deepagents import create_deep_agent from deepagents import create_deep_agent
from deepagents.backends import CompositeBackend, LocalShellBackend, FilesystemBackend from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# LLM configuration (OpenRouter) # Configuration
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# LLM - OpenRouter (free tier). The API key must be stored in the environment.
llm = ChatOpenAI( llm = ChatOpenAI(
model="openai/gpt-oss-20b:free", model="openai/gpt-oss-20b:free",
base_url="https://openrouter.ai/api/v1", base_url="https://openrouter.ai/api/v1",
@@ -19,9 +20,8 @@ llm = ChatOpenAI(
temperature=0.7, temperature=0.7,
) )
# ---------------------------------------------------------------------- # Backend for the agents - a simple composite that allows file operations
# Backend for sub-agents (allows file operations and shell commands) # and execution of shell commands inside a sandboxed workspace.
# ----------------------------------------------------------------------
backend = CompositeBackend( backend = CompositeBackend(
[ [
LocalShellBackend(workspace_dir="./workspace"), LocalShellBackend(workspace_dir="./workspace"),
@@ -30,90 +30,90 @@ backend = CompositeBackend(
) )
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Sub-agent that generates a realistic price table for a product # Sub-agent: price generator
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
def create_price_subagent() -> Any: def _create_price_subagent() -> Any:
""" """
Returns a deep agent that, given a product and a city, produces a markdown Creates a lightweight sub-agent that, given a product and a city,
table with product, price and store. The prompt forces the model to fabricate returns a markdown table with a plausible price and a store name.
plausible data based on typical market prices. The sub-agent re-uses the same LLM and backend as the main agent.
""" """
system_prompt = (
"You are a price-generation sub-agent. Given a product name and a city, "
"return a markdown table with columns: Продукт, Цена (руб.), Магазин. "
"Fabricate realistic prices based on typical Russian market data. "
"Do not add any extra commentary, only the table."
)
subagent = create_deep_agent( subagent = create_deep_agent(
model=llm, model=llm,
tools=[], # no external tools needed for this simple sub-agent tools=[], # No additional tools are required for price generation
backend=backend, backend=backend,
system_prompt=system_prompt, system_prompt=(
"You are a price-estimation sub-agent. "
"Given a product name and a city, generate a realistic price "
"in Russian rubles and suggest a typical store. "
"Return the result as a markdown table with columns: "
"`Продукт`, `Цена (руб.)`, `Магазин`."
),
) )
return subagent return subagent
price_subagent = create_price_subagent() _price_subagent = _create_price_subagent()
# ----------------------------------------------------------------------
# Tool that calls the sub-agent
# ----------------------------------------------------------------------
@tool @tool
def get_price(product: str, city: str) -> str: def get_price(product: str, city: str) -> str:
""" """
Generate a realistic price for the given product in the specified city. Estimate the price of a product in a given city.
Returns a markdown table with columns: Продукт, Цена (руб.), Магазин. The function creates a sub-agent that returns a markdown table:
| Продукт | Цена (руб.) | Магазин |
""" """
# Build the prompt for the sub-agent # Build the prompt for the sub-agent
prompt = f"Продукт: {product}\nГород: {city}" prompt = HumanMessage(
# Invoke the sub-agent synchronously (deepagents also supports async, content=f"Продукт: {product}\nГород: {city}\nСгенерируй цену."
# but a simple sync call keeps the example straightforward) )
# Invoke the sub-agent asynchronously and wait for the result
result = asyncio.run( result = asyncio.run(
price_subagent.ainvoke( _price_subagent.ainvoke(
{"messages": [HumanMessage(content=prompt)]}, {"messages": [prompt]},
{"configurable": {"thread_id": f"price-{product}-{city}"}}, {"configurable": {"thread_id": f"price-{product}-{city}"}},
) )
) )
# The sub-agent returns a list of messages; the last one contains the table # The sub-agent returns a list of messages; the last one contains the table
final_message = result["messages"][-1] final_message = result["messages"][-1]
if isinstance(final_message, AIMessage): return final_message.content if isinstance(final_message, BaseMessage) else str(final_message)
return final_message.content
elif isinstance(final_message, ToolMessage):
return final_message.content
else:
return str(final_message)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Main shopping-list agent # Main agent: shopping list planner
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
shopping_agent = create_deep_agent( main_agent = create_deep_agent(
model=llm, model=llm,
tools=[get_price], tools=[get_price],
backend=backend, backend=backend,
system_prompt="Ты помощник по планированию покупок.", system_prompt="Ты помощник по планированию покупок.",
) )
def format_message(msg: Any) -> str: def format_message(msg: BaseMessage) -> str:
"""Human-readable representation of a message or tool call.""" """
if isinstance(msg, (HumanMessage, AIMessage)): Convert a LangChain message to a readable string.
Handles normal text messages and tool calls.
"""
if hasattr(msg, "content") and msg.content:
return msg.content return msg.content
if isinstance(msg, ToolMessage): # Tool call representation
return f"{msg.name}({msg.args}) -> {msg.content}"
# Fallback for generic dict-like messages
if hasattr(msg, "tool_calls") and msg.tool_calls: if hasattr(msg, "tool_calls") and msg.tool_calls:
call = msg.tool_calls[0] call = msg.tool_calls[0]
return f"{call['name']}({call['args']})" name = call["name"]
args = ", ".join(f"{k}={v!r}" for k, v in call["args"].items())
return f"{name}({args})"
return str(msg) return str(msg)
async def main() -> None: async def main() -> None:
user_query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани." user_query = (
result = await shopping_agent.ainvoke( "Помоги составить список покупок: молоко, хлеб, яблоки. "
"Я нахожусь в Казани."
)
result = await main_agent.ainvoke(
{"messages": [HumanMessage(content=user_query)]}, {"messages": [HumanMessage(content=user_query)]},
{"configurable": {"thread_id": "shopping-session-1"}}, {"configurable": {"thread_id": "shopping-session-1"}},
) )
# Print the whole chain of messages # Print the whole conversation chain
for i, message in enumerate(result["messages"]): for i, msg in enumerate(result["messages"], start=1):
print(f"--- Message {i + 1} ---") print(f"--- Message {i} ---")
print(format_message(message)) print(format_message(msg))
print() print()
if __name__ == "__main__": if __name__ == "__main__":