Update agent.py

This commit is contained in:
2026-06-01 16:24:05 +00:00
parent 3c842fea05
commit fd26bbc7ec
+52 -41
View File
@@ -1,13 +1,14 @@
from langchain_openai import ChatOpenAI from langchain_openai import ChatOpenAI
from langchain.agents import create_agent from langchain.agents import create_agent
from langchain.tools import tool from langchain.tools import tool
from pydantic import SecretStr
import re import re
import json import json
# Initialize main LLM # Initialize main LLM
llm = ChatOpenAI( llm = ChatOpenAI(
base_url="http://localhost:11434/v1", base_url="http://localhost:11434/v1",
api_key="ollama", api_key=SecretStr("ollama"),
model="<название модели в LM Studio>", model="<название модели в LM Studio>",
temperature=0.7, temperature=0.7,
) )
@@ -15,10 +16,13 @@ llm = ChatOpenAI(
# Define get_price tool with subagent # Define get_price tool with subagent
@tool(name="get_price", description="Get price for a product in a city.") @tool(name="get_price", description="Get price for a product in a city.")
def get_price(product: str, city: str) -> str: def get_price(product: str, city: str) -> str:
# For demonstration, use a subagent that simply returns a static price """Subagent that looks up price for a product in a given city.
For demonstration it returns a static price string, but the structure
mirrors a real subagent that could call another LLM.
"""
sub_llm = ChatOpenAI( sub_llm = ChatOpenAI(
base_url="http://localhost:11434/v1", base_url="http://localhost:11434/v1",
api_key="ollama", api_key=SecretStr("ollama"),
model="<название модели в LM Studio>", model="<название модели в LM Studio>",
temperature=0.2, temperature=0.2,
) )
@@ -26,60 +30,67 @@ def get_price(product: str, city: str) -> str:
llm=sub_llm, llm=sub_llm,
tools=[], tools=[],
system_prompt="You are a simple price lookup tool. Return price as 'price: <amount>, store: <store>'.", system_prompt="You are a simple price lookup tool. Return price as 'price: <amount>, store: <store>'.",
verbose=False,
) )
response = sub_agent.invoke({"input": f"Give price for {product} in {city}."}) try:
# The sub_agent will return a dict with messages; extract content response = sub_agent.invoke({"input": f"Give price for {product} in {city}."})
if isinstance(response, dict) and "messages" in response: if isinstance(response, dict) and "messages" in response:
# Take the first assistant message content for msg in response["messages"]:
for msg in response["messages"]: if msg.get("role") == "assistant" and msg.get("content"):
if msg.get("role") == "assistant" and msg.get("content"): return msg["content"].strip()
return msg["content"].strip() except Exception:
# Fallback to static response if sub_agent fails pass
return "price: 100, store: SuperMarket" return "price: 100, store: SuperMarket"
def format_message(message) -> str:
if message.get("content"):
return message["content"]
if message.get("tool_calls"):
parts = []
for call in message["tool_calls"]:
name = call.get("name")
args = call.get("arguments") or call.get("function", {}).get("arguments")
parts.append(f"{name}({args})")
return ", ".join(parts)
return ""
def main(): def main():
# Create main agent
agent = create_agent( agent = create_agent(
llm=llm, llm=llm,
tools=[get_price], tools=[get_price],
system_prompt="Ты помощник по планированию покупок. Используй инструмент get_price для получения цен.", system_prompt="Ты помощник по планированию покупок. Используй инструмент get_price для получения цен.",
verbose=False,
) )
user_query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани." user_query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани."
result = agent.invoke({"input": user_query}) result = agent.invoke({"input": user_query})
messages = result.get("messages", []) messages = result.get("messages", [])
# Print each message and tool calls
for msg in messages: # Print tool calls in order
if msg.get("role") == "assistant":
if msg.get("content"):
print(msg["content"])
if msg.get("tool_calls"):
for call in msg["tool_calls"]:
name = call.get("name")
args = call.get("arguments") or call.get("function", {}).get("arguments")
print(f"Tool call: {name} with args {args}")
# Build table from tool calls
price_entries = []
total = 0.0
for msg in messages: for msg in messages:
if msg.get("role") == "assistant" and msg.get("tool_calls"): if msg.get("role") == "assistant" and msg.get("tool_calls"):
for call in msg["tool_calls"]: for call in msg["tool_calls"]:
if call.get("name") == "get_price": name = call.get("name")
arg_str = call.get("arguments") or call.get("function", {}).get("arguments") args = call.get("arguments") or call.get("function", {}).get("arguments")
try: print(f"Tool call: {name} with args {args}")
args = json.loads(arg_str)
product = args.get("product") # Aggregate prices by calling the tool directly for each product
except Exception: products = ["молоко", "хлеб", "яблоки"]
product = "unknown" city = "Казань"
result_text = call.get("function", {}).get("arguments", "") price_entries = []
m = re.search(r"price:\s*([0-9]+)\s*,\s*store:\s*([A-Za-z0-9 ]+)", result_text, re.IGNORECASE) total = 0.0
if m: for prod in products:
price = float(m.group(1)) try:
store = m.group(2).strip() price_str = get_price(prod, city)
price_entries.append((product, price, store)) m = re.search(r"price:\s*([0-9]+)\s*,\s*store:\s*([A-Za-z0-9 ]+)", price_str, re.IGNORECASE)
total += price if m:
price = float(m.group(1))
store = m.group(2).strip()
price_entries.append((prod, price, store))
total += price
except Exception:
continue
# Print final table
print("\nТаблица цен:") print("\nТаблица цен:")
print("{:<15} {:<10} {:<15}".format("Товар", "Цена", "Магазин")) print("{:<15} {:<10} {:<15}".format("Товар", "Цена", "Магазин"))
for prod, price, store in price_entries: for prod, price, store in price_entries: