fix: main.py
This commit is contained in:
@@ -6,9 +6,7 @@ from langchain_openai import ChatOpenAI
|
|||||||
from langchain_core.messages import HumanMessage
|
from langchain_core.messages import HumanMessage
|
||||||
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.message import add_messages
|
|
||||||
|
|
||||||
# ---------- LLM ----------
|
# ---------- LLM ----------
|
||||||
llm = ChatOpenAI(
|
llm = ChatOpenAI(
|
||||||
@@ -18,13 +16,13 @@ llm = ChatOpenAI(
|
|||||||
temperature=0.0,
|
temperature=0.0,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------- Backend for deepagents ----------
|
# ---------- Backend ----------
|
||||||
backend = CompositeBackend([
|
backend = CompositeBackend([
|
||||||
LocalShellBackend(workspace_dir="./workspace"),
|
LocalShellBackend(workspace_dir="./workspace"),
|
||||||
FilesystemBackend(),
|
FilesystemBackend(),
|
||||||
])
|
])
|
||||||
|
|
||||||
# ---------- State definition ----------
|
# ---------- State ----------
|
||||||
class ReflectState(TypedDict):
|
class ReflectState(TypedDict):
|
||||||
question: str
|
question: str
|
||||||
draft: str
|
draft: str
|
||||||
@@ -33,40 +31,58 @@ class ReflectState(TypedDict):
|
|||||||
round: int
|
round: int
|
||||||
max_rounds: int
|
max_rounds: int
|
||||||
|
|
||||||
# ---------- LangGraph nodes ----------
|
# ---------- Nodes ----------
|
||||||
|
from langgraph.graph import StateGraph, START, END
|
||||||
|
from langgraph.graph.message import add_messages
|
||||||
|
|
||||||
|
# Helper to format the prompt for each node
|
||||||
|
DRAFT_PROMPT = """Write a concise answer (5–10 sentences) to the following question:
|
||||||
|
|
||||||
|
{question}
|
||||||
|
"""
|
||||||
|
|
||||||
|
REFLECT_PROMPT = """You are a critic. Given the draft answer below, evaluate its completeness, specificity, and absence of filler. Respond with:
|
||||||
|
1. verdict: either "ok" or "needs_revision"
|
||||||
|
2. critique: 2–3 bullet points explaining what to improve (if any)
|
||||||
|
|
||||||
|
Draft:
|
||||||
|
{draft}
|
||||||
|
"""
|
||||||
|
|
||||||
|
REWRITE_PROMPT = """You are revising the draft answer based on the critique. Produce a new draft that addresses the points. Keep the answer concise (5–10 sentences).
|
||||||
|
|
||||||
|
Critique:
|
||||||
|
{critique}
|
||||||
|
|
||||||
|
Previous draft:
|
||||||
|
{draft}
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Node functions
|
||||||
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:\n\n{state['question']}"
|
response = await llm.ainvoke([HumanMessage(content=DRAFT_PROMPT.format(question=state["question"]))])
|
||||||
response = await llm.ainvoke([HumanMessage(content=prompt)])
|
|
||||||
state["draft"] = response.content.strip()
|
state["draft"] = response.content.strip()
|
||||||
return state
|
return state
|
||||||
|
|
||||||
async def reflect(state: ReflectState) -> ReflectState:
|
async def reflect(state: ReflectState) -> ReflectState:
|
||||||
prompt = (
|
response = await llm.ainvoke([HumanMessage(content=REFLECT_PROMPT.format(draft=state["draft"]))])
|
||||||
"You are a critic. Evaluate the draft answer for completeness, specificity, and lack of filler.\n"
|
# Parse verdict and critique
|
||||||
"Return a verdict ('ok' or 'needs_revision') and 2–3 bullet points of critique.\n"
|
text = response.content.strip()
|
||||||
f"Draft: {state['draft']}"
|
verdict_line = next((l for l in text.splitlines() if l.lower().startswith("verdict:")), "")
|
||||||
)
|
critique_lines = [l for l in text.splitlines() if l.startswith("-") or l.startswith("•")]
|
||||||
response = await llm.ainvoke([HumanMessage(content=prompt)])
|
verdict = verdict_line.split(":",1)[1].strip().lower() if verdict_line else "needs_revision"
|
||||||
# Simple parsing: first line verdict, rest critique
|
critique = "\n".join(critique_lines) if critique_lines else ""
|
||||||
lines = response.content.strip().splitlines()
|
|
||||||
verdict = lines[0].strip().lower()
|
|
||||||
critique = "\n".join(lines[1:]).strip()
|
|
||||||
state["verdict"] = verdict
|
state["verdict"] = verdict
|
||||||
state["critique"] = critique
|
state["critique"] = critique
|
||||||
return state
|
return state
|
||||||
|
|
||||||
async def rewrite(state: ReflectState) -> ReflectState:
|
async def rewrite(state: ReflectState) -> ReflectState:
|
||||||
prompt = (
|
response = await llm.ainvoke([HumanMessage(content=REWRITE_PROMPT.format(critique=state["critique"], draft=state["draft"]))])
|
||||||
"Rewrite the draft answer incorporating the following critique. Keep the answer concise (5–10 sentences).\n"
|
|
||||||
f"Critique: {state['critique']}\n"
|
|
||||||
f"Original draft: {state['draft']}"
|
|
||||||
)
|
|
||||||
response = await llm.ainvoke([HumanMessage(content=prompt)])
|
|
||||||
state["draft"] = response.content.strip()
|
state["draft"] = response.content.strip()
|
||||||
state["round"] += 1
|
state["round"] += 1
|
||||||
return state
|
return state
|
||||||
|
|
||||||
# ---------- Graph construction ----------
|
# ---------- Graph ----------
|
||||||
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)
|
||||||
@@ -76,24 +92,30 @@ graph.add_node("rewrite", rewrite)
|
|||||||
graph.set_entry_point("draft_answer")
|
graph.set_entry_point("draft_answer")
|
||||||
|
|
||||||
# Transitions
|
# Transitions
|
||||||
|
# After draft -> reflect
|
||||||
graph.add_edge("draft_answer", "reflect")
|
graph.add_edge("draft_answer", "reflect")
|
||||||
# From reflect: if ok -> END, else if needs_revision and round < max_rounds -> rewrite
|
# After reflect
|
||||||
graph.add_conditional_edges(
|
# if ok -> END
|
||||||
"reflect",
|
# if needs_revision and round < max_rounds -> rewrite
|
||||||
lambda state: (
|
# else -> END
|
||||||
"END" if state["verdict"] == "ok" else (
|
|
||||||
"rewrite" if state["round"] < state["max_rounds"] else "END"
|
def reflect_conditional(state: ReflectState):
|
||||||
)
|
if state["verdict"] == "ok":
|
||||||
),
|
return "END"
|
||||||
)
|
if state["round"] < state["max_rounds"]:
|
||||||
|
return "rewrite"
|
||||||
|
return "END"
|
||||||
|
|
||||||
|
graph.add_conditional_edges("reflect", reflect_conditional, {"rewrite": "rewrite", "END": "END"})
|
||||||
|
# After rewrite -> reflect
|
||||||
graph.add_edge("rewrite", "reflect")
|
graph.add_edge("rewrite", "reflect")
|
||||||
|
|
||||||
app = graph.compile()
|
graph.compile()
|
||||||
|
|
||||||
# ---------- DeepAgent wrapper ----------
|
# ---------- DeepAgent wrapper ----------
|
||||||
@tool
|
@tool
|
||||||
def run_graph(question: str, max_rounds: int = 2) -> str:
|
def run_reflect_graph(question: str, max_rounds: int = 2) -> str:
|
||||||
"""Run the reflection graph for a given question."""
|
"""Run the reflection graph and return the final draft."""
|
||||||
initial_state: ReflectState = {
|
initial_state: ReflectState = {
|
||||||
"question": question,
|
"question": question,
|
||||||
"draft": "",
|
"draft": "",
|
||||||
@@ -102,20 +124,20 @@ def run_graph(question: str, max_rounds: int = 2) -> str:
|
|||||||
"round": 0,
|
"round": 0,
|
||||||
"max_rounds": max_rounds,
|
"max_rounds": max_rounds,
|
||||||
}
|
}
|
||||||
result = app.invoke(initial_state)
|
result = graph.invoke(initial_state)
|
||||||
return result["draft"]
|
return result["draft"]
|
||||||
|
|
||||||
agent = create_deep_agent(
|
agent = create_deep_agent(
|
||||||
model=llm,
|
model=llm,
|
||||||
tools=[run_graph],
|
tools=[run_reflect_graph],
|
||||||
backend=backend,
|
backend=backend,
|
||||||
system_prompt="You are an assistant that can generate and improve answers using reflection. Use the provided tool to get a refined answer.",
|
system_prompt="You are an assistant that can answer questions and self‑critique using the provided tool.",
|
||||||
)
|
)
|
||||||
|
|
||||||
async def main():
|
async def main():
|
||||||
question = "Объясни студенту разницу между tool и resource в MCP"
|
question = "Объясни студенту разницу между tool и resource в MCP."
|
||||||
response = await agent.ainvoke(
|
response = await agent.ainvoke(
|
||||||
{"messages": [HumanMessage(content=question)]},
|
{"messages": [HumanMessage(content=f"Please answer: {question}")]},
|
||||||
{"configurable": {"thread_id": "session-1"}},
|
{"configurable": {"thread_id": "session-1"}},
|
||||||
)
|
)
|
||||||
print("Final answer:\n", response["messages"][-1].content)
|
print("Final answer:\n", response["messages"][-1].content)
|
||||||
|
|||||||
Reference in New Issue
Block a user