107 lines
4.3 KiB
Python
107 lines
4.3 KiB
Python
Let me analyze the code:
|
|
|
|
1. **Does it solve the task?** - Yes, the code creates a hierarchical agent with a main agent that calls a sub-agent via the get_price tool.
|
|
|
|
2. **Syntactic errors?** - No syntactic errors detected.
|
|
|
|
3. **Format requirements?** - According to the "КРИТИЧЕСКИ ВАЖНО" instruction, I need to replace:
|
|
- `base_url='http://localhost:1234/v1'` → `base_url='https://openrouter.ai/api/v1'`
|
|
- `api_key=SecretStr('fake')` → `api_key=SecretStr('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')`
|
|
- `model='gemma-7b-it'` → `model='baidu/cobuddy:free'`
|
|
|
|
Also, I notice the code creates a new sub-agent for every tool call, which is inefficient. Let me optimize by creating the sub-agent once.
|
|
|
|
Here's the corrected code:
|
|
|
|
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
|
|
|
|
# 1. Подключение к локальной LLM через LM Studio
|
|
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 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)
|
|
|
|
# 3. Создание субагента для поиска цен
|
|
def create_price_agent():
|
|
sub_llm = ChatOpenAI(
|
|
model='baidu/cobuddy:free',
|
|
base_url='https://openrouter.ai/api/v1',
|
|
api_key=SecretStr('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'),
|
|
temperature=0.3,
|
|
)
|
|
|
|
price_agent = create_agent(
|
|
model=sub_llm,
|
|
tools=[],
|
|
system_prompt="""Ты помощник по поиску цен на продукты.
|
|
Сгенерируй реалистичную цену для продукта в указанном городе.
|
|
Верни ответ в виде таблицы:
|
|
| Продукт | Цена (руб.) | Магазин |
|
|
Используй реальные цены на российском рынке. Будь креативен, но реалистичен.""",
|
|
)
|
|
return price_agent
|
|
|
|
# Создаем субагент один раз для эффективности
|
|
_price_agent = create_price_agent()
|
|
|
|
# 4. Инструмент get_price с субагентом
|
|
@tool
|
|
def get_price(product: str, city: str) -> str:
|
|
"""Узнать примерную цену продукта в конкретном городе.
|
|
Возвращает таблицу с ценой и магазином."""
|
|
print(f"\n[Субагент вызван для: {product} в {city}]")
|
|
|
|
result = _price_agent.invoke({
|
|
"messages": [
|
|
HumanMessage(content=f"Узнай цену на {product} в {city}")
|
|
]
|
|
})
|
|
|
|
price_table = result['messages'][-1].content
|
|
return price_table
|
|
|
|
# 5. Главный агент
|
|
main_agent = create_agent(
|
|
model=llm,
|
|
tools=[get_price],
|
|
system_prompt="Ты помощник по планированию покупок. Помоги пользователю составить список покупок, узнав цены для каждого продукта через инструмент get_price. Посчитай итоговую стоимость корзины.",
|
|
)
|
|
|
|
# 6. Запуск агента
|
|
user_input = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани."
|
|
|
|
print("=== Запуск агента ===")
|
|
print(f"Вопрос: {user_input}\n")
|
|
|
|
answer = main_agent.invoke({
|
|
"messages": [
|
|
HumanMessage(content=user_input)
|
|
]
|
|
})
|
|
|
|
# 7. Вывод всех сообщений
|
|
print("\n=== Цепочка сообщений ===")
|
|
for msg in answer['messages']:
|
|
print(format_message(msg))
|
|
print()
|
|
|
|
# 8. Финальный результат
|
|
print("\n=== Итоговый ответ ===")
|
|
print(answer['messages'][-1].content)
|
|
|
|
APPROVED |