79 lines
2.6 KiB
Python
79 lines
2.6 KiB
Python
import os
|
|
from langchain_openai import ChatOpenAI
|
|
from langchain.tools import tool
|
|
from langgraph.checkpoint.memory import MemorySaver
|
|
from langgraph import create_agent
|
|
from langchain_core.messages import HumanMessage
|
|
from rich.console import Console
|
|
|
|
# LLM setup
|
|
llm = ChatOpenAI(
|
|
model="openai/gpt-oss-20b:free",
|
|
base_url="https://openrouter.ai/api/v1",
|
|
api_key=os.getenv("OPENAI_API_KEY"),
|
|
temperature=0.0,
|
|
)
|
|
|
|
# Console for rich output
|
|
console = Console()
|
|
|
|
# Dummy tool example: get_price (weather placeholder)
|
|
@tool
|
|
def get_price(*, city: str, date: str) -> str:
|
|
"""Return a mock weather price for a city and date."""
|
|
return f"Weather in {city} on {date}: sunny 25°C"
|
|
|
|
# Memory and agent setup
|
|
memory = MemorySaver()
|
|
|
|
agent = create_agent(
|
|
llm=llm,
|
|
tools=[get_price],
|
|
system_prompt="You are a helpful assistant that can call tools.",
|
|
checkpointer=memory,
|
|
interrupt_before=["tools"],
|
|
)
|
|
|
|
# Configuration for a single conversation thread
|
|
config = {"configurable": {"thread_id": "conversation-1"}}
|
|
|
|
# Helper to display tool calls nicely
|
|
def display_tool_call(tool_call):
|
|
name = tool_call["name"]
|
|
args = tool_call["args"]
|
|
console.print(f"\n{name}({args})")
|
|
console.print("Агент хочет вызвать утилиту", f"{name}({args})")
|
|
|
|
# Main interaction loop
|
|
def ask_and_run(user_input, config):
|
|
for chunk in agent.stream(user_input, config=config, stream_mode=["messages", "updates"]):
|
|
state = agent.get_state(config)
|
|
chunk_type, chunk_data = chunk
|
|
if chunk_type == "messages":
|
|
# stream token output
|
|
console.print(chunk_data, end="")
|
|
if chunk_type == "updates":
|
|
# tool calls
|
|
for update in chunk_data:
|
|
if update.get("type") == "tool_call":
|
|
tool_call = update["tool_call"]
|
|
display_tool_call(tool_call)
|
|
if "__interrupt__" in chunk_data and state.next == ("tools",):
|
|
# pause before tool
|
|
answer = console.input("\nРазрешить? (Y/n): ")
|
|
if answer.lower().strip() in ("", "y", "yes"):
|
|
# resume
|
|
ask_and_run(None, config)
|
|
else:
|
|
console.print("Отменено")
|
|
break
|
|
|
|
if __name__ == "__main__":
|
|
console.print("Добро пожаловать! Введите 'exit' для выхода.")
|
|
while True:
|
|
user_input = console.input("\nВы: ")
|
|
if user_input.lower() == "exit":
|
|
break
|
|
ask_and_run({"messages": [{"role": "human", "content": user_input}]}, config)
|
|
console.print("\n--- --- ---")
|