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

This commit is contained in:
2026-07-02 06:39:22 +00:00
parent ef8fec4c1a
commit ed1095868d
+66 -60
View File
@@ -1,27 +1,26 @@
import os import os
import asyncio import asyncio
from typing import List from typing import Any, Dict, List
from pydantic import SecretStr 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, AIMessage, ToolMessage
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 CompositeBackend, LocalShellBackend, FilesystemBackend
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Configuration of the LLM (OpenRouter, as required by the course) # LLM configuration (OpenRouter)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
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",
api_key=SecretStr(os.getenv("OPENAI_API_KEY")), api_key=os.getenv("OPENAI_API_KEY"),
temperature=0.7, temperature=0.7,
) )
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Backend for the agents - allows file operations and shell commands # Backend for sub-agents (allows file operations and shell commands)
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
backend = CompositeBackend( backend = CompositeBackend(
[ [
@@ -31,84 +30,91 @@ backend = CompositeBackend(
) )
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Sub-agent tool: get_price # Sub-agent that generates a realistic price table for a product
# ----------------------------------------------------------------------
def create_price_subagent() -> Any:
"""
Returns a deep agent that, given a product and a city, produces a markdown
table with product, price and store. The prompt forces the model to fabricate
plausible data based on typical market prices.
"""
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(
model=llm,
tools=[], # no external tools needed for this simple sub-agent
backend=backend,
system_prompt=system_prompt,
)
return 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.
Возвращает markdown-таблицу с колонками: Продукт, Цена (руб.), Магазин. Returns a markdown table with columns: Продукт, Цена (руб.), Магазин.
""" """
# Создаём суб-агента, который генерирует цену. # Build the prompt for the sub-agent
sub_agent = create_deep_agent( prompt = f"Продукт: {product}\nГород: {city}"
model=llm, # Invoke the sub-agent synchronously (deepagents also supports async,
tools=[], # but a simple sync call keeps the example straightforward)
backend=backend, result = asyncio.run(
system_prompt=( price_subagent.ainvoke(
"Ты суб-агент, который генерирует реалистичную цену продукта " {"messages": [HumanMessage(content=prompt)]},
"в заданном городе. Выдай результат в виде markdown-таблицы "
"с колонками: Продукт, Цена (руб.), Магазин."
),
)
# Формируем запрос к суб-агенту
query = f"Сгенерируй цену для продукта '{product}' в городе {city}."
# Асинхронный вызов суб-агента
async def _invoke():
result = await sub_agent.ainvoke(
{"messages": [HumanMessage(content=query)]},
{"configurable": {"thread_id": f"price-{product}-{city}"}}, {"configurable": {"thread_id": f"price-{product}-{city}"}},
) )
# Последнее сообщение содержит таблицу )
return result["messages"][-1].content # The sub-agent returns a list of messages; the last one contains the table
final_message = result["messages"][-1]
# Запускаем цикл событий, если уже внутри async контекста if isinstance(final_message, AIMessage):
try: return final_message.content
loop = asyncio.get_running_loop() elif isinstance(final_message, ToolMessage):
table = loop.create_task(_invoke()) return final_message.content
# Если мы уже в async функции, вернём задачу, иначе дождёмся результата else:
if isinstance(table, asyncio.Task): return str(final_message)
return asyncio.run(table)
except RuntimeError:
# Нет запущенного цикла - создаём новый
return asyncio.run(_invoke())
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
# Main shopping-assistant agent # Main shopping-list agent
# ---------------------------------------------------------------------- # ----------------------------------------------------------------------
assistant_agent = create_deep_agent( shopping_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:
# Helper to format the chain of messages for display """Human-readable representation of a message or tool call."""
# ---------------------------------------------------------------------- if isinstance(msg, (HumanMessage, AIMessage)):
def format_message(msg) -> str: return msg.content
if isinstance(msg, HumanMessage):
return f"Human: {msg.content}"
if isinstance(msg, AIMessage):
return f"AI: {msg.content}"
if isinstance(msg, ToolMessage): if isinstance(msg, ToolMessage):
# tool call result return f"{msg.name}({msg.args}) -> {msg.content}"
return f"ToolResult: {msg.content}" # Fallback for generic dict-like messages
# Fallback for generic messages if hasattr(msg, "tool_calls") and msg.tool_calls:
call = msg.tool_calls[0]
return f"{call['name']}({call['args']})"
return str(msg) return str(msg)
async def main(): async def main() -> None:
user_query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани." user_query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани."
result = await assistant_agent.ainvoke( result = await shopping_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
# Выводим всю цепочку сообщений for i, message in enumerate(result["messages"]):
print("\n--- Диалог с агентом ---\n") print(f"--- Message {i + 1} ---")
for m in result["messages"]: print(format_message(message))
print(format_message(m)) print()
print("---")
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())