fix: main.py
This commit is contained in:
@@ -1,10 +1,10 @@
|
|||||||
import os
|
import os
|
||||||
import asyncio
|
import asyncio
|
||||||
from typing import TypedDict, Annotated
|
from typing import TypedDict, Annotated
|
||||||
|
from langgraph.graph import StateGraph, START, END
|
||||||
|
from langgraph.graph.message import add_messages
|
||||||
from langchain_openai import ChatOpenAI
|
from langchain_openai import ChatOpenAI
|
||||||
from langchain_core.messages import HumanMessage
|
from langchain_core.messages import HumanMessage, AIMessage
|
||||||
from langchain.tools import tool
|
|
||||||
from deepagents import create_deep_agent
|
from deepagents import create_deep_agent
|
||||||
from deepagents.backends import CompositeBackend, LocalShellBackend, FilesystemBackend
|
from deepagents.backends import CompositeBackend, LocalShellBackend, FilesystemBackend
|
||||||
|
|
||||||
@@ -16,12 +16,6 @@ llm = ChatOpenAI(
|
|||||||
temperature=0.0,
|
temperature=0.0,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------- Backend ----------
|
|
||||||
backend = CompositeBackend([
|
|
||||||
LocalShellBackend(workspace_dir="./workspace"),
|
|
||||||
FilesystemBackend(),
|
|
||||||
])
|
|
||||||
|
|
||||||
# ---------- State ----------
|
# ---------- State ----------
|
||||||
class ReflectState(TypedDict):
|
class ReflectState(TypedDict):
|
||||||
question: str
|
question: str
|
||||||
@@ -32,90 +26,75 @@ class ReflectState(TypedDict):
|
|||||||
max_rounds: int
|
max_rounds: int
|
||||||
|
|
||||||
# ---------- 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:
|
||||||
response = await llm.ainvoke([HumanMessage(content=DRAFT_PROMPT.format(question=state["question"]))])
|
prompt = f"Write a concise answer (5–10 sentences) to the following question: {state['question']}"
|
||||||
state["draft"] = response.content.strip()
|
response = await llm.ainvoke([HumanMessage(content=prompt)])
|
||||||
|
state['draft'] = response.content
|
||||||
return state
|
return state
|
||||||
|
|
||||||
async def reflect(state: ReflectState) -> ReflectState:
|
async def reflect(state: ReflectState) -> ReflectState:
|
||||||
response = await llm.ainvoke([HumanMessage(content=REFLECT_PROMPT.format(draft=state["draft"]))])
|
prompt = (
|
||||||
# Parse verdict and critique
|
f"You are a critic. Evaluate the following draft answer for completeness, specificity, and lack of filler.\n\nDraft: {state['draft']}\n\nProvide a verdict (ok or needs_revision) and 2–3 bullet points of critique."
|
||||||
text = response.content.strip()
|
)
|
||||||
verdict_line = next((l for l in text.splitlines() if l.lower().startswith("verdict:")), "")
|
response = await llm.ainvoke([HumanMessage(content=prompt)])
|
||||||
critique_lines = [l for l in text.splitlines() if l.startswith("-") or l.startswith("•")]
|
# Simple parsing: first line verdict, rest critique
|
||||||
verdict = verdict_line.split(":",1)[1].strip().lower() if verdict_line else "needs_revision"
|
lines = response.content.strip().splitlines()
|
||||||
critique = "\n".join(critique_lines) if critique_lines else ""
|
verdict_line = lines[0].lower()
|
||||||
state["verdict"] = verdict
|
verdict = "ok" if "ok" in verdict_line else "needs_revision"
|
||||||
state["critique"] = critique
|
critique = "\n".join(lines[1:]) if len(lines) > 1 else ""
|
||||||
|
state['verdict'] = verdict
|
||||||
|
state['critique'] = critique
|
||||||
return state
|
return state
|
||||||
|
|
||||||
async def rewrite(state: ReflectState) -> ReflectState:
|
async def rewrite(state: ReflectState) -> ReflectState:
|
||||||
response = await llm.ainvoke([HumanMessage(content=REWRITE_PROMPT.format(critique=state["critique"], draft=state["draft"]))])
|
prompt = (
|
||||||
state["draft"] = response.content.strip()
|
f"Rewrite the draft answer taking into account the following critique: {state['critique']}\n\nOriginal draft: {state['draft']}"
|
||||||
state["round"] += 1
|
)
|
||||||
|
response = await llm.ainvoke([HumanMessage(content=prompt)])
|
||||||
|
state['draft'] = response.content
|
||||||
|
state['round'] += 1
|
||||||
return state
|
return state
|
||||||
|
|
||||||
# ---------- Graph ----------
|
# ---------- Graph ----------
|
||||||
graph = StateGraph(ReflectState)
|
builder = StateGraph(ReflectState)
|
||||||
graph.add_node("draft_answer", draft_answer)
|
builder.add_node("draft_answer", draft_answer)
|
||||||
graph.add_node("reflect", reflect)
|
builder.add_node("reflect", reflect)
|
||||||
graph.add_node("rewrite", rewrite)
|
builder.add_node("rewrite", rewrite)
|
||||||
|
|
||||||
# Entry point
|
builder.set_entry_point("draft_answer")
|
||||||
graph.set_entry_point("draft_answer")
|
|
||||||
|
|
||||||
# Transitions
|
# Transition logic
|
||||||
# After draft -> reflect
|
def should_rewrite(state: ReflectState) -> str:
|
||||||
graph.add_edge("draft_answer", "reflect")
|
if state['verdict'] == "ok":
|
||||||
# After reflect
|
return "END"
|
||||||
# if ok -> END
|
if state['round'] >= state['max_rounds']:
|
||||||
# if needs_revision and round < max_rounds -> rewrite
|
|
||||||
# else -> END
|
|
||||||
|
|
||||||
def reflect_conditional(state: ReflectState):
|
|
||||||
if state["verdict"] == "ok":
|
|
||||||
return "END"
|
return "END"
|
||||||
if state["round"] < state["max_rounds"]:
|
|
||||||
return "rewrite"
|
return "rewrite"
|
||||||
return "END"
|
|
||||||
|
|
||||||
graph.add_conditional_edges("reflect", reflect_conditional, {"rewrite": "rewrite", "END": "END"})
|
builder.add_conditional_edges("reflect", should_rewrite, {
|
||||||
# After rewrite -> reflect
|
"rewrite": "rewrite",
|
||||||
graph.add_edge("rewrite", "reflect")
|
"END": "END",
|
||||||
|
})
|
||||||
|
|
||||||
graph.compile()
|
builder.add_edge("rewrite", "reflect")
|
||||||
|
|
||||||
|
graph = builder.compile()
|
||||||
|
|
||||||
# ---------- DeepAgent wrapper ----------
|
# ---------- DeepAgent wrapper ----------
|
||||||
@tool
|
backend = CompositeBackend([
|
||||||
def run_reflect_graph(question: str, max_rounds: int = 2) -> str:
|
LocalShellBackend(workspace_dir="./workspace"),
|
||||||
"""Run the reflection graph and return the final draft."""
|
FilesystemBackend(),
|
||||||
|
])
|
||||||
|
|
||||||
|
agent = create_deep_agent(
|
||||||
|
model=llm,
|
||||||
|
tools=[],
|
||||||
|
backend=backend,
|
||||||
|
system_prompt="You are a helper that runs a reflection graph.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---------- CLI ----------
|
||||||
|
async def run_graph(question: str, max_rounds: int = 2):
|
||||||
initial_state: ReflectState = {
|
initial_state: ReflectState = {
|
||||||
"question": question,
|
"question": question,
|
||||||
"draft": "",
|
"draft": "",
|
||||||
@@ -124,23 +103,18 @@ def run_reflect_graph(question: str, max_rounds: int = 2) -> str:
|
|||||||
"round": 0,
|
"round": 0,
|
||||||
"max_rounds": max_rounds,
|
"max_rounds": max_rounds,
|
||||||
}
|
}
|
||||||
result = graph.invoke(initial_state)
|
result = await graph.ainvoke(initial_state)
|
||||||
return result["draft"]
|
return result
|
||||||
|
|
||||||
agent = create_deep_agent(
|
|
||||||
model=llm,
|
|
||||||
tools=[run_reflect_graph],
|
|
||||||
backend=backend,
|
|
||||||
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(
|
result = await run_graph(question)
|
||||||
{"messages": [HumanMessage(content=f"Please answer: {question}")]},
|
print("\n--- Final Draft ---\n")
|
||||||
{"configurable": {"thread_id": "session-1"}},
|
print(result["draft"])
|
||||||
)
|
print("\n--- Critique ---\n")
|
||||||
print("Final answer:\n", response["messages"][-1].content)
|
print(result["critique"])
|
||||||
|
print("\n--- Verdict ---\n")
|
||||||
|
print(result["verdict"])
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|||||||
Reference in New Issue
Block a user