add main.py
This commit is contained in:
@@ -1,16 +1,22 @@
|
|||||||
|
"""
|
||||||
|
# main.py
|
||||||
|
# Implementation of the LangGraph reflective agent using deepagents
|
||||||
|
# Author: Auto-generated for the assignment
|
||||||
|
# Requires: deepagents, langchain-openai, langgraph, langchain
|
||||||
|
"""
|
||||||
import os
|
import os
|
||||||
import asyncio
|
import asyncio
|
||||||
from typing import TypedDict, Annotated
|
from typing import TypedDict, Annotated
|
||||||
|
|
||||||
from langchain_openai import ChatOpenAI
|
from langchain_openai import ChatOpenAI
|
||||||
from langchain_core.messages import HumanMessage
|
from langchain_core.messages import HumanMessage, SystemMessage
|
||||||
from langchain.tools import tool
|
from langchain.tools import tool
|
||||||
from deepagents import create_deep_agent
|
from deepagents import create_deep_agent
|
||||||
from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
|
from deepagents.backends import CompositeBackend, LocalShellBackend, FilesystemBackend
|
||||||
from langgraph.graph import StateGraph, START, END
|
from langgraph.graph import StateGraph, START, END
|
||||||
from langgraph.graph.message import add_messages
|
from langgraph.graph.message import add_messages
|
||||||
|
|
||||||
# ---------- LLM ----------
|
# ---------- LLM configuration (OpenRouter) ----------
|
||||||
llm = ChatOpenAI(
|
llm = ChatOpenAI(
|
||||||
model="openai/gpt-oss-20b:free",
|
model="openai/gpt-oss-20b:free",
|
||||||
base_url="https://openrouter.ai/api/v1",
|
base_url="https://openrouter.ai/api/v1",
|
||||||
@@ -18,59 +24,66 @@ llm = ChatOpenAI(
|
|||||||
temperature=0.0,
|
temperature=0.0,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------- Backend ----------
|
# ---------- State definition ----------
|
||||||
backend = CompositeBackend([
|
|
||||||
LocalShellBackend(workspace_dir="./workspace"),
|
|
||||||
FilesystemBackend(),
|
|
||||||
])
|
|
||||||
|
|
||||||
# ---------- State ----------
|
|
||||||
class ReflectState(TypedDict):
|
class ReflectState(TypedDict):
|
||||||
question: str
|
question: str
|
||||||
draft: str
|
draft: str
|
||||||
critique: str
|
critique: str
|
||||||
verdict: str # ok | needs_revision
|
verdict: str # "ok" | "needs_revision"
|
||||||
round: int
|
round: int
|
||||||
max_rounds: int
|
max_rounds: int
|
||||||
|
|
||||||
# ---------- Nodes ----------
|
# ---------- Node implementations ----------
|
||||||
async def draft_answer(state: ReflectState) -> ReflectState:
|
async def draft_answer(state: ReflectState) -> ReflectState:
|
||||||
prompt = f"Write a concise answer (5–10 sentences) to the following question: {state['question']}"
|
"""Generate an initial draft answer (5–10 sentences)."""
|
||||||
response = await llm.ainvoke([HumanMessage(content=prompt)])
|
prompt = (
|
||||||
|
"You are an expert tutor. Answer the following question in 5–10 concise sentences. "
|
||||||
|
"Avoid filler and keep it clear.
|
||||||
|
"
|
||||||
|
f"Question: {state['question']}"
|
||||||
|
)
|
||||||
|
response = await llm.ainvoke([SystemMessage(content="You are a helpful tutor."), HumanMessage(content=prompt)])
|
||||||
state["draft"] = response.content.strip()
|
state["draft"] = response.content.strip()
|
||||||
state["round"] = 0
|
state["round"] = 1
|
||||||
state["max_rounds"] = state.get("max_rounds", 2)
|
|
||||||
return state
|
return state
|
||||||
|
|
||||||
async def reflect(state: ReflectState) -> ReflectState:
|
async def reflect(state: ReflectState) -> ReflectState:
|
||||||
|
"""Critique the draft and decide if revision is needed."""
|
||||||
prompt = (
|
prompt = (
|
||||||
"You are a critic. Evaluate the following draft answer for completeness, specificity, and lack of filler.\n"
|
"You are a critical reviewer. Evaluate the following answer for completeness, specificity, and lack of filler. "
|
||||||
f"Draft: {state['draft']}\n"
|
"Respond with a verdict of either "ok" or "needs_revision", followed by 2–3 bullet points of constructive feedback.
|
||||||
"Return a JSON object with fields: verdict (ok or needs_revision) and critique (2–3 bullet points)."
|
"
|
||||||
|
f"Answer draft:\n{state['draft']}"
|
||||||
)
|
)
|
||||||
response = await llm.ainvoke([HumanMessage(content=prompt)])
|
response = await llm.ainvoke([SystemMessage(content="You are a critical reviewer."), HumanMessage(content=prompt)])
|
||||||
# Simple extraction of JSON
|
text = response.content.strip()
|
||||||
import json, re
|
# Parse verdict and critique
|
||||||
try:
|
if "needs_revision" in text.lower():
|
||||||
data = json.loads(re.search(r"\{.*\}", response.content, re.S).group(0))
|
verdict = "needs_revision"
|
||||||
except Exception:
|
else:
|
||||||
data = {"verdict": "needs_revision", "critique": "Could not parse critique."}
|
verdict = "ok"
|
||||||
state["critique"] = data.get("critique", "")
|
# Extract critique lines after the verdict
|
||||||
state["verdict"] = data.get("verdict", "needs_revision")
|
lines = text.splitlines()
|
||||||
|
critique_lines = [line for line in lines if line.strip() and line.strip().lower() not in {"ok", "needs_revision"}]
|
||||||
|
critique = "\n".join(critique_lines).strip()
|
||||||
|
state["critique"] = critique
|
||||||
|
state["verdict"] = verdict
|
||||||
return state
|
return state
|
||||||
|
|
||||||
async def rewrite(state: ReflectState) -> ReflectState:
|
async def rewrite(state: ReflectState) -> ReflectState:
|
||||||
|
"""Rewrite the draft incorporating the critique."""
|
||||||
prompt = (
|
prompt = (
|
||||||
"Rewrite the draft answer incorporating the following critique. Keep the answer concise (5–10 sentences).\n"
|
"You are revising an answer based on the following critique. Produce a new version that addresses the points and remains 5–10 sentences.
|
||||||
f"Critique: {state['critique']}\n"
|
"
|
||||||
f"Original draft: {state['draft']}"
|
f"Original draft:\n{state['draft']}\n\nCritique:\n{state['critique']}"
|
||||||
)
|
)
|
||||||
response = await llm.ainvoke([HumanMessage(content=prompt)])
|
response = await llm.ainvoke([SystemMessage(content="You are a revising tutor."), HumanMessage(content=prompt)])
|
||||||
state["draft"] = response.content.strip()
|
state["draft"] = response.content.strip()
|
||||||
state["round"] += 1
|
state["round"] += 1
|
||||||
return state
|
return state
|
||||||
|
|
||||||
# ---------- Graph ----------
|
# ---------- Graph construction ----------
|
||||||
|
def build_graph() -> StateGraph[ReflectState]:
|
||||||
graph = StateGraph(ReflectState)
|
graph = StateGraph(ReflectState)
|
||||||
graph.add_node("draft_answer", draft_answer)
|
graph.add_node("draft_answer", draft_answer)
|
||||||
graph.add_node("reflect", reflect)
|
graph.add_node("reflect", reflect)
|
||||||
@@ -80,46 +93,61 @@ graph.add_node("rewrite", rewrite)
|
|||||||
graph.set_entry_point("draft_answer")
|
graph.set_entry_point("draft_answer")
|
||||||
|
|
||||||
# Transitions
|
# Transitions
|
||||||
graph.add_edge("draft_answer", "reflect")
|
graph.add_conditional_edges(
|
||||||
# If ok -> END
|
"draft_answer",
|
||||||
|
lambda _: "reflect",
|
||||||
|
)
|
||||||
graph.add_conditional_edges(
|
graph.add_conditional_edges(
|
||||||
"reflect",
|
"reflect",
|
||||||
lambda state: "rewrite" if state["verdict"] == "needs_revision" and state["round"] < state["max_rounds"] else "END",
|
lambda state: "END" if state["verdict"] == "ok" else "rewrite",
|
||||||
|
)
|
||||||
|
graph.add_conditional_edges(
|
||||||
|
"rewrite",
|
||||||
|
lambda state: "END" if state["round"] > state["max_rounds"] else "reflect",
|
||||||
)
|
)
|
||||||
# rewrite -> reflect
|
|
||||||
graph.add_edge("rewrite", "reflect")
|
|
||||||
|
|
||||||
app = graph.compile()
|
return graph
|
||||||
|
|
||||||
# ---------- DeepAgent wrapper ----------
|
# ---------- Tool that runs the graph ----------
|
||||||
@tool
|
@tool
|
||||||
def run_graph(question: str) -> str:
|
async def answer_question(query: str) -> str:
|
||||||
"""Run the reflection graph for a given question."""
|
"""Run the reflective LangGraph to answer a question."""
|
||||||
|
graph = build_graph()
|
||||||
|
# Initialize state
|
||||||
state: ReflectState = {
|
state: ReflectState = {
|
||||||
"question": question,
|
"question": query,
|
||||||
"draft": "",
|
"draft": "",
|
||||||
"critique": "",
|
"critique": "",
|
||||||
"verdict": "",
|
"verdict": "",
|
||||||
"round": 0,
|
"round": 0,
|
||||||
"max_rounds": 2,
|
"max_rounds": 2,
|
||||||
}
|
}
|
||||||
result = app.invoke(state)
|
# Run graph
|
||||||
return result["draft"]
|
final_state = await graph.ainvoke(state)
|
||||||
|
return final_state["draft"]
|
||||||
|
|
||||||
|
# ---------- DeepAgent setup ----------
|
||||||
|
backend = CompositeBackend([
|
||||||
|
LocalShellBackend(workspace_dir="./workspace"),
|
||||||
|
FilesystemBackend(),
|
||||||
|
])
|
||||||
|
|
||||||
agent = create_deep_agent(
|
agent = create_deep_agent(
|
||||||
model=llm,
|
model=llm,
|
||||||
tools=[run_graph],
|
tools=[answer_question],
|
||||||
backend=backend,
|
backend=backend,
|
||||||
system_prompt="You are a helpful agent that can answer questions and self‑critique using the provided tool.",
|
system_prompt="You are a helpful educational agent. Use the provided tools to answer questions.",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# ---------- CLI entry point ----------
|
||||||
async def main():
|
async def main():
|
||||||
question = "Объясни студенту разницу между tool и resource в MCP"
|
question = "Объясни студенту разницу между tool и resource в MCP"
|
||||||
result = await agent.ainvoke(
|
result = await agent.ainvoke(
|
||||||
{"messages": [HumanMessage(content=question)]},
|
{"messages": [HumanMessage(content=question)]},
|
||||||
{"configurable": {"thread_id": "session-1"}},
|
{"configurable": {"thread_id": "session-1"}},
|
||||||
)
|
)
|
||||||
print("Final answer:\n", result["messages"][-1].content)
|
# The tool returns the final answer as the last message content
|
||||||
|
print("\nFinal answer:\n", result["messages"][-1].content)
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|||||||
Reference in New Issue
Block a user