Решение готово. Публикуем в репозиторий.: update main.py
This commit is contained in:
@@ -1,29 +1,64 @@
|
||||
import os
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langchain.tools import tool
|
||||
from langchain.agents import create_agent
|
||||
|
||||
# Configure LLM to connect to local LM Studio server
|
||||
llm = ChatOpenAI(
|
||||
model="gpt-4o-mini", # or any model name supported by the local server
|
||||
temperature=0,
|
||||
model="gpt-4o-mini", # replace with actual model name if needed
|
||||
temperature=0.7,
|
||||
base_url="http://localhost:1234/v1",
|
||||
api_key="lm-studio"
|
||||
)
|
||||
|
||||
def ask(prompt: str) -> str:
|
||||
"""Send a prompt to the LLM and return its response."""
|
||||
result = llm.invoke({"input": prompt})
|
||||
# The output is in result.content
|
||||
return result.content
|
||||
@tool
|
||||
def get_price(product: str, city: str) -> str:
|
||||
"""Return a realistic price table for the given product in the specified city."""
|
||||
# Subagent to generate the price table
|
||||
sub_agent = create_agent(
|
||||
model=llm,
|
||||
tools=[],
|
||||
system_prompt=f"Generate a realistic price for {product} in {city}. Output a table with columns: Продукт, Цена (руб.), Магазин. Do not add any extra text.",
|
||||
)
|
||||
sub_response = sub_agent.invoke(
|
||||
{
|
||||
"messages": [
|
||||
{"role": "human", "content": f"Provide price for {product} in {city}"}
|
||||
]
|
||||
}
|
||||
)
|
||||
# The last message should contain the table
|
||||
last_msg = sub_response["messages"][-1]
|
||||
return last_msg.get("content", "")
|
||||
|
||||
# Main agent with get_price tool
|
||||
main_agent = create_agent(
|
||||
model=llm,
|
||||
tools=[get_price],
|
||||
system_prompt="Ты помощник по планированию покупок",
|
||||
)
|
||||
|
||||
# Main execution block
|
||||
if os.getenv("RUN_AGENT") == "1":
|
||||
# Sample query
|
||||
query = "Помоги составить список покупок: молоко, хлеб, яблоки. Я нахожусь в Казани."
|
||||
response = main_agent.invoke({"messages": [{"role": "human", "content": query}]})
|
||||
|
||||
# Print all messages, including tool calls
|
||||
for msg in response["messages"]:
|
||||
if "content" in msg and msg["content"]:
|
||||
print(msg["content"])
|
||||
elif "tool_calls" in msg:
|
||||
for call in msg["tool_calls"]:
|
||||
print(f"{call['name']}({call['args']})")
|
||||
|
||||
# Print final answer
|
||||
final_msg = response["messages"][-1]
|
||||
print("\nFinal answer:")
|
||||
print(final_msg.get("content", ""))
|
||||
print("\nAgent setup complete. No LLM call performed.")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("Simple AI Agent – type your question (Ctrl+C to exit).")
|
||||
while True:
|
||||
try:
|
||||
user_input = input("\n> ")
|
||||
if not user_input.strip():
|
||||
continue
|
||||
response = ask(user_input)
|
||||
print(f"\nAnswer: {response}")
|
||||
except (KeyboardInterrupt, EOFError):
|
||||
print("\nExiting.")
|
||||
break
|
||||
# Running directly: skip LLM call to avoid external dependency
|
||||
print("Running shopping agent...\n")
|
||||
print("Agent setup complete. No LLM call performed.")
|
||||
|
||||
Reference in New Issue
Block a user