Files
task-6997111cd6d3a5544a3deffd/main.py
T
2026-05-28 10:11:23 +00:00

53 lines
2.1 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.
from langchain_openai import ChatOpenAI
from langchain.tools import tool, BaseTool
from langchain.agents import create_agent
from pydantic import SecretStr
import json
# Connect to local LLM via OpenAI-compatible API
llm = ChatOpenAI(
model="gpt-4o-mini", # replace with your LM Studio model name
base_url="http://localhost:1234/v1",
api_key=SecretStr("fake"),
temperature=0.7,
)
# Sub-agent that generates a price table for a product in a city
@tool
def get_price(product: str, city: str) -> str:
"""Return a realistic price table for the given product and city."""
# Create a subagent with a simple prompt to generate a table
sub_agent = create_agent(
model=llm,
tools=[],
system_prompt=f"You are a market analyst. Provide a realistic price for {product} in {city}. Return the result as a markdown table with columns: Продукт, Цена (руб.), Магазин.",
)
response = sub_agent.invoke({"messages": [{"role": "human", "content": f"Generate price for {product} in {city}"}]})
# The agent returns a dict with messages; the last message contains the table
return response["messages"][-1]["content"]
# Main agent that uses get_price to build shopping list
main_agent = create_agent(
model=llm,
tools=[get_price],
system_prompt="Ты помощник по планированию покупок. Используй инструмент get_price для получения цены каждого продукта.",
)
# Example query
query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани."
result = main_agent.invoke({"messages": [{"role": "human", "content": query}]})
# Prettyprint all messages
for msg in result["messages"]:
if "content" in msg and msg["content"]:
print(msg["content"])
elif "tool_calls" in msg and msg["tool_calls"]:
for call in msg["tool_calls"]:
name = call["name"]
args = json.dumps(call["args"], ensure_ascii=False)
print(f"{name}({args})")
else:
print(msg)
print("\n--- End of conversation ---")