fix(needs_fixes): 2 исправлений, 0 отстояно — main.py
This commit is contained in:
@@ -1,47 +1,62 @@
|
|||||||
import os
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from langchain_openai import ChatOpenAI
|
from langchain_openai import ChatOpenAI
|
||||||
|
from pydantic import SecretStr
|
||||||
from langchain.tools import tool
|
from langchain.tools import tool
|
||||||
from langchain.agents import create_agent
|
from deepagents import create_deep_agent
|
||||||
|
from deepagents.backends import CompositeBackend, LocalShellBackend, FilesystemBackend
|
||||||
from langchain_core.messages import HumanMessage
|
from langchain_core.messages import HumanMessage
|
||||||
|
|
||||||
# Настройка LLM через OpenRouter
|
# 1. Подключение к локальной LLM
|
||||||
llm = ChatOpenAI(
|
llm = ChatOpenAI(
|
||||||
model="openai/gpt-oss-20b:free",
|
model='llama3.1-8b',
|
||||||
base_url="https://openrouter.ai/api/v1",
|
base_url='http://localhost:1234/v1',
|
||||||
api_key=os.getenv("OPENAI_API_KEY"),
|
api_key=SecretStr('fake'),
|
||||||
temperature=0.7,
|
temperature=0.7,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Инструмент, который вызывает субагент для получения цены
|
# 2. Backend для deepagents
|
||||||
|
backend = CompositeBackend([
|
||||||
|
LocalShellBackend(workspace_dir='./workspace'),
|
||||||
|
FilesystemBackend(),
|
||||||
|
])
|
||||||
|
|
||||||
|
# 3. Субагент, генерирующий цену
|
||||||
@tool
|
@tool
|
||||||
def get_price(product: str, city: str) -> str:
|
def get_price(product: str, city: str) -> str:
|
||||||
"""Получить примерную цену продукта в указанном городе.
|
"""Получить примерную цену продукта в указанном городе.
|
||||||
Возвращает таблицу в формате Markdown.
|
Возвращает таблицу в формате Markdown.
|
||||||
"""
|
"""
|
||||||
# Создаём субагент, который генерирует таблицу
|
# Создаём субагент, который просто генерирует реалистичную цену
|
||||||
sub_agent = create_agent(
|
sub_agent = create_deep_agent(
|
||||||
model=llm,
|
model=llm,
|
||||||
tools=[],
|
tools=[],
|
||||||
system_prompt=f"Ты эксперт по ценам в {city}.\n\nДай таблицу: | Продукт | Цена (руб.) | Магазин |", # простая подсказка
|
backend=backend,
|
||||||
|
system_prompt=f"Ты эксперт по ценам в {city}. Дай таблицу с продуктом, ценой и магазином.",
|
||||||
)
|
)
|
||||||
# Запускаем субагент с запросом
|
# Запрос к субагенту
|
||||||
sub_prompt = f"Какова примерная цена на {product} в {city}?"
|
response = asyncio.run(sub_agent.ainvoke(
|
||||||
result = sub_agent.invoke({"messages": [HumanMessage(content=sub_prompt)]})
|
{"messages": [HumanMessage(content=f"Сгенерируй таблицу цены для продукта {product} в городе {city}.")]},
|
||||||
# Извлекаем последний текстовый ответ
|
{"configurable": {"thread_id": f"price-{product}-{city}"}},
|
||||||
return result["messages"][-1].content
|
))
|
||||||
|
# Предполагаем, что последний элемент содержит таблицу
|
||||||
|
return response["messages"][-1].content
|
||||||
|
|
||||||
# Главный агент
|
# 4. Главный агент
|
||||||
agent = create_agent(
|
agent = create_deep_agent(
|
||||||
model=llm,
|
model=llm,
|
||||||
tools=[get_price],
|
tools=[get_price],
|
||||||
system_prompt="Ты помощник по планированию покупок.",
|
backend=backend,
|
||||||
|
system_prompt='Ты помощник по планированию покупок.',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 5. Запуск
|
||||||
async def main():
|
async def main():
|
||||||
user_query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани."
|
user_query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани."
|
||||||
result = await agent.ainvoke({"messages": [HumanMessage(content=user_query)]})
|
result = await agent.ainvoke(
|
||||||
# Печатаем все сообщения, включая вызовы инструментов
|
{"messages": [HumanMessage(content=user_query)]},
|
||||||
|
{"configurable": {"thread_id": "shopping-session"}},
|
||||||
|
)
|
||||||
|
# Вывод всех сообщений
|
||||||
for msg in result["messages"]:
|
for msg in result["messages"]:
|
||||||
if msg.content:
|
if msg.content:
|
||||||
print(msg.content)
|
print(msg.content)
|
||||||
|
|||||||
Reference in New Issue
Block a user