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

117 lines
4.9 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** необходимо заменить localhost на openrouter.ai согласно критическому требованию
2. **Модель** необходимо указать конкретную модель `baidu/cobuddy:free`
3. **API ключ** должен быть реальный ключ из инструкции
4. **Конструкция субагента** создание агента внутри инструмента с `@tool` декоратором может вызвать проблемы с областью видимости. Лучше создать субагента отдельно
5. **Формат вывода** код выводит все сообщения, но не форматирует промежуточные результаты в таблицу
Исправленный код:
from langchain_openai import ChatOpenAI
from pydantic import SecretStr
from langchain.tools import tool
from langchain.agents import create_agent
from langchain_core.messages import HumanMessage, ToolMessage
from typing import List
import json
# 1. Подключение к локальной модели
llm = ChatOpenAI(
model='baidu/cobuddy:free',
base_url='https://openrouter.ai/api/v1',
api_key=SecretStr('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'),
temperature=0.7,
)
# 2. Функция создания субагента для получения цены
def create_sub_agent(city: str, product: str):
"""Создает субагента для определения цены продукта"""
sub_agent = create_agent(
model=llm,
tools=[],
system_prompt=f"""Ты — эксперт по ценам продуктов в городе {city}.
На основе твоих знаний генерируй реалистичную цену для продукта "{product}".
Возвращает ответ в виде таблицы:
| Продукт | Цена (руб.) | Магазин |
Например:
| Молоко | 89 | Магнит |
Учитывай, что цены могут быть примерными и варьироваться."""
)
return sub_agent
# 3. Инструмент с субагентом
@tool
def get_price(product: str, city: str) -> str:
"""Узнать примерную цену продукта в указанном городе.
Возвращает таблицу с ценой и магазином."""
sub_agent = create_sub_agent(city, product)
response = sub_agent.invoke({
"messages": [
HumanMessage(content=f"Определи цену продукта: {product}")
]
})
result = response['messages'][-1].content
return result
# 4. Главный агент
main_agent = create_agent(
model=llm,
tools=[get_price],
system_prompt='Ты помощник по планированию покупок. '
'Твоя задача — помочь пользователю составить список покупок, '
'узнать цены на каждый продукт через инструмент get_price, '
'и посчитать итоговую стоимость. '
'Отвечай на русском языке.'
)
# 5. Функция форматирования сообщений
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']}({tool_call['args']})"
return str(message)
# 6. Запуск агента
def run_shopping_agent(products: List[str], city: str):
"""Запускает агента с запросом о списках покупок"""
query = f"Помоги составить список покупок: {', '.join(products)}. Я нахожусь в {city}."
print(f"Запрос: {query}\n")
print("Цепочка вызовов:\n")
# Вызываем агента
response = main_agent.invoke({
"messages": [
HumanMessage(content=query)
]
})
# Выводим все сообщения
messages = response['messages']
for msg in messages:
formatted = format_message(msg)
print(formatted)
print()
# Финальный ответ
final_response = messages[-1].content
print("\n" + "="*50)
print("Финальный ответ агента:")
print(final_response)
# Запуск
if __name__ == "__main__":
# Пример использования
products = ["молоко", "хлеб", "яблоки"]
city = "Казань"
run_shopping_agent(products, city)
**APPROVED**