Compare commits
14 Commits
baf18c5876
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 1f22fb349c | |||
| 5b1720bf17 | |||
| d362ed7b56 | |||
| 6283334f30 | |||
| c24bf26577 | |||
| 3e0a7af30f | |||
| 7e9a879dfd | |||
| 0486d5cf52 | |||
| 581d783243 | |||
| 5912e0f5cc | |||
| e97be7f2af | |||
| 08e0fee223 | |||
| 153b04b33c | |||
| f14d41830d |
@@ -1,14 +1,16 @@
|
|||||||
# Project Requirements
|
# Самокорректирующийся агент
|
||||||
|
|
||||||
This project requires the following Python packages:
|
This repository contains a simple implementation of a self‑correcting agent using LangChain.
|
||||||
|
The project requires the following Python packages:
|
||||||
|
|
||||||
- `langgraph`
|
- `langchain-core` – core LangChain functionality.
|
||||||
- `langchain-openai`
|
- `langchain-openai` – OpenAI LLM provider (alternatively, `langchain-ollama` can be used).
|
||||||
|
- `langchain-ollama`
|
||||||
|
|
||||||
Install them using:
|
Install the dependencies with:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
pip install -r requirements.txt
|
pip install -r requirements.txt
|
||||||
```
|
```
|
||||||
|
|
||||||
Ensure you have a compatible Python environment before running the project.
|
Feel free to extend the agent with additional tools or prompts as needed.
|
||||||
+12
-21
@@ -1,30 +1,21 @@
|
|||||||
**Что реализовано**
|
**Что реализовано**
|
||||||
В файл `requirements.txt` добавлены два пакета, необходимые для работы проекта:
|
В файл `requirements.txt` добавлены два пакета:
|
||||||
|
- `langchain-core` – основной модуль, необходимый для работы с LLM‑провайдерами.
|
||||||
|
- `langchain-openai` – конкретный провайдер LLM, который можно импортировать в проект.
|
||||||
|
|
||||||
```
|
**Почему это удовлетворяет требованиям**
|
||||||
langgraph
|
- В файле явно присутствует строка `langchain-core`, что удовлетворяет ограничению «должен включать langchain-core».
|
||||||
langchain-openai
|
- Также присутствует строка `langchain-openai`, что удовлетворяет ограничению «должен включать либо langchain-openai, либо langchain-ollama».
|
||||||
```
|
- Пакеты находятся в списке зависимостей, поэтому при установке проекта они будут импортированы автоматически.
|
||||||
|
|
||||||
**Почему это решает задачу**
|
|
||||||
- `langgraph` обеспечивает инфраструктуру графов для агента.
|
|
||||||
- `langchain-openai` подключает OpenAI к LangChain, позволяя импортировать нужные модули без ошибок.
|
|
||||||
- Добавление в `requirements.txt` гарантирует, что при установке зависимостей через `pip install -r requirements.txt` оба пакета будут установлены автоматически.
|
|
||||||
|
|
||||||
**Краткие фрагменты кода**
|
**Краткие фрагменты кода**
|
||||||
|
|
||||||
*requirements.txt*
|
`requirements.txt`
|
||||||
```
|
```
|
||||||
langgraph
|
langchain-core
|
||||||
langchain-openai
|
langchain-openai
|
||||||
```
|
```
|
||||||
|
|
||||||
*Пример импорта в проекте (не менялся)*
|
**Ограничения / замечания**
|
||||||
```python
|
- В проекте пока не используется `langchain-ollama`; если понадобится поддержка локального LLM, можно заменить `langchain-openai` на `langchain-ollama`.
|
||||||
from langgraph import Graph
|
- После добавления пакетов необходимо убедиться, что они корректно устанавливаются в среде выполнения (pip install -r requirements.txt).
|
||||||
from langchain_openai import OpenAI
|
|
||||||
```
|
|
||||||
|
|
||||||
**Ограничения**
|
|
||||||
- В проекте не было других изменений, поэтому возможны проблемы, если в коде используются другие, не перечисленные в `requirements.txt`, зависимости.
|
|
||||||
- Если версия пакетов конфликтует с уже установленными, может потребоваться уточнение версий.
|
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""
|
||||||
|
A simple self-correcting agent example using LangGraph.
|
||||||
|
|
||||||
|
This script demonstrates how to build a minimal LangGraph graph
|
||||||
|
with three nodes: start, process, and end. The graph concatenates
|
||||||
|
a greeting message and prints it at the end. The example ensures
|
||||||
|
that imports from `langgraph.graph` work correctly.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from langgraph.graph import StateGraph, END
|
||||||
|
from typing import Dict, Any
|
||||||
|
|
||||||
|
|
||||||
|
class SimpleAgent:
|
||||||
|
"""
|
||||||
|
A minimal agent that builds and runs a LangGraph graph.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
# Create a new StateGraph instance
|
||||||
|
self.graph = StateGraph()
|
||||||
|
|
||||||
|
# Add nodes to the graph
|
||||||
|
self.graph.add_node("start", self.start_node)
|
||||||
|
self.graph.add_node("process", self.process_node)
|
||||||
|
self.graph.add_node("end", self.end_node)
|
||||||
|
|
||||||
|
# Define the entry point and edges
|
||||||
|
self.graph.set_entry_point("start")
|
||||||
|
self.graph.add_edge("start", "process")
|
||||||
|
self.graph.add_edge("process", "end")
|
||||||
|
self.graph.add_edge("end", END)
|
||||||
|
|
||||||
|
def start_node(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Initial node that sets the starting message.
|
||||||
|
"""
|
||||||
|
state["message"] = "Hello"
|
||||||
|
return state
|
||||||
|
|
||||||
|
def process_node(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Process node that appends to the message.
|
||||||
|
"""
|
||||||
|
state["message"] += " World"
|
||||||
|
return state
|
||||||
|
|
||||||
|
def end_node(self, state: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
|
"""
|
||||||
|
End node that prints the final message.
|
||||||
|
"""
|
||||||
|
print(state["message"])
|
||||||
|
return state
|
||||||
|
|
||||||
|
def run(self) -> None:
|
||||||
|
"""
|
||||||
|
Compile and execute the graph.
|
||||||
|
"""
|
||||||
|
# Compile the graph into a runnable function
|
||||||
|
runnable = self.graph.compile()
|
||||||
|
|
||||||
|
# Execute the graph with an empty initial state
|
||||||
|
runnable({})
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
agent = SimpleAgent()
|
||||||
|
agent.run()
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
module.exports = {
|
||||||
|
preset: 'ts-jest',
|
||||||
|
testEnvironment: 'node',
|
||||||
|
testMatch: ['**/__tests__/**/*.ts', '**/?(*.)+(spec|test).ts']
|
||||||
|
};
|
||||||
@@ -1,14 +1,25 @@
|
|||||||
from langchain_openai import OpenAI
|
from langgraph.graph import StateGraph
|
||||||
from langgraph import Graph
|
from src.graph import build_graph
|
||||||
|
from langchain_core.messages import HumanMessage
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
# Initialize OpenAI LLM
|
# Build and compile the graph
|
||||||
llm = OpenAI(model="gpt-3.5-turbo")
|
graph = build_graph()
|
||||||
# Create a simple LangGraph graph instance
|
app = graph.compile()
|
||||||
graph = Graph()
|
|
||||||
print("OpenAI and LangGraph imports succeeded.")
|
# Initial state with an empty messages list
|
||||||
print(f"LLM instance: {llm}")
|
state = {"messages": []}
|
||||||
print(f"Graph instance: {graph}")
|
|
||||||
|
# Simulate a user message
|
||||||
|
state["messages"].append(HumanMessage(content="Hello, agent!"))
|
||||||
|
|
||||||
|
# Run the graph
|
||||||
|
result = app.invoke(state)
|
||||||
|
|
||||||
|
# Print the resulting state
|
||||||
|
print("Resulting state:")
|
||||||
|
for msg in result["messages"]:
|
||||||
|
print(f"{msg.__class__.__name__}: {msg.content}")
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
+11
-10
@@ -1,18 +1,19 @@
|
|||||||
{
|
{
|
||||||
"name": "graph-reflection-rewrite",
|
"name": "self-correcting-agent",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"description": "Graph implementation with reflection and rewrite nodes.",
|
"description": "A minimal Node.js project demonstrating a self‑correcting agent using langchain-openai and langchain-core.",
|
||||||
"main": "src/index.js",
|
"main": "src/index.js",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "node test.js"
|
"start": "node src/index.js"
|
||||||
},
|
},
|
||||||
"keywords": [
|
"dependencies": {
|
||||||
"graph",
|
"langchain-core": "^0.1.0",
|
||||||
"reflection",
|
"langchain-openai": "^0.1.0"
|
||||||
"rewrite",
|
},
|
||||||
"node"
|
"engines": {
|
||||||
],
|
"node": ">=18"
|
||||||
"author": "Auto-generated",
|
},
|
||||||
|
"author": "Your Name",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
}
|
}
|
||||||
+3
-1
@@ -1,2 +1,4 @@
|
|||||||
langgraph
|
langchain-core
|
||||||
langchain-openai
|
langchain-openai
|
||||||
|
langchain-ollama
|
||||||
|
langgraph
|
||||||
+1
-2
@@ -1,2 +1 @@
|
|||||||
# Package initialization for the graph project
|
# src package initialization
|
||||||
# No additional code required
|
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { OpenAI } from 'langchain-openai';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates a response from the LLM for a given prompt.
|
||||||
|
*
|
||||||
|
* @param {string} prompt - The input prompt to send to the LLM.
|
||||||
|
* @returns {Promise<string>} The LLM's response text.
|
||||||
|
*/
|
||||||
|
export async function getResponse(prompt) {
|
||||||
|
const model = new OpenAI({
|
||||||
|
temperature: 0.7,
|
||||||
|
modelName: 'gpt-3.5-turbo'
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await model.invoke(prompt);
|
||||||
|
return response;
|
||||||
|
}
|
||||||
+8
-40
@@ -1,46 +1,14 @@
|
|||||||
"""
|
from langgraph.graph import StateGraph
|
||||||
Graph definition using LangGraph.
|
from src.nodes import generate_response
|
||||||
"""
|
|
||||||
|
|
||||||
from typing import Dict, Any
|
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:
|
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)
|
graph = StateGraph()
|
||||||
|
# Add the echo node
|
||||||
# Add nodes
|
graph.add_node("echo", generate_response)
|
||||||
graph.add_node("ask", ask_llm)
|
# Set the entry point to the echo node
|
||||||
graph.add_node("final", final)
|
graph.set_entry_point("echo")
|
||||||
|
|
||||||
# Define edges
|
|
||||||
graph.set_entry_point("ask")
|
|
||||||
graph.add_edge("ask", "final")
|
|
||||||
graph.add_edge("final", END)
|
|
||||||
|
|
||||||
return graph
|
return graph
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import { BaseNode } from './nodes/baseNode';
|
||||||
|
import { ReflectionNode } from './nodes/reflectionNode';
|
||||||
|
import { RewriteNode, RewriteFunction } from './nodes/rewriteNode';
|
||||||
|
|
||||||
|
export type Edge = {
|
||||||
|
from: string;
|
||||||
|
out: string;
|
||||||
|
to: string;
|
||||||
|
in: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export class Graph {
|
||||||
|
private nodes: Map<string, BaseNode>;
|
||||||
|
private edges: Edge[];
|
||||||
|
private nodeCounter: number;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.nodes = new Map();
|
||||||
|
this.edges = [];
|
||||||
|
this.nodeCounter = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private generateId(): string {
|
||||||
|
return `node_${this.nodeCounter++}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a node of the specified type.
|
||||||
|
* @param type 'reflection' | 'rewrite'
|
||||||
|
* @param options For rewrite nodes, provide { func: (value) => any }
|
||||||
|
*/
|
||||||
|
createNode(type: 'reflection' | 'rewrite', options?: any): BaseNode {
|
||||||
|
const id = this.generateId();
|
||||||
|
let node: BaseNode;
|
||||||
|
if (type === 'reflection') {
|
||||||
|
node = new ReflectionNode(id);
|
||||||
|
} else if (type === 'rewrite') {
|
||||||
|
if (!options || typeof options.func !== 'function') {
|
||||||
|
throw new Error('Rewrite node requires a func option');
|
||||||
|
}
|
||||||
|
node = new RewriteNode(id, options.func);
|
||||||
|
} else {
|
||||||
|
throw new Error(`Unknown node type: ${type}`);
|
||||||
|
}
|
||||||
|
this.nodes.set(id, node);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
addNode(node: BaseNode): void {
|
||||||
|
if (this.nodes.has(node.id)) {
|
||||||
|
throw new Error(`Node with id ${node.id} already exists`);
|
||||||
|
}
|
||||||
|
this.nodes.set(node.id, node);
|
||||||
|
}
|
||||||
|
|
||||||
|
addEdge(from: string, out: string, to: string, inKey: string): void {
|
||||||
|
if (!this.nodes.has(from) || !this.nodes.has(to)) {
|
||||||
|
throw new Error('Both nodes must exist to add an edge');
|
||||||
|
}
|
||||||
|
this.edges.push({ from, out, to, in: inKey });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Executes the graph in a simple order: nodes are processed in the order they were added.
|
||||||
|
* After each node processes, its outputs are propagated to connected nodes.
|
||||||
|
*/
|
||||||
|
run(): void {
|
||||||
|
for (const node of this.nodes.values()) {
|
||||||
|
node.process();
|
||||||
|
for (const edge of this.edges.filter(e => e.from === node.id)) {
|
||||||
|
const target = this.nodes.get(edge.to);
|
||||||
|
if (!target) continue;
|
||||||
|
const value = node.outputs.get(edge.out);
|
||||||
|
target.inputs.set(edge.in, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getNode(id: string): BaseNode | undefined {
|
||||||
|
return this.nodes.get(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
-56
@@ -1,66 +1,37 @@
|
|||||||
import ReflectionNode from './nodes/reflectionNode.js';
|
import { OpenAI } from "langchain-openai";
|
||||||
import RewriteNode from './nodes/rewriteNode.js';
|
import { BaseLLM } from "langchain-core";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Simple directed graph implementation that supports reflection and rewrite nodes.
|
* Simple self‑correcting agent demo.
|
||||||
|
* Requires an OpenAI API key set in the environment variable OPENAI_API_KEY.
|
||||||
*/
|
*/
|
||||||
class Graph {
|
async function main() {
|
||||||
constructor() {
|
// Ensure the API key is available
|
||||||
/** @type {Object.<string, Object>} */
|
if (!process.env.OPENAI_API_KEY) {
|
||||||
this.nodes = {};
|
console.error("Error: OPENAI_API_KEY environment variable is not set.");
|
||||||
/** @type {Array<{from: string, to: string}>} */
|
process.exit(1);
|
||||||
this.edges = [];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Instantiate the OpenAI LLM provider
|
||||||
* Adds a node to the graph.
|
const llm = new OpenAI({
|
||||||
* @param {Object} node - Node instance (must have id and type).
|
temperature: 0.7,
|
||||||
*/
|
// The API key is automatically read from the environment variable
|
||||||
addNode(node) {
|
});
|
||||||
if (!node || !node.id) {
|
|
||||||
throw new Error('Node must have an id.');
|
// Verify that llm is an instance of BaseLLM (from langchain-core)
|
||||||
}
|
if (!(llm instanceof BaseLLM)) {
|
||||||
this.nodes[node.id] = node;
|
console.error("Error: The LLM instance is not a BaseLLM.");
|
||||||
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
// Send a simple prompt to the LLM
|
||||||
* Adds a directed edge from one node to another.
|
const prompt = "Hello, world! What is the capital of France?";
|
||||||
* @param {string} fromId - Source node id.
|
try {
|
||||||
* @param {string} toId - Destination node id.
|
const response = await llm.invoke(prompt);
|
||||||
*/
|
console.log("LLM response:", response);
|
||||||
addEdge(fromId, toId) {
|
} catch (error) {
|
||||||
if (!this.nodes[fromId] || !this.nodes[toId]) {
|
console.error("Error invoking LLM:", error);
|
||||||
throw new Error('Both nodes must exist before adding an edge.');
|
|
||||||
}
|
|
||||||
this.edges.push({ from: fromId, to: toId });
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Evaluates the graph in topological order.
|
|
||||||
* @returns {Object.<string, *>} Mapping of node ids to their output values.
|
|
||||||
*/
|
|
||||||
evaluate() {
|
|
||||||
const visited = new Set();
|
|
||||||
const outputs = {};
|
|
||||||
|
|
||||||
const visit = (nodeId) => {
|
|
||||||
if (visited.has(nodeId)) return;
|
|
||||||
visited.add(nodeId);
|
|
||||||
|
|
||||||
// Find all incoming edges to this node
|
|
||||||
const incoming = this.edges.filter((e) => e.to === nodeId);
|
|
||||||
const inputValues = incoming.map((e) => outputs[e.from]);
|
|
||||||
|
|
||||||
// For simplicity, if multiple inputs, pass them as an array
|
|
||||||
const input = inputValues.length === 1 ? inputValues[0] : inputValues;
|
|
||||||
|
|
||||||
const node = this.nodes[nodeId];
|
|
||||||
outputs[nodeId] = node.process(input);
|
|
||||||
};
|
|
||||||
|
|
||||||
Object.keys(this.nodes).forEach(visit);
|
|
||||||
return outputs;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export { Graph, ReflectionNode, RewriteNode };
|
main();
|
||||||
+4
-10
@@ -1,10 +1,4 @@
|
|||||||
import { app } from './langgraph';
|
export { Graph } from './graph';
|
||||||
|
export { BaseNode } from './nodes/baseNode';
|
||||||
async function main() {
|
export { ReflectionNode } from './nodes/reflectionNode';
|
||||||
const result = await app.invoke({ input: 'Hello world' });
|
export { RewriteNode, RewriteFunction } from './nodes/rewriteNode';
|
||||||
console.log('Final result:', result);
|
|
||||||
}
|
|
||||||
|
|
||||||
main().catch((err) => {
|
|
||||||
console.error('Error during execution:', err);
|
|
||||||
});
|
|
||||||
+18
-77
@@ -1,80 +1,21 @@
|
|||||||
from typing import TypedDict, Dict, Any
|
from langchain_core.messages import HumanMessage, AIMessage
|
||||||
from langchain_openai import ChatOpenAI
|
from typing import Dict, Any
|
||||||
from langchain.prompts import PromptTemplate
|
|
||||||
|
|
||||||
# Define the state structure
|
def generate_response(state: Dict[str, Any]) -> Dict[str, Any]:
|
||||||
class ReflectState(TypedDict):
|
"""
|
||||||
question: str
|
Simple node that echoes the user's message as an AI response.
|
||||||
draft: str
|
"""
|
||||||
critique: str
|
messages = state.get("messages", [])
|
||||||
verdict: str # "ok" or "needs_revision"
|
if not messages:
|
||||||
round: int
|
return state
|
||||||
max_rounds: int
|
|
||||||
|
|
||||||
# Initialize the LLM (requires OPENAI_API_KEY environment variable)
|
# Assume the last message is a HumanMessage
|
||||||
llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0.2)
|
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
|
# Update the state with the new messages list
|
||||||
DRAFT_PROMPT = PromptTemplate(
|
state["messages"] = messages
|
||||||
input_variables=["question"],
|
return state
|
||||||
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}
|
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
export abstract class BaseNode {
|
||||||
|
id: string;
|
||||||
|
type: string;
|
||||||
|
inputs: Map<string, any>;
|
||||||
|
outputs: Map<string, any>;
|
||||||
|
|
||||||
|
constructor(id: string, type: string) {
|
||||||
|
this.id = id;
|
||||||
|
this.type = type;
|
||||||
|
this.inputs = new Map();
|
||||||
|
this.outputs = new Map();
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract process(): void;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { BaseNode } from './baseNode';
|
||||||
|
|
||||||
|
export class ReflectionNode extends BaseNode {
|
||||||
|
constructor(id: string) {
|
||||||
|
super(id, 'reflection');
|
||||||
|
}
|
||||||
|
|
||||||
|
process(): void {
|
||||||
|
// Copy all inputs to outputs with the same keys
|
||||||
|
this.inputs.forEach((value, key) => {
|
||||||
|
this.outputs.set(key, value);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { BaseNode } from './baseNode';
|
||||||
|
|
||||||
|
export type RewriteFunction = (value: any) => any;
|
||||||
|
|
||||||
|
export class RewriteNode extends BaseNode {
|
||||||
|
private func: RewriteFunction;
|
||||||
|
|
||||||
|
constructor(id: string, func: RewriteFunction) {
|
||||||
|
super(id, 'rewrite');
|
||||||
|
this.func = func;
|
||||||
|
}
|
||||||
|
|
||||||
|
process(): void {
|
||||||
|
this.inputs.forEach((value, key) => {
|
||||||
|
const newValue = this.func(value);
|
||||||
|
this.outputs.set(key, newValue);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
-5
@@ -1,10 +1,13 @@
|
|||||||
{
|
{
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"target": "ES2020",
|
"target": "ES2019",
|
||||||
"module": "CommonJS",
|
"module": "commonjs",
|
||||||
"outDir": "dist",
|
"declaration": true,
|
||||||
|
"outDir": "./dist",
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"esModuleInterop": true
|
"esModuleInterop": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"forceConsistentCasingInFileNames": true
|
||||||
},
|
},
|
||||||
"include": ["src"]
|
"include": ["src/**/*"]
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user