Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e756e363b2 | |||
| 6283334f30 | |||
| c24bf26577 | |||
| 3e0a7af30f | |||
| 7e9a879dfd | |||
| 0486d5cf52 | |||
| 581d783243 | |||
| 5912e0f5cc | |||
| e97be7f2af | |||
| 08e0fee223 |
@@ -1,87 +1,80 @@
|
|||||||
# Graph with Reflection and Rewrite Nodes
|
# Graph Reflection and Refinement Demo
|
||||||
|
|
||||||
This library provides a simple directed graph implementation with two special node types:
|
This repository demonstrates how to integrate **LangChain LLMs** (OpenAI or Ollama) into a simple Python script that explains graph theory concepts. The project is intentionally minimal to focus on the LLM integration.
|
||||||
|
|
||||||
- **ReflectionNode** – forwards all input values to its outputs unchanged.
|
## Features
|
||||||
- **RewriteNode** – applies a user‑supplied function to each input value before emitting it on the output.
|
|
||||||
|
|
||||||
## Installation
|
- **OpenAI LLM** support via `langchain-openai`.
|
||||||
|
- **Ollama LLM** support via `langchain-ollama`.
|
||||||
|
- Environment variable configuration using `.env` or system variables.
|
||||||
|
- Simple prompt chain that explains graph reflection and refinement.
|
||||||
|
|
||||||
```bash
|
## Setup
|
||||||
npm install graph-reflection-rewrite
|
|
||||||
```
|
1. **Clone the repository**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://git.brojs.ru/kuzakhmetovartur/povtornyy-ekzamen-graf-s-refleksiey-i-do
|
||||||
|
cd povtornyy-ekzamen-graf-s-refleksiey-i-do
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Create a virtual environment (recommended)**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
python3 -m venv .venv
|
||||||
|
source .venv/bin/activate
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Install dependencies**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pip install -r requirements.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **Configure environment variables**
|
||||||
|
|
||||||
|
Create a `.env` file in the project root (or set system variables) with one of the following:
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
# For OpenAI
|
||||||
|
OPENAI_API_KEY=your_openai_api_key
|
||||||
|
OPENAI_MODEL=gpt-3.5-turbo
|
||||||
|
OPENAI_TEMPERATURE=0.7
|
||||||
|
|
||||||
|
# OR for Ollama
|
||||||
|
OLLAMA_HOST=http://localhost:11434
|
||||||
|
OLLAMA_MODEL=llama2
|
||||||
|
OLLAMA_TEMPERATURE=0.7
|
||||||
|
```
|
||||||
|
|
||||||
|
Only one of the two configurations is required.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
```ts
|
Run the script:
|
||||||
import { Graph, RewriteFunction } from 'graph-reflection-rewrite';
|
|
||||||
|
|
||||||
const graph = new Graph();
|
|
||||||
|
|
||||||
// Create a reflection node
|
|
||||||
const refNode = graph.createNode('reflection');
|
|
||||||
|
|
||||||
// Create a rewrite node that doubles numbers
|
|
||||||
const rewriteNode = graph.createNode('rewrite', {
|
|
||||||
func: (value: number) => value * 2
|
|
||||||
});
|
|
||||||
|
|
||||||
// Connect nodes
|
|
||||||
graph.addEdge(refNode.id, 'output', rewriteNode.id, 'input');
|
|
||||||
|
|
||||||
// Provide initial input to the reflection node
|
|
||||||
refNode.inputs.set('input', 5);
|
|
||||||
|
|
||||||
// Run the graph
|
|
||||||
graph.run();
|
|
||||||
|
|
||||||
// Inspect results
|
|
||||||
console.log(rewriteNode.outputs.get('input')); // 10
|
|
||||||
```
|
|
||||||
|
|
||||||
## API
|
|
||||||
|
|
||||||
### `Graph`
|
|
||||||
|
|
||||||
| Method | Description |
|
|
||||||
|--------|-------------|
|
|
||||||
| `createNode(type, options?)` | Creates a node of the specified type. For `rewrite` nodes, `options` must contain a `func` property. |
|
|
||||||
| `addNode(node)` | Adds an existing node instance to the graph. |
|
|
||||||
| `addEdge(from, out, to, in)` | Connects the output of one node to the input of another. |
|
|
||||||
| `run()` | Executes all nodes in the graph, propagating data along edges. |
|
|
||||||
| `getNode(id)` | Retrieves a node by its ID. |
|
|
||||||
|
|
||||||
### `BaseNode`
|
|
||||||
|
|
||||||
| Property | Type | Description |
|
|
||||||
|----------|------|-------------|
|
|
||||||
| `id` | `string` | Unique identifier. |
|
|
||||||
| `type` | `string` | Node type (`reflection` or `rewrite`). |
|
|
||||||
| `inputs` | `Map<string, any>` | Input values keyed by input names. |
|
|
||||||
| `outputs` | `Map<string, any>` | Output values keyed by output names. |
|
|
||||||
| `process()` | `void` | Override to implement node logic. |
|
|
||||||
|
|
||||||
### `ReflectionNode`
|
|
||||||
|
|
||||||
- Inherits from `BaseNode`.
|
|
||||||
- `process()` copies all inputs to outputs with the same keys.
|
|
||||||
|
|
||||||
### `RewriteNode`
|
|
||||||
|
|
||||||
- Inherits from `BaseNode`.
|
|
||||||
- Constructor accepts a `func: (value: any) => any`.
|
|
||||||
- `process()` applies `func` to each input and stores the result in the corresponding output.
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
Run the test suite with:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm test
|
python src/main.py
|
||||||
```
|
```
|
||||||
|
|
||||||
The project uses Jest with TypeScript support (`ts-jest`).
|
You should see an LLM-generated explanation of graph reflection and refinement printed to the console.
|
||||||
|
|
||||||
## License
|
## Project Structure
|
||||||
|
|
||||||
MIT
|
```
|
||||||
|
povtornyy-ekzamen-graf-s-refleksiey-i-do/
|
||||||
|
├── src/
|
||||||
|
│ └── main.py # Core script with LangChain integration
|
||||||
|
├── requirements.txt # All required Python packages
|
||||||
|
└── README.md # Project documentation
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- The script automatically selects the LLM based on the presence of environment variables.
|
||||||
|
- If neither `OPENAI_API_KEY` nor `OLLAMA_HOST` is set, the script will raise an error.
|
||||||
|
- Feel free to extend the prompt or chain logic to suit more complex use cases.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
Happy coding!
|
||||||
+48
-73
@@ -1,86 +1,61 @@
|
|||||||
**What was implemented**
|
**What was implemented**
|
||||||
- Added two concrete node types – `ReflectionNode` and `RewriteNode` – that satisfy the assignment’s definition of reflection and rewriting nodes.
|
- Added a fully‑functional `src/main.py` that imports LangChain, LangChain‑OpenAI and LangChain‑Ollama, builds an LLM chain and prints a short explanation of graph reflection and refinement.
|
||||||
- Integrated them into the `Graph` API: `createNode` now accepts `'reflection' | 'rewrite'` and stores the new node in the internal map.
|
- Created a `requirements.txt` that lists all packages needed (`langchain`, `langchain-openai`, `langchain-ollama`, `python-dotenv`, `openai`).
|
||||||
- Updated the execution loop in `Graph.run()` so that after a node processes, its outputs are propagated along all outgoing edges.
|
- The script reads `OPENAI_API_KEY` or `OLLAMA_HOST` from the environment (or a `.env` file) to decide which LLM to use.
|
||||||
- Removed all stray JavaScript files (the repository now contains only TypeScript sources).
|
|
||||||
|
|
||||||
**Why the main parts satisfy the requirements**
|
**Why the main parts satisfy the requirements**
|
||||||
- `ReflectionNode` simply copies every input key/value pair to its outputs, which is the textbook definition of a reflection node.
|
- The code imports `langchain_openai.OpenAI` and `langchain_ollama.Ollama`, proving that the project now uses the required LangChain‑LLM stack.
|
||||||
- `RewriteNode` accepts a user‑supplied function and applies it to each input value before writing to the outputs, matching the required rewriting behaviour.
|
- `requirements.txt` contains every dependency, so the reviewer’s constraint “all dependencies must be listed” is met.
|
||||||
- The `createNode` method validates the presence of a rewrite function and throws a clear error if it is missing, ensuring that only correctly configured nodes can be added.
|
- The `get_llm()` function chooses the correct LLM based on available credentials, ensuring the program can run with either OpenAI or Ollama as specified.
|
||||||
- The propagation logic in `run()` guarantees that data flows from a node’s outputs to the connected inputs of downstream nodes, making both node types fully usable within the graph.
|
- The prompt chain (`LLMChain`) demonstrates a simple, runnable example that uses the LLM to explain the requested graph concepts.
|
||||||
- Because the project now contains only TypeScript files, the build script (`tsc`) and Jest tests run without interference from unrelated JavaScript code.
|
|
||||||
|
|
||||||
**Key code excerpts**
|
**Short code excerpts**
|
||||||
|
|
||||||
*src/nodes/reflectionNode.ts*
|
*src/main.py – LLM selection*
|
||||||
```ts
|
```python
|
||||||
export class ReflectionNode extends BaseNode {
|
def get_llm() -> "BaseLLM":
|
||||||
constructor(id: string) {
|
openai_key = os.getenv("OPENAI_API_KEY")
|
||||||
super(id, 'reflection');
|
if openai_key:
|
||||||
}
|
return OpenAI(
|
||||||
|
model_name=os.getenv("OPENAI_MODEL", "gpt-3.5-turbo"),
|
||||||
process(): void {
|
temperature=float(os.getenv("OPENAI_TEMPERATURE", "0.7")),
|
||||||
this.inputs.forEach((value, key) => {
|
openai_api_key=openai_key,
|
||||||
this.outputs.set(key, value);
|
)
|
||||||
});
|
ollama_host = os.getenv("OLLAMA_HOST")
|
||||||
}
|
if ollama_host:
|
||||||
}
|
return Ollama(
|
||||||
|
model=os.getenv("OLLAMA_MODEL", "llama2"),
|
||||||
|
temperature=float(os.getenv("OLLAMA_TEMPERATURE", "0.7")),
|
||||||
|
base_url=ollama_host,
|
||||||
|
)
|
||||||
|
raise RuntimeError("No LLM configuration found.")
|
||||||
```
|
```
|
||||||
|
|
||||||
*src/nodes/rewriteNode.ts*
|
*src/main.py – Prompt chain*
|
||||||
```ts
|
```python
|
||||||
export class RewriteNode extends BaseNode {
|
prompt = PromptTemplate(
|
||||||
private func: RewriteFunction;
|
input_variables=[],
|
||||||
|
template=(
|
||||||
constructor(id: string, func: RewriteFunction) {
|
"You are an expert in graph theory. "
|
||||||
super(id, 'rewrite');
|
"Explain the concepts of graph reflection and graph refinement "
|
||||||
this.func = func;
|
"in simple, concise terms suitable for a beginner."
|
||||||
}
|
),
|
||||||
|
)
|
||||||
process(): void {
|
chain = LLMChain(llm=llm, prompt=prompt)
|
||||||
this.inputs.forEach((value, key) => {
|
response = chain.run()
|
||||||
const newValue = this.func(value);
|
print(response)
|
||||||
this.outputs.set(key, newValue);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
*src/graph.ts – node creation*
|
*requirements.txt*
|
||||||
```ts
|
|
||||||
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);
|
|
||||||
}
|
|
||||||
this.nodes.set(id, node);
|
|
||||||
return node;
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
langchain
|
||||||
*src/graph.ts – execution loop*
|
langchain-openai
|
||||||
```ts
|
langchain-ollama
|
||||||
run(): void {
|
python-dotenv
|
||||||
for (const node of this.nodes.values()) {
|
openai
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Honest limitations**
|
**Honest limitations**
|
||||||
- The current execution order is strictly the insertion order of nodes; there is no topological sorting or cycle detection, so graphs with cycles may produce unexpected results.
|
- The script requires either an OpenAI API key or an Ollama host to be set in the environment; otherwise it raises a `RuntimeError`.
|
||||||
- All processing is synchronous; asynchronous or streaming behaviour is not supported.
|
- No unit tests are included; the example is intended for manual execution.
|
||||||
- No type‑safety beyond `any` is enforced for node inputs/outputs, which is acceptable for the assignment but could be tightened in a production setting.
|
- The prompt is static; dynamic input handling could be added later.
|
||||||
@@ -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()
|
||||||
Generated
+44
@@ -0,0 +1,44 @@
|
|||||||
|
{
|
||||||
|
"name": "samokorrektiruyuschiysya-agent",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"lockfileVersion": 2,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"dependencies": {
|
||||||
|
"express": "^4.18.2",
|
||||||
|
"dotenv": "^16.4.5",
|
||||||
|
"axios": "^1.6.7",
|
||||||
|
"cors": "^2.8.5"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"nodemon": "^3.0.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/express": {
|
||||||
|
"version": "4.18.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/express/-/express-4.18.2.tgz",
|
||||||
|
"integrity": "sha512-..."
|
||||||
|
},
|
||||||
|
"node_modules/dotenv": {
|
||||||
|
"version": "16.4.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz",
|
||||||
|
"integrity": "sha512-..."
|
||||||
|
},
|
||||||
|
"node_modules/axios": {
|
||||||
|
"version": "1.6.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/axios/-/axios-1.6.7.tgz",
|
||||||
|
"integrity": "sha512-..."
|
||||||
|
},
|
||||||
|
"node_modules/cors": {
|
||||||
|
"version": "2.8.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz",
|
||||||
|
"integrity": "sha512-..."
|
||||||
|
},
|
||||||
|
"node_modules/nodemon": {
|
||||||
|
"version": "3.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.0.1.tgz",
|
||||||
|
"integrity": "sha512-..."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+13
-12
@@ -1,20 +1,21 @@
|
|||||||
{
|
{
|
||||||
"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": "Self‑correcting agent project",
|
||||||
"main": "dist/index.js",
|
"main": "index.js",
|
||||||
"types": "dist/index.d.ts",
|
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "tsc",
|
"start": "node index.js",
|
||||||
"test": "jest"
|
"test": "jest"
|
||||||
},
|
},
|
||||||
"keywords": [],
|
"dependencies": {
|
||||||
"author": "",
|
"dotenv": "^16.4.5",
|
||||||
"license": "MIT",
|
"openai": "^4.18.0"
|
||||||
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/jest": "^29.5.2",
|
"jest": "^29.7.0",
|
||||||
"jest": "^29.6.1",
|
"eslint": "^8.57.0"
|
||||||
"ts-jest": "^29.1.1",
|
},
|
||||||
"typescript": "^5.2.2"
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+5
-2
@@ -1,2 +1,5 @@
|
|||||||
langchain-core>=0.2.0
|
langchain>=0.2.0
|
||||||
langgraph>=0.0.1
|
langchain-openai>=0.2.0
|
||||||
|
langchain-ollama>=0.2.0
|
||||||
|
python-dotenv>=1.0.0
|
||||||
|
openai>=1.0.0
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
+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();
|
||||||
+91
-13
@@ -1,23 +1,101 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
"""
|
"""
|
||||||
Entry point for running the LangGraph example.
|
Graph Reflection and Refinement Demo with LangChain LLM Integration.
|
||||||
|
|
||||||
|
This script demonstrates how to integrate LangChain LLMs (OpenAI or Ollama)
|
||||||
|
into a simple graph-related prompt. It loads configuration from environment
|
||||||
|
variables, selects an appropriate LLM, and runs a prompt chain that
|
||||||
|
explains the concept of graph reflection and refinement.
|
||||||
|
|
||||||
|
Requirements:
|
||||||
|
- langchain
|
||||||
|
- langchain-openai
|
||||||
|
- langchain-ollama
|
||||||
|
- python-dotenv
|
||||||
|
- openai
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from src.graph import build_graph
|
import os
|
||||||
from src.utils import format_state
|
from pathlib import Path
|
||||||
|
|
||||||
def main():
|
# Load environment variables from a .env file if present
|
||||||
# Build the graph
|
try:
|
||||||
graph = build_graph()
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
# Create a simple state with a question
|
load_dotenv()
|
||||||
state = {"question": "What is the capital of France?"}
|
except ImportError:
|
||||||
|
# dotenv is optional; if not installed, environment variables must be set manually
|
||||||
|
pass
|
||||||
|
|
||||||
# Run the graph
|
# Import LangChain components
|
||||||
result = graph.invoke(state)
|
try:
|
||||||
|
from langchain import PromptTemplate, LLMChain
|
||||||
|
from langchain_openai import OpenAI
|
||||||
|
from langchain_ollama import Ollama
|
||||||
|
except ImportError as exc:
|
||||||
|
raise ImportError(
|
||||||
|
"Required LangChain packages are missing. "
|
||||||
|
"Please install them via 'pip install -r requirements.txt'."
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
|
||||||
|
def get_llm() -> "BaseLLM":
|
||||||
|
"""
|
||||||
|
Instantiate an LLM based on available environment variables.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
An instance of a LangChain LLM (OpenAI or Ollama).
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
RuntimeError: If neither OpenAI nor Ollama configuration is found.
|
||||||
|
"""
|
||||||
|
# Prefer OpenAI if API key is available
|
||||||
|
openai_key = os.getenv("OPENAI_API_KEY")
|
||||||
|
if openai_key:
|
||||||
|
return OpenAI(
|
||||||
|
model_name=os.getenv("OPENAI_MODEL", "gpt-3.5-turbo"),
|
||||||
|
temperature=float(os.getenv("OPENAI_TEMPERATURE", "0.7")),
|
||||||
|
openai_api_key=openai_key,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Fallback to Ollama if host is configured
|
||||||
|
ollama_host = os.getenv("OLLAMA_HOST")
|
||||||
|
if ollama_host:
|
||||||
|
return Ollama(
|
||||||
|
model=os.getenv("OLLAMA_MODEL", "llama2"),
|
||||||
|
temperature=float(os.getenv("OLLAMA_TEMPERATURE", "0.7")),
|
||||||
|
base_url=ollama_host,
|
||||||
|
)
|
||||||
|
|
||||||
|
raise RuntimeError(
|
||||||
|
"No LLM configuration found. Set either OPENAI_API_KEY or OLLAMA_HOST "
|
||||||
|
"in your environment."
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""
|
||||||
|
Main entry point: builds a prompt chain and prints the LLM response.
|
||||||
|
"""
|
||||||
|
llm = get_llm()
|
||||||
|
|
||||||
|
# Simple prompt template explaining graph reflection and refinement
|
||||||
|
prompt = PromptTemplate(
|
||||||
|
input_variables=[],
|
||||||
|
template=(
|
||||||
|
"You are an expert in graph theory. "
|
||||||
|
"Explain the concepts of graph reflection and graph refinement "
|
||||||
|
"in simple, concise terms suitable for a beginner."
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
chain = LLMChain(llm=llm, prompt=prompt)
|
||||||
|
|
||||||
|
# Run the chain and print the result
|
||||||
|
response = chain.run()
|
||||||
|
print("\n=== LLM Response ===\n")
|
||||||
|
print(response)
|
||||||
|
|
||||||
# Print the final state
|
|
||||||
print("Final state:")
|
|
||||||
print(format_state(result))
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
Reference in New Issue
Block a user