fix: main.py — Создайть просто AI агент на Python с применением langchain
This commit is contained in:
@@ -1,22 +1,28 @@
|
|||||||
import os
|
import os
|
||||||
import asyncio
|
import asyncio
|
||||||
from typing import Any
|
from typing import List
|
||||||
|
|
||||||
|
from pydantic import SecretStr
|
||||||
from langchain_openai import ChatOpenAI
|
from langchain_openai import ChatOpenAI
|
||||||
from langchain_core.messages import HumanMessage
|
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.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
|
|
||||||
|
|
||||||
# LLM configuration according to the assignment specification
|
from deepagents import create_deep_agent
|
||||||
|
from deepagents.backends import CompositeBackend, LocalShellBackend, FilesystemBackend
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
# Configuration of the LLM (OpenRouter, as required by the course)
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
llm = ChatOpenAI(
|
llm = ChatOpenAI(
|
||||||
model="your-model-name", # replace with the actual model name in LM Studio
|
model="openai/gpt-oss-20b:free",
|
||||||
base_url="http://localhost:1234/v1",
|
base_url="https://openrouter.ai/api/v1",
|
||||||
api_key="fake", # OpenAI SDK requires a non-empty key
|
api_key=SecretStr(os.getenv("OPENAI_API_KEY")),
|
||||||
temperature=0.7,
|
temperature=0.7,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Backend for file operations and shell commands (required by deepagents)
|
# ----------------------------------------------------------------------
|
||||||
|
# Backend for the agents - allows file operations and shell commands
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
backend = CompositeBackend(
|
backend = CompositeBackend(
|
||||||
[
|
[
|
||||||
LocalShellBackend(workspace_dir="./workspace"),
|
LocalShellBackend(workspace_dir="./workspace"),
|
||||||
@@ -24,78 +30,85 @@ backend = CompositeBackend(
|
|||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
# Sub-agent tool: get_price
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
@tool
|
@tool
|
||||||
def get_price(product: str, city: str) -> str:
|
def get_price(product: str, city: str) -> str:
|
||||||
"""
|
"""
|
||||||
Retrieve a realistic price for the given product in the specified city.
|
Получить примерную цену продукта в указанном городе.
|
||||||
The function creates a sub-agent that returns a markdown table row.
|
Возвращает markdown-таблицу с колонками: Продукт, Цена (руб.), Магазин.
|
||||||
"""
|
"""
|
||||||
# System prompt for the sub-agent - it must output a table with columns
|
# Создаём суб-агента, который генерирует цену.
|
||||||
# Product, Price (руб.), Store.
|
|
||||||
sub_system_prompt = (
|
|
||||||
"You are a price generator. Provide a markdown table with columns "
|
|
||||||
"'Продукт', 'Цена (руб.)', 'Магазин' for the given product and city. "
|
|
||||||
"Give a realistic price and a plausible store name."
|
|
||||||
)
|
|
||||||
|
|
||||||
# Create the sub-agent (no additional tools needed)
|
|
||||||
sub_agent = create_deep_agent(
|
sub_agent = create_deep_agent(
|
||||||
model=llm,
|
model=llm,
|
||||||
tools=[],
|
tools=[],
|
||||||
backend=backend,
|
backend=backend,
|
||||||
system_prompt=sub_system_prompt,
|
system_prompt=(
|
||||||
|
"Ты суб-агент, который генерирует реалистичную цену продукта "
|
||||||
|
"в заданном городе. Выдай результат в виде markdown-таблицы "
|
||||||
|
"с колонками: Продукт, Цена (руб.), Магазин."
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
# Prepare the query for the sub-agent
|
# Формируем запрос к суб-агенту
|
||||||
query = f"Provide price information for {product} in {city}."
|
query = f"Сгенерируй цену для продукта '{product}' в городе {city}."
|
||||||
|
# Асинхронный вызов суб-агента
|
||||||
# Invoke the sub-agent synchronously
|
async def _invoke():
|
||||||
# DESIGN DECISION: Use asyncio.run to execute the sub-agent inside a
|
result = await sub_agent.ainvoke(
|
||||||
# synchronous tool. deepagents operates asynchronously, but the tool
|
|
||||||
# interface required by the main agent is synchronous.
|
|
||||||
# NECESSITY: The assignment defines the tool as a regular function.
|
|
||||||
# OPTIMALITY: This approach keeps the code simple and avoids mixing
|
|
||||||
# async/sync contexts incorrectly.
|
|
||||||
# ALTERNATIVES CONSIDERED: Making the tool async (deepagents supports
|
|
||||||
# async tools) would require changes to the main agent invocation pattern,
|
|
||||||
# which is unnecessary for this educational example.
|
|
||||||
result = asyncio.run(
|
|
||||||
sub_agent.ainvoke(
|
|
||||||
{"messages": [HumanMessage(content=query)]},
|
{"messages": [HumanMessage(content=query)]},
|
||||||
{"configurable": {"thread_id": f"price-{product}-{city}"}},
|
{"configurable": {"thread_id": f"price-{product}-{city}"}},
|
||||||
)
|
)
|
||||||
)
|
# Последнее сообщение содержит таблицу
|
||||||
# Extract the final content from the sub-agent's response
|
|
||||||
return result["messages"][-1].content
|
return result["messages"][-1].content
|
||||||
|
|
||||||
# Main shopping-list agent
|
# Запускаем цикл событий, если уже внутри async контекста
|
||||||
agent = create_deep_agent(
|
try:
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
table = loop.create_task(_invoke())
|
||||||
|
# Если мы уже в async функции, вернём задачу, иначе дождёмся результата
|
||||||
|
if isinstance(table, asyncio.Task):
|
||||||
|
return asyncio.run(table)
|
||||||
|
except RuntimeError:
|
||||||
|
# Нет запущенного цикла - создаём новый
|
||||||
|
return asyncio.run(_invoke())
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
# Main shopping-assistant agent
|
||||||
|
# ----------------------------------------------------------------------
|
||||||
|
assistant_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(message: Any) -> str:
|
# ----------------------------------------------------------------------
|
||||||
"""Convert a LangChain message to a readable string."""
|
# Helper to format the chain of messages for display
|
||||||
if hasattr(message, "content") and message.content:
|
# ----------------------------------------------------------------------
|
||||||
return message.content
|
def format_message(msg) -> str:
|
||||||
if hasattr(message, "tool_calls") and message.tool_calls:
|
if isinstance(msg, HumanMessage):
|
||||||
tc = message.tool_calls[0]
|
return f"Human: {msg.content}"
|
||||||
return f"{tc['name']}({tc['args']})"
|
if isinstance(msg, AIMessage):
|
||||||
return str(message)
|
return f"AI: {msg.content}"
|
||||||
|
if isinstance(msg, ToolMessage):
|
||||||
|
# tool call result
|
||||||
|
return f"ToolResult: {msg.content}"
|
||||||
|
# Fallback for generic messages
|
||||||
|
return str(msg)
|
||||||
|
|
||||||
async def main() -> None:
|
async def main():
|
||||||
user_query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани."
|
user_query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани."
|
||||||
result = await agent.ainvoke(
|
result = await assistant_agent.ainvoke(
|
||||||
{"messages": [HumanMessage(content=user_query)]},
|
{"messages": [HumanMessage(content=user_query)]},
|
||||||
{"configurable": {"thread_id": "shopping-session-1"}},
|
{"configurable": {"thread_id": "shopping-session-1"}},
|
||||||
)
|
)
|
||||||
# Output the whole chain of messages
|
|
||||||
for idx, msg in enumerate(result["messages"], start=1):
|
# Выводим всю цепочку сообщений
|
||||||
print(f"--- Message {idx} ---")
|
print("\n--- Диалог с агентом ---\n")
|
||||||
print(format_message(msg))
|
for m in result["messages"]:
|
||||||
print()
|
print(format_message(m))
|
||||||
|
print("---")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
Reference in New Issue
Block a user