Add main.py
This commit is contained in:
@@ -1,16 +1,13 @@
|
|||||||
import os
|
import os
|
||||||
|
import re
|
||||||
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.tools import tool
|
|
||||||
from deepagents import create_deep_agent
|
|
||||||
from deepagents.backends import FilesystemBackend, LocalShellBackend, CompositeBackend
|
|
||||||
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,91 +15,78 @@ llm = ChatOpenAI(
|
|||||||
temperature=0.0,
|
temperature=0.0,
|
||||||
)
|
)
|
||||||
|
|
||||||
# ---------- Backend for deepagents (not used directly in graph but required by create_deep_agent) ----------
|
|
||||||
backend = CompositeBackend([
|
|
||||||
LocalShellBackend(workspace_dir="./workspace"),
|
|
||||||
FilesystemBackend(),
|
|
||||||
])
|
|
||||||
|
|
||||||
# ---------- State definition ----------
|
# ---------- State definition ----------
|
||||||
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) -> dict:
|
||||||
prompt = f"Write a concise answer (5–10 sentences) to the following question:\n\n{state['question']}"
|
|
||||||
response = await llm.ainvoke([HumanMessage(content=prompt)])
|
|
||||||
state["draft"] = response.content.strip()
|
|
||||||
return state
|
|
||||||
|
|
||||||
async def reflect(state: ReflectState) -> ReflectState:
|
|
||||||
prompt = (
|
prompt = (
|
||||||
f"You are a critic. Evaluate the following draft answer for completeness, specificity, and lack of filler.\n\nDraft:\n{state['draft']}\n\nProvide a verdict (ok or needs_revision) and 2–3 bullet points of critique."
|
f"Write a concise answer (5–10 sentences) to the following question:\n\n"
|
||||||
|
f"Question: {state['question']}"
|
||||||
)
|
)
|
||||||
response = await llm.ainvoke([HumanMessage(content=prompt)])
|
response = await llm.ainvoke([{"role": "user", "content": prompt}])
|
||||||
|
draft = response.content.strip()
|
||||||
|
return {"draft": draft, "round": 0}
|
||||||
|
|
||||||
|
async def reflect(state: ReflectState) -> dict:
|
||||||
|
prompt = (
|
||||||
|
f"You are a critical reviewer. Evaluate the following draft answer for completeness, specificity, and lack of filler.\n\n"
|
||||||
|
f"Draft: {state['draft']}\n\n"
|
||||||
|
f"Provide a verdict (ok or needs_revision) and 2–3 bullet points of critique."
|
||||||
|
)
|
||||||
|
response = await llm.ainvoke([{"role": "user", "content": prompt}])
|
||||||
text = response.content.strip()
|
text = response.content.strip()
|
||||||
# Simple parsing: first line verdict, rest critique
|
verdict_match = re.search(r"(ok|needs_revision)", text, re.IGNORECASE)
|
||||||
lines = text.splitlines()
|
verdict = verdict_match.group(1).lower() if verdict_match else "needs_revision"
|
||||||
verdict_line = lines[0].lower()
|
return {"critique": text, "verdict": verdict}
|
||||||
verdict = "ok" if "ok" in verdict_line else "needs_revision"
|
|
||||||
critique = "\n".join(lines[1:]).strip()
|
|
||||||
state["verdict"] = verdict
|
|
||||||
state["critique"] = critique
|
|
||||||
return state
|
|
||||||
|
|
||||||
async def rewrite(state: ReflectState) -> ReflectState:
|
async def rewrite(state: ReflectState) -> dict:
|
||||||
prompt = (
|
prompt = (
|
||||||
f"Rewrite the draft answer taking into account the following critique. Keep the answer concise (5–10 sentences).\n\nCritique:\n{state['critique']}\n\nOriginal Draft:\n{state['draft']}"
|
f"Rewrite the draft answer incorporating the following critique. Keep the answer concise (5–10 sentences).\n\n"
|
||||||
|
f"Critique: {state['critique']}\n\n"
|
||||||
|
f"Original Draft: {state['draft']}"
|
||||||
)
|
)
|
||||||
response = await llm.ainvoke([HumanMessage(content=prompt)])
|
response = await llm.ainvoke([{"role": "user", "content": prompt}])
|
||||||
state["draft"] = response.content.strip()
|
new_draft = response.content.strip()
|
||||||
state["round"] += 1
|
return {"draft": new_draft, "round": state['round'] + 1}
|
||||||
return state
|
|
||||||
|
|
||||||
# ---------- Graph ----------
|
# ---------- Graph construction ----------
|
||||||
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")
|
builder.add_edge("draft_answer", "reflect")
|
||||||
|
builder.add_conditional_edges(
|
||||||
|
"reflect",
|
||||||
|
lambda x: x["verdict"],
|
||||||
|
{
|
||||||
|
"ok": END,
|
||||||
|
"needs_revision": "rewrite",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
builder.add_edge("rewrite", "reflect")
|
||||||
|
|
||||||
# Transition logic
|
# Limit rounds
|
||||||
# After draft_answer -> reflect
|
async def limit_rounds(state: ReflectState) -> str:
|
||||||
graph.add_edge("draft_answer", "reflect")
|
if state["round"] >= state["max_rounds"] and state["verdict"] == "needs_revision":
|
||||||
# After reflect
|
return END
|
||||||
# if ok -> END
|
return "reflect"
|
||||||
# if needs_revision and round < max_rounds -> rewrite
|
|
||||||
# else -> END
|
|
||||||
|
|
||||||
def reflect_conditional(state: ReflectState):
|
builder.add_conditional_edges("rewrite", limit_rounds, {"reflect": "reflect", END: END})
|
||||||
if state["verdict"] == "ok":
|
|
||||||
return "END"
|
|
||||||
if state["round"] < state["max_rounds"]:
|
|
||||||
return "rewrite"
|
|
||||||
return "END"
|
|
||||||
|
|
||||||
graph.add_conditional_edges("reflect", reflect_conditional, {
|
graph = builder.compile()
|
||||||
"rewrite": "rewrite",
|
|
||||||
"END": "END",
|
|
||||||
})
|
|
||||||
|
|
||||||
# After rewrite -> reflect
|
# ---------- Demo execution ----------
|
||||||
graph.add_edge("rewrite", "reflect")
|
async def main():
|
||||||
|
question = "Объясни студенту разницу между tool и resource в MCP."
|
||||||
app = graph.compile()
|
|
||||||
|
|
||||||
# ---------- DeepAgent wrapper ----------
|
|
||||||
# The deepagent will simply forward the human message to the graph and return the final draft.
|
|
||||||
@tool
|
|
||||||
def run_graph(question: str) -> str:
|
|
||||||
"""Run the reflection graph for a given question."""
|
|
||||||
initial_state: ReflectState = {
|
initial_state: ReflectState = {
|
||||||
"question": question,
|
"question": question,
|
||||||
"draft": "",
|
"draft": "",
|
||||||
@@ -111,23 +95,8 @@ def run_graph(question: str) -> str:
|
|||||||
"round": 0,
|
"round": 0,
|
||||||
"max_rounds": 2,
|
"max_rounds": 2,
|
||||||
}
|
}
|
||||||
result = app.invoke(initial_state)
|
final_state = await graph.ainvoke(initial_state)
|
||||||
return result["draft"]
|
print("\nFinal Answer:\n", final_state["draft"])
|
||||||
|
|
||||||
agent = create_deep_agent(
|
|
||||||
model=llm,
|
|
||||||
tools=[run_graph],
|
|
||||||
backend=backend,
|
|
||||||
system_prompt="You are an assistant that can answer questions using a self‑checking process.",
|
|
||||||
)
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
question = "Объясни студенту разницу между tool и resource в MCP."
|
|
||||||
response = await agent.ainvoke(
|
|
||||||
{"messages": [HumanMessage(content=question)]},
|
|
||||||
{"configurable": {"thread_id": "session-1"}},
|
|
||||||
)
|
|
||||||
print("Final answer:\n", response["messages"][-1].content)
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
asyncio.run(main())
|
asyncio.run(main())
|
||||||
|
|||||||
Reference in New Issue
Block a user