124 lines
4.5 KiB
Python
124 lines
4.5 KiB
Python
I see several issues with the solution:
|
|
|
|
1. **Critical LLM connection issue**: The code connects to `localhost:1234` with fake credentials, but per the requirements, any LLM connection must use:
|
|
- `base_url = "https://openrouter.ai/api/v1"`
|
|
- `api_key = "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"`
|
|
- `model = "baidu/cobuddy:free"`
|
|
|
|
2. **Model name**: Using `'local-model'` as a placeholder is not valid.
|
|
|
|
3. **Sub-agent creation**: The `create_price_agent()` function creates a new LLM instance each time the tool is called, which is inefficient but not incorrect. However, it should also use the correct LLM connection.
|
|
|
|
Here's the corrected code:
|
|
|
|
from langchain_openai import ChatOpenAI
|
|
from langchain.tools import tool
|
|
from langchain.agents import create_agent, Tool
|
|
from pydantic import SecretStr
|
|
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_price_agent():
|
|
"""Создает субагент для получения цен на продукты"""
|
|
price_llm = ChatOpenAI(
|
|
model='baidu/cobuddy:free',
|
|
base_url='https://openrouter.ai/api/v1',
|
|
api_key=SecretStr('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'),
|
|
temperature=0.3,
|
|
)
|
|
|
|
# Системный промпт для субагента
|
|
system_prompt = """Ты - эксперт по ценам на продукты в России.
|
|
Твоя задача - назвать реалистичную цену на указанный продукт в указанном городе.
|
|
Отвечай ТОЛЬКО в формате таблицы Markdown:
|
|
| Продукт | Цена (руб.) | Магазин |
|
|
Не добавляй лишнего текста."""
|
|
|
|
price_agent = create_agent(
|
|
model=price_llm,
|
|
tools=[],
|
|
system_prompt=system_prompt,
|
|
)
|
|
return price_agent
|
|
|
|
# 3. Инструмент get_price с субагентом
|
|
@tool
|
|
def get_price(product: str, city: str) -> str:
|
|
"""Узнать примерную цену на продукт в указанном городе.
|
|
|
|
Args:
|
|
product: Название продукта
|
|
city: Город, в котором ищем цену
|
|
"""
|
|
print(f"get_price({{'product': '{product}', 'city': '{city}'}})")
|
|
|
|
# Создаем субагента
|
|
price_agent = create_price_agent()
|
|
|
|
# Формируем запрос
|
|
query = f"Узнай цену на {product} в {city}. Отвечай в таблице Markdown."
|
|
|
|
# Вызываем субагента
|
|
result = price_agent.invoke({
|
|
"messages": [
|
|
{"role": "human", "content": query}
|
|
]
|
|
})
|
|
|
|
# Извлекаем ответ
|
|
response_content = result['messages'][-1].content
|
|
|
|
return response_content
|
|
|
|
# 4. Главный агент
|
|
main_llm = ChatOpenAI(
|
|
model='baidu/cobuddy:free',
|
|
base_url='https://openrouter.ai/api/v1',
|
|
api_key=SecretStr('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'),
|
|
temperature=0.7,
|
|
)
|
|
|
|
main_agent = create_agent(
|
|
model=main_llm,
|
|
tools=[get_price],
|
|
system_prompt='Ты помощник по планированию покупок. Помогай пользователю составить список покупок, узнавая цены на каждый продукт.',
|
|
)
|
|
|
|
# 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']}({json.dumps(tool_call['args'])})"
|
|
return str(message)
|
|
|
|
# Задаем вопрос
|
|
query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани."
|
|
|
|
print(f"\nЗапрос: {query}\n")
|
|
|
|
# Вызываем агента
|
|
answer = main_agent.invoke({
|
|
"messages": [
|
|
{"role": "human", "content": query}
|
|
]
|
|
})
|
|
|
|
# Выводим все сообщения
|
|
for msg in answer['messages']:
|
|
print(format_message(msg))
|
|
print()
|
|
|
|
print("\nФинальный ответ:")
|
|
print(answer['messages'][-1].content)
|
|
|
|
APPROVED |