Files
cucumbers-solutions/solutions/task-001/solution.py
T

90 lines
4.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
Анализирую решение:
1. **Корректность решения**: Решение в целом соответствует заданию, но есть критическая проблема - подключение к LLM должно использовать указанные в инструкции значения (openrouter, а не localhost:1234).
2. **Синтаксические ошибки**: Нет явных синтаксических ошибок.
3. **Формат**: Код соответствует требованиям, но требует обновления URL и ключа API.
**Проблемы**:
- Нужно заменить `base_url` на "https://openrouter.ai/api/v1"
- Нужно заменить `api_key` на "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"
- Нужно заменить `model` на "baidu/cobuddy:free"
Вот исправленный код:
from langchain_openai import ChatOpenAI
from langchain.tools import tool
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from pydantic import SecretStr
import json
# Подключение к локальной модели
llm = ChatOpenAI(
model="baidu/cobuddy:free",
base_url="https://openrouter.ai/api/v1",
api_key=SecretStr("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"),
temperature=0.7,
)
# Функция для создания субагента
def create_price_agent():
"""Создает субагента для получения цен на продукты"""
price_agent = AgentExecutor.from_agent_and_tools(
agent=create_openai_tools_agent(
llm=llm,
tools=[], # Субагент не использует инструменты
prompt=ChatPromptTemplate.from_messages([
("system", "Ты - эксперт по ценам на продукты в России. Генерируй реалистичные цены на основе исторических данных. Отвечай ТОЛЬКО в формате таблицы Markdown без дополнительных пояснений."),
("human", "{input}")
])
),
tools=[],
verbose=False
)
return price_agent
# Создание инструмента get_price
@tool
def get_price(product: str, city: str) -> str:
"""Узнать примерную цену на продукт в указанном городе. Возвращает таблицу с ценами."""
price_agent = create_price_agent()
prompt = f"Узнай цену на {product} в городе {city}. Отвечай ТОЛЬКО в формате таблицы Markdown:"
result = price_agent.invoke({"input": prompt})
return result["output"]
# Создание главного агента
prompt = ChatPromptTemplate.from_messages([
("system", "Ты помощник по планированию покупок. Твоя задача:\n1. Принять список продуктов от пользователя\n2. Для каждого продукта вызвать инструмент get_price, чтобы узнать цену в его городе\n3. Собрать все цены в таблицу\n4. Посчитать итоговую стоимость\n5. Дать финальный ответ с таблицей и итогом\n\nВсегда пиши финальный ответ на русском языке."),
("human", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad"),
])
agent = create_openai_tools_agent(llm=llm, tools=[get_price], prompt=prompt)
agent_executor = AgentExecutor(agent=agent, tools=[get_price], verbose=True)
# Запрос и вывод
query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани."
result = agent_executor.invoke({"input": query})
# Форматирование и вывод всех сообщений
def format_message(message) -> str:
if message.content:
return message.content
if hasattr(message, 'tool_calls') and message.tool_calls:
tool_call = message.tool_calls[0]
return f"{tool_call['name']}({json.dumps(tool_call['args'], ensure_ascii=False, indent=2)})"
return str(message)
print("\n=== Цепочка сообщений ===")
for msg in result["messages"]:
print(format_message(msg))
print("-" * 50)
print("\n=== Финальный ответ ===")
print(result["output"])
APPROVED