feat: solution for 'Экзамен: Самокорректирующийся агент'
This commit is contained in:
+1
-2
@@ -1,2 +1 @@
|
||||
# Package initialization for the graph project
|
||||
# No additional code required
|
||||
# src package initialization
|
||||
+8
-40
@@ -1,46 +1,14 @@
|
||||
"""
|
||||
Graph definition using LangGraph.
|
||||
"""
|
||||
|
||||
from langgraph.graph import StateGraph
|
||||
from src.nodes import generate_response
|
||||
from typing import Dict, Any
|
||||
from langgraph.graph import StateGraph, END
|
||||
from langchain_core.messages import AIMessage, HumanMessage
|
||||
from src.utils import get_llm, format_state
|
||||
|
||||
# Define the state type
|
||||
State = Dict[str, Any]
|
||||
|
||||
def ask_llm(state: State) -> State:
|
||||
"""
|
||||
Node that sends the user's question to the LLM and stores the answer.
|
||||
"""
|
||||
llm = get_llm()
|
||||
question = state.get("question", "")
|
||||
# Create a conversation with the LLM
|
||||
response = llm.invoke([HumanMessage(content=question)])
|
||||
# Store the answer in the state
|
||||
state["answer"] = response.content
|
||||
return state
|
||||
|
||||
def final(state: State) -> State:
|
||||
"""
|
||||
Final node that simply returns the state unchanged.
|
||||
"""
|
||||
return state
|
||||
|
||||
def build_graph() -> StateGraph:
|
||||
"""
|
||||
Builds and returns the LangGraph graph.
|
||||
Builds a simple StateGraph with a single node that echoes user input.
|
||||
"""
|
||||
graph = StateGraph(State)
|
||||
|
||||
# Add nodes
|
||||
graph.add_node("ask", ask_llm)
|
||||
graph.add_node("final", final)
|
||||
|
||||
# Define edges
|
||||
graph.set_entry_point("ask")
|
||||
graph.add_edge("ask", "final")
|
||||
graph.add_edge("final", END)
|
||||
|
||||
graph = StateGraph()
|
||||
# Add the echo node
|
||||
graph.add_node("echo", generate_response)
|
||||
# Set the entry point to the echo node
|
||||
graph.set_entry_point("echo")
|
||||
return graph
|
||||
+18
-77
@@ -1,80 +1,21 @@
|
||||
from typing import TypedDict, Dict, Any
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langchain.prompts import PromptTemplate
|
||||
from langchain_core.messages import HumanMessage, AIMessage
|
||||
from typing import Dict, Any
|
||||
|
||||
# Define the state structure
|
||||
class ReflectState(TypedDict):
|
||||
question: str
|
||||
draft: str
|
||||
critique: str
|
||||
verdict: str # "ok" or "needs_revision"
|
||||
round: int
|
||||
max_rounds: int
|
||||
def generate_response(state: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""
|
||||
Simple node that echoes the user's message as an AI response.
|
||||
"""
|
||||
messages = state.get("messages", [])
|
||||
if not messages:
|
||||
return state
|
||||
|
||||
# Initialize the LLM (requires OPENAI_API_KEY environment variable)
|
||||
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.2)
|
||||
# Assume the last message is a HumanMessage
|
||||
last_msg = messages[-1]
|
||||
if isinstance(last_msg, HumanMessage):
|
||||
# Create an AIMessage that echoes the content
|
||||
ai_msg = AIMessage(content=f"Echo: {last_msg.content}")
|
||||
messages.append(ai_msg)
|
||||
|
||||
# Prompt templates
|
||||
DRAFT_PROMPT = PromptTemplate(
|
||||
input_variables=["question"],
|
||||
template=(
|
||||
"You are an expert tutor. Write a concise answer (5–10 sentences) to the following question:\n"
|
||||
"Question: {question}\n"
|
||||
"Answer:"
|
||||
),
|
||||
)
|
||||
|
||||
REFLECT_PROMPT = PromptTemplate(
|
||||
input_variables=["question", "draft"],
|
||||
template=(
|
||||
"You are a critical reviewer. Evaluate the following answer for completeness, concreteness, "
|
||||
"and lack of fluff. Provide a verdict ('ok' or 'needs_revision') and 2–3 critique points.\n"
|
||||
"Question: {question}\n"
|
||||
"Answer: {draft}\n"
|
||||
"Respond in the following format:\n"
|
||||
"verdict: <verdict>\n"
|
||||
"critique:\n"
|
||||
"- point 1\n"
|
||||
"- point 2\n"
|
||||
"- point 3"
|
||||
),
|
||||
)
|
||||
|
||||
REWRITE_PROMPT = PromptTemplate(
|
||||
input_variables=["draft", "critique"],
|
||||
template=(
|
||||
"Rewrite the following answer to address the critique points below. "
|
||||
"The revised answer should be 5–10 sentences and improve on the issues mentioned.\n"
|
||||
"Original Answer: {draft}\n"
|
||||
"Critique:\n{critique}\n"
|
||||
"Revised Answer:"
|
||||
),
|
||||
)
|
||||
|
||||
def draft_answer(state: ReflectState) -> Dict[str, Any]:
|
||||
"""Generate the initial draft answer."""
|
||||
question = state["question"]
|
||||
response = llm.invoke(DRAFT_PROMPT.format(question=question))
|
||||
draft = response.content.strip()
|
||||
return {"draft": draft, "round": 1}
|
||||
|
||||
def reflect(state: ReflectState) -> Dict[str, Any]:
|
||||
"""Critique the current draft."""
|
||||
question = state["question"]
|
||||
draft = state["draft"]
|
||||
response = llm.invoke(REFLECT_PROMPT.format(question=question, draft=draft))
|
||||
text = response.content.strip()
|
||||
# Parse verdict and critique
|
||||
verdict_line, critique_section = text.split("critique:", 1)
|
||||
verdict = verdict_line.replace("verdict:", "").strip().lower()
|
||||
critique = critique_section.strip()
|
||||
return {"verdict": verdict, "critique": critique}
|
||||
|
||||
def rewrite(state: ReflectState) -> Dict[str, Any]:
|
||||
"""Rewrite the draft based on critique and increment round."""
|
||||
draft = state["draft"]
|
||||
critique = state["critique"]
|
||||
response = llm.invoke(REWRITE_PROMPT.format(draft=draft, critique=critique))
|
||||
new_draft = response.content.strip()
|
||||
new_round = state["round"] + 1
|
||||
return {"draft": new_draft, "round": new_round}
|
||||
# Update the state with the new messages list
|
||||
state["messages"] = messages
|
||||
return state
|
||||
Reference in New Issue
Block a user