From d8c9f4ae33741556f0d3cae8fd42935afa58a6b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D0=B4=D0=B5=D0=BB=D0=B8=D0=BD=D0=B0=20=D0=A1=D0=B0?= =?UTF-8?q?=D1=82=D1=82=D0=B0=D1=80=D0=BE=D0=B2=D0=B0?= Date: Thu, 28 May 2026 10:12:08 +0000 Subject: [PATCH] add main.py --- main.py | 101 ++++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 72 insertions(+), 29 deletions(-) diff --git a/main.py b/main.py index 1b396dc..2e4941f 100644 --- a/main.py +++ b/main.py @@ -1,52 +1,95 @@ +""" +Simple hierarchical AI agent for shopping list using LangChain. + +The script demonstrates: +* Connection to a local LLM via OpenAI-compatible API. +* A tool that internally creates a sub‑agent to generate realistic prices. +* A top‑level agent that orchestrates the price queries and aggregates results. +""" + +from __future__ import annotations + +import json +from typing import Dict, Any + from langchain_openai import ChatOpenAI -from langchain.tools import tool, BaseTool +from langchain.tools import tool from langchain.agents import create_agent from pydantic import SecretStr -import json -# Connect to local LLM via OpenAI-compatible API +# --------------------------------------------------------------------------- +# 1. LLM configuration – adjust model name to your LM Studio instance. +# --------------------------------------------------------------------------- llm = ChatOpenAI( - model="gpt-4o-mini", # replace with your LM Studio model name + model="gpt-4o-mini", # replace with the actual model name in LM Studio 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 +# --------------------------------------------------------------------------- +# 2. Sub‑agent that generates a price table for a single product. +# --------------------------------------------------------------------------- @tool def get_price(product: str, city: str) -> str: - """Return a realistic price table for the given product and city.""" - # Create a sub‑agent with a simple prompt to generate a table + """Return a realistic price table for *product* in *city*. + + The function internally creates a small LangChain agent that asks the LLM to + produce a markdown table with columns Product | Price (руб.) | Store. + """ + # Create a tiny agent that only has the task of generating a price row. 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: Продукт, Цена (руб.), Магазин.", + system_prompt=( + f"You are an assistant that provides realistic prices for products in {city}. " + "Respond with a markdown table containing columns: Product, Price (руб.), Store." + ), ) - 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( + # Ask the sub‑agent to produce the price. + response = sub_agent.invoke( + { + "messages": [ + {"role": "human", "content": f"Provide a price for {product} in {city}."} + ] + } + ) + + # Extract the final message content. + messages = response.get("messages", []) + if not messages: + return f"| {product} | N/A | Unknown | +" + last_msg = messages[-1] + content = last_msg.get("content") or "" + # Ensure the table has a header row. + if "|" in content and "Product" not in content: + content = f"| Product | Price (руб.) | Store |\n{content}" + return content + +# --------------------------------------------------------------------------- +# 3. Main agent that orchestrates price queries for a shopping list. +# --------------------------------------------------------------------------- +shopping_agent = create_agent( model=llm, tools=[get_price], - system_prompt="Ты помощник по планированию покупок. Используй инструмент get_price для получения цены каждого продукта.", + system_prompt="You are an assistant that helps plan a shopping list and calculates total cost.", ) -# Example query -query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани." -result = main_agent.invoke({"messages": [{"role": "human", "content": query}]}) +def main() -> None: + user_query = ( + "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани." + ) + result = shopping_agent.invoke({"messages": [{"role": "human", "content": user_query}]}) -# Pretty‑print 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) + # Pretty‑print all messages. + for msg in result.get("messages", []): + if msg.get("content"): + print(msg["content"]) + elif msg.get("tool_calls"): + call = msg["tool_calls"][0] + print(f"{call['name']}({json.dumps(call['args'], ensure_ascii=False)})") -print("\n--- End of conversation ---") +if __name__ == "__main__": + main()