{"id":51545183,"url":"https://github.com/gilf/prompt-chain","last_synced_at":"2026-07-09T17:30:59.837Z","repository":{"id":365192257,"uuid":"1263066295","full_name":"gilf/prompt-chain","owner":"gilf","description":"Browser-native AI agent runner executing step-by-step ReAct loops in background threads. Leverages Chrome's built-in Gemini Nano for local, private inference, modular skills, and IndexedDB session memory.","archived":false,"fork":false,"pushed_at":"2026-07-03T11:54:52.000Z","size":1049,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-07-03T13:29:01.709Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gilf.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-06-08T15:33:02.000Z","updated_at":"2026-07-03T11:54:56.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/gilf/prompt-chain","commit_stats":null,"previous_names":["gilf/prompt-chain"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/gilf/prompt-chain","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gilf%2Fprompt-chain","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gilf%2Fprompt-chain/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gilf%2Fprompt-chain/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gilf%2Fprompt-chain/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gilf","download_url":"https://codeload.github.com/gilf/prompt-chain/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gilf%2Fprompt-chain/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":35308362,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-07-09T02:00:07.329Z","response_time":57,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-07-09T17:30:59.762Z","updated_at":"2026-07-09T17:30:59.830Z","avatar_url":"https://github.com/gilf.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n  \u003cimg src=\"https://github.com/gilf/prompt-chain/blob/main/images/prompt-chain-logo.png\" alt=\"Prompt Chain Logo\" width=\"400\" /\u003e\n\u003c/div\u003e\n\n# On-Device Prompt Chain Agent\n\nAn interactive, on-device AI agent platform that runs inside a Web Worker. \nIt leverages **Prompt API** for private, local, and cost-free inference, combining custom tools, modular skills, persistent long-term memory, and a declarative **LangChain Expression Language (LCEL)** pipeline architecture.\n\n---\n\n## Key Features\n\n- **On-Device LLM Inference**: Runs entirely in the browser using Chrome's built-in `LanguageModel` API (`window.LanguageModel`), eliminating the need for external API keys or network latency.\n- **Composable Chains \u0026 Universal Agent Runtime (LCEL)**: \n  - Features declarative primitive composition via [src/runnables/](file:///c:/Lectures/Demo/src/runnables) (`RunnableSequence`, `RunnableParallel`, `.pipe()`, `.bind()`).\n  - [createAgentWorker()](file:///c:/Lectures/Demo/src/core/prompt-chain-worker.js) acts as a **Universal Agent Runtime Host**. It accepts either legacy tool arrays (to spin up default ReAct loops via `ReActAgentExecutor`) or **any custom Runnable chain topology**.\n- **Asynchronous Web Worker Architecture**: \n  - [prompt-chain-host.js](file:///c:/Lectures/Demo/src/core/prompt-chain-host.js) runs on the main browser thread to manage the LLM session.\n  - [prompt-chain-worker.js](file:///c:/Lectures/Demo/src/core/prompt-chain-worker.js) runs in a background thread to orchestrate the agent loop, execute tools, and handle errors, keeping the user interface completely responsive.\n- **Dynamic Skill \u0026 Tool Retrieval (Lightweight RAG)**: Matches the user prompt against loaded skills and tools using a token-overlap scorer, feeding only relevant context to the prompt and preserving token limits.\n- **Typed Message History \u0026 Roles (LangChain Standard)**:\n  - Structures memory using standardized message objects (`HumanMessage`, `AIMessage`, `SystemMessage`, `ToolMessage`) defined in [messages.js](file:///c:/Lectures/Demo/src/messages.js).\n  - Uses [agent-memory.js](file:///c:/Lectures/Demo/src/agent-memory.js) to persist object-oriented message schemas directly in **IndexedDB**.\n  - Implements automatic conversation summarization (defined in [utils.js](file:///c:/Lectures/Demo/src/utils.js)) once the chat history exceeds 5 turns, ensuring the context window remains optimized.\n- **Complex Structured Tool Schemas (Multi-Parameter Tools)**:\n  - Tools extend `Runnable` and accept structured JSON Schema parameter definitions. Supports both legacy string inputs and complex multi-parameter objects (e.g., `bookFlight({ origin: \"NYC\", dest: \"LAX\", passengers: 2 })`).\n  - Automatically validates required arguments prior to execution and generates precise self-correction feedback observations when parameters are missing.\n- **Event Callbacks \u0026 Token-by-Token Streaming**:\n  - Implements a global `CallbackManager` emitting structured lifecycle hooks (`on_chain_start`, `on_llm_start`, `on_llm_new_token`, `on_tool_start`, etc.).\n  - Uses Chrome's `session.promptStreaming()` API across the Web Worker boundary to render live, token-by-token reasoning updates in the UI.\n- **Dynamic Context Management \u0026 Rolling Summarization (`RunnableTokenBuffer`)**:\n  - Bridges Chrome Prompt API token monitoring (`session.measureContextUsage()`, `session.contextUsage`, `session.contextWindow`) across the Web Worker boundary.\n  - Features `RunnableTokenBuffer` LCEL primitive with a configurable watermark threshold (default **85%** of context window capacity).\n  - Automatically truncates verbose single-turn tool observations and triggers rolling summarization of past conversation turns to ensure continuous ReAct loops without quota errors.\n- **Human-in-the-Loop (HITL) Interruption \u0026 Checkpointing (`RunnableInterrupt`)**:\n  - Implements an asynchronous safety rail for sensitive operations (e.g., modifying databases, booking flights, or external network requests).\n  - When the agent attempts to invoke a tool flagged with `{ requiresApproval: true }`, the execution graph suspends and serializes its exact loop state (including sanitized context and turn history) into IndexedDB (`checkpoints` store).\n  - Emits a real-time `userApprovalRequired` event to the host UI, displaying an interactive approval card where developers can review or edit JSON tool parameters.\n- **Hybrid Local/Cloud Fallback \u0026 Readiness Routing (`RunnableFallback`)**:\n  - **Download State Monitoring**: Hooks into Chrome's `LanguageModel.create({ monitor(m) })` to track on-device model downloading, emitting real-time `modelDownloadProgress` events (`loaded`, `total`) to display UI progress bars.\n  - **Composable Readiness \u0026 Retry Routing**: Wraps the inference runtime in a `RunnableFallback` pipeline (`[localLLM, cloudFallbackLLM]`). If the local Prompt API is unavailable, rate-limited, or exceeds configurable self-correction retry limits (`maxSelfCorrectionAttempts`, default **2** attempts), execution transparently switches to `CloudFallbackLLMRunnable` (or remote fetch endpoints) without altering agent business logic or swallowing HITL interruptions.\n- **Native Structured Output Enforcement \u0026 Schema Grammar (`StructuredOutputRunnable`)**:\n  - Integrates JSON Schema parameter and output constraints directly into Chrome Prompt API options (`responseSchema` and `responseConstraint`).\n  - Features a zero-dependency client-side recursive JSON Schema validator (`validateJSONSchema`) producing exact JSON pointer error paths (e.g., `Error at /toolInput/passengers: expected number, got string`).\n  - Wraps agent inference steps inside `StructuredOutputRunnable`. If schema violations occur, exact pointer paths are intercepted and automatically injected into the ReAct self-correction loop for pinpoint model self-repair.\n- **On-Device Vector RAG \u0026 Semantic Tool/Skill Retrieval (`IndexedDBVectorStore` \u0026 `RunnableRetriever`)**:\n  - Features zero-dependency local vector search backed by IndexedDB (`IndexedDBVectorStore`) with exact mathematical cosine similarity ranking.\n  - Exposes an extensible `EmbeddingsPlugin` interface allowing developers to plug in any custom client-side embedding generator (such as Chrome's built-in embedding API or Transformers.js WebGPU models).\n  - Includes `RunnableRetriever` for declarative LCEL RAG pipelines.\n  - Upgraded `ToolRetriever` and `SkillRetriever` to perform dynamic semantic pruning, filtering manifests of 50+ tools/skills down to the Top-K most relevant items before LLM prompt construction.\n- **StateGraph \u0026 Multi-Agent Supervisor Swarms (`StateGraph` \u0026 `AgentSupervisor`)**:\n  - Brings LangGraph-style cyclical state graphs, conditional routing, and custom channel state reducers directly to on-device Web Workers.\n  - Features `AgentSupervisor` and `createAgentSupervisor` to dynamically evaluate team state and route tasks across specialized AI worker runnables using strict JSON schema output enforcement.\n- **Enterprise Observability \u0026 Tracing (LangSmith / OpenTelemetry Equivalent)**:\n  - Upgrades flat callback logs into standardized hierarchical OpenTelemetry trace trees (`Trace`, `Span`). Automatically tracks parent-child span links (`parentSpanId`), timestamps, execution durations (`durationMs`), status codes (`SpanStatus.OK / ERROR`), and custom attributes.\n  - Features built-in multi-destination exporters (`ConsoleTraceExporter`, `IndexedDBTraceExporter`, and `OTLPTraceExporter` for HTTP OTLP telemetry dashboards).\n  - Includes a live **Interactive Trace Explorer Dashboard** in the host UI (`index.html`) with expandable parent-child tree views and one-click OTLP JSON downloads.\n- **Interactive UI Stream**: A sleek interface built with HTML/CSS that displays real-time agent reasoning steps (Thoughts, Actions, and Observations), live token generation, download progress bars, interactive HITL approval cards, and trace hierarchies.\n\n---\n\n## File Directory \u0026 Architecture\n\n- **[index.html](file:///c:/Lectures/Demo/index.html)** \u0026 **[styles.css](file:///c:/Lectures/Demo/styles.css)**: The frontend user interface containing input fields, suggestion chips, reasoning stream log viewports, interactive HITL approval cards, download progress bars, and loaded skills indicators.\n- **[src/index.js](file:///c:/Lectures/Demo/src/index.js)**: Main package entry point exporting all library modules.\n- **[src/runnables/](file:///c:/Lectures/Demo/src/runnables)**: Modular LangChain Expression Language (LCEL) primitives:\n  - [runnable.js](file:///c:/Lectures/Demo/src/runnables/runnable.js): Base abstract class with `.pipe()` and `.bind()`.\n  - [runnable-sequence.js](file:///c:/Lectures/Demo/src/runnables/runnable-sequence.js): Sequential chaining (`RunnableSequence.from`).\n  - [runnable-parallel.js](file:///c:/Lectures/Demo/src/runnables/runnable-parallel.js): Parallel graph branching (`RunnableParallel`).\n  - [runnable-lambda.js](file:///c:/Lectures/Demo/src/runnables/runnable-lambda.js): Function wrapping (`RunnableLambda`).\n  - [runnable-passthrough.js](file:///c:/Lectures/Demo/src/runnables/runnable-passthrough.js): Identity mapping \u0026 assignment (`RunnablePassthrough.assign`).\n  - [runnable-token-buffer.js](file:///c:/Lectures/Demo/src/runnables/runnable-token-buffer.js): Context window watermark truncation \u0026 summarization.\n  - [runnable-interrupt.js](file:///c:/Lectures/Demo/src/runnables/runnable-interrupt.js) \u0026 [interrupt-exception.js](file:///c:/Lectures/Demo/src/runnables/interrupt-exception.js): Human-in-the-Loop suspension rails.\n  - [runnable-fallback.js](file:///c:/Lectures/Demo/src/runnables/runnable-fallback.js): Hybrid local/cloud model fallback routing.\n  - [structured-output-runnable.js](file:///c:/Lectures/Demo/src/runnables/structured-output-runnable.js) \u0026 [validate-json-schema.js](file:///c:/Lectures/Demo/src/runnables/validate-json-schema.js): JSON Schema validation and pinpoint self-repair.\n  - [runnable-retriever.js](file:///c:/Lectures/Demo/src/runnables/runnable-retriever.js): Declarative LCEL vector and semantic retriever primitive.\n  - [state-graph.js](file:///c:/Lectures/Demo/src/runnables/state-graph.js): LangGraph-style cyclical state graphs (`StateGraph`, `CompiledStateGraph`) with conditional routing and reducers.\n  - [agent-supervisor.js](file:///c:/Lectures/Demo/src/runnables/agent-supervisor.js): LLM-powered multi-agent supervisor router (`AgentSupervisor`, `createAgentSupervisor`).\n- **[src/retrievers/](file:///c:/Lectures/Demo/src/retrievers)**:\n  - [indexeddb-vector-store.js](file:///c:/Lectures/Demo/src/retrievers/indexeddb-vector-store.js): Zero-dependency local vector store backed by IndexedDB (`IndexedDBVectorStore`), pluggable embedding interface (`EmbeddingsPlugin`), and exact `cosineSimilarity` calculation.\n  - [semantic-retriever.js](file:///c:/Lectures/Demo/src/retrievers/semantic-retriever.js): Unified base retriever class (`SemanticRetriever`) providing vector cosine pruning and token overlap fallback.\n- **[src/observability/](file:///c:/Lectures/Demo/src/observability)**:\n  - [trace.js](file:///c:/Lectures/Demo/src/observability/trace.js): Core hierarchical primitives (`SpanStatus`, `Span`, `Trace`, and hex ID generation).\n  - [tracer.js](file:///c:/Lectures/Demo/src/observability/tracer.js): Active span stack manager and trace execution singleton (`Tracer`).\n  - [exporters.js](file:///c:/Lectures/Demo/src/observability/exporters.js): Standardized trace exporters (`SpanExporter`, `ConsoleTraceExporter`, `IndexedDBTraceExporter`, `OTLPTraceExporter`).\n  - [index.js](file:///c:/Lectures/Demo/src/observability/index.js): Observability package module entry point.\n- **[src/skills/](file:///c:/Lectures/Demo/src/skills)**:\n  - [skill.js](file:///c:/Lectures/Demo/src/skills/skill.js): Dynamic skill loader and markdown frontmatter parser.\n  - [skill-retriever.js](file:///c:/Lectures/Demo/src/skills/skill-retriever.js): Semantic skill retriever extending `SemanticRetriever`.\n- **[src/tools/](file:///c:/Lectures/Demo/src/tools)**:\n  - [tool-retriever.js](file:///c:/Lectures/Demo/src/tools/tool-retriever.js): Semantic tool retriever extending `SemanticRetriever`.\n- **[src/core/](file:///c:/Lectures/Demo/src/core)**:\n  - [prompt-chain-host.js](file:///c:/Lectures/Demo/src/core/prompt-chain-host.js): Main thread session manager, event dispatcher, and Prompt API host bridge.\n  - [prompt-chain-worker.js](file:///c:/Lectures/Demo/src/core/prompt-chain-worker.js): Universal Web Worker agent runtime host \u0026 `ReActAgentExecutor`.\n  - [callbacks.js](file:///c:/Lectures/Demo/src/core/callbacks.js): Global `CallbackManager` for structured event emitting and cross-thread token streaming.\n  - [messages.js](file:///c:/Lectures/Demo/src/core/messages.js): Standard LangChain typed message classes (`HumanMessage`, `AIMessage`, `SystemMessage`, `ToolMessage`).\n  - [prompt-template.js](file:///c:/Lectures/Demo/src/core/prompt-template.js): LCEL-pipeable prompt formatting component.\n  - [agent-memory.js](file:///c:/Lectures/Demo/src/core/agent-memory.js): IndexedDB persistent conversation storage manager.\n- **[src/examples/](file:///c:/Lectures/Demo/src/examples)**:\n  - [my-agent.js](file:///c:/Lectures/Demo/src/examples/my-agent.js): Default Web Worker entry point running global tools and dynamic skills.\n  - [custom-runner-demo.js](file:///c:/Lectures/Demo/src/examples/custom-runner-demo.js): Demonstration of custom linear QA topologies.\n  - [supervisor-demo.js](file:///c:/Lectures/Demo/src/examples/supervisor-demo.js): Demonstration of an LLM-supervised multi-agent swarm (`Researcher` + `MathExpert`).\n- **[tests/](file:///c:/Lectures/Demo/tests)**: Complete automated test suites covering LCEL runnables, HITL interrupts, callbacks, token buffers, structured tools, fallback routing, structured output, on-device vector RAG, and cyclical state graph / multi-agent supervisor swarms ([test-state-graph.js](file:///c:/Lectures/Demo/tests/test-state-graph.js)).\n\n\n---\n\n## LCEL Chaining \u0026 Runnable Usage Guide\n\n### 1. Sequential Chaining (`RunnableSequence` \u0026 `.pipe()`)\nCompose multiple runnables or functions step-by-step:\n```javascript\nimport { RunnableSequence, RunnableLambda } from './src/index.js';\n\n// Using .pipe()\nconst addOne = new RunnableLambda(async (x) =\u003e x + 1);\nconst multiplyTwo = new RunnableLambda(async (x) =\u003e x * 2);\nconst chain = addOne.pipe(multiplyTwo);\n\nconsole.log(await chain.invoke(3)); // Output: 8\n\n// Or declarative array syntax:\nconst arrayChain = RunnableSequence.from([\n    async (text) =\u003e text.trim(),\n    async (text) =\u003e text.toUpperCase()\n]);\nconsole.log(await arrayChain.invoke(\"  hello world  \")); // Output: \"HELLO WORLD\"\n```\n\n### 2. Parallel Branching (`RunnableParallel`)\nExecute multiple runnables concurrently on the same input object:\n```javascript\nimport { RunnableParallel } from './src/index.js';\n\nconst parallel = new RunnableParallel({\n    charCount: async (text) =\u003e text.length,\n    wordCount: async (text) =\u003e text.split(/\\s+/).filter(Boolean).length\n});\n\nconst stats = await parallel.invoke(\"Prompt Chain runs on device!\");\n// Output: { charCount: 28, wordCount: 5 }\n```\n\n### 3. State Enrichment (`RunnablePassthrough.assign`)\nAttach computed properties to an incoming input dictionary without mutating or dropping existing fields:\n```javascript\nimport { RunnablePassthrough } from './src/index.js';\n\nconst enrichChain = RunnablePassthrough.assign({\n    timestamp: async () =\u003e new Date().toISOString(),\n    normalizedTopic: async (input) =\u003e input.topic.toLowerCase()\n});\n\nconst enriched = await enrichChain.invoke({ topic: \"AI Agents\", user: \"Alice\" });\n// Output: { topic: \"AI Agents\", user: \"Alice\", timestamp: \"...\", normalizedTopic: \"ai agents\" }\n```\n\n### 4. Structured Output Enforcement (`StructuredOutputRunnable`)\nForce an LLM or pipeline step to produce strictly validated JSON matching a JSON Schema:\n```javascript\nimport { StructuredOutputRunnable } from './src/index.js';\n\nconst schema = {\n    type: \"object\",\n    properties: {\n        city: { type: \"string\" },\n        temp: { type: \"number\" }\n    },\n    required: [\"city\", \"temp\"]\n};\n\n// Wraps any runnable; intercepts markdown fences and validates properties\nconst structuredChain = new StructuredOutputRunnable(mockLLMRunnable, schema);\nconst res = await structuredChain.invoke(\"The weather in Tokyo is 22C\");\n// Output: { success: true, parsed: { city: \"Tokyo\", temp: 22 } }\n```\n\n### 5. Readiness \u0026 Self-Repair Fallbacks (`RunnableFallback`)\nAutomatically route to a backup model or cloud endpoint if local on-device inference fails or exceeds self-correction limits:\n```javascript\nimport { RunnableFallback } from './src/index.js';\n\nconst robustLLM = new RunnableFallback([\n    localOnDeviceLLM, // Tries Chrome window.LanguageModel first\n    cloudFallbackLLM  // Switches to cloud API if local model fails or is rate-limited\n], {\n    onFallback: async (err, failedRunnable, nextRunnable) =\u003e {\n        console.warn(`Local model failed (${err.message}), falling back to remote endpoint...`);\n    }\n});\n```\n\n### 6. Default ReAct Agent Mode\nPassing an array of tools to `createAgentWorker` automatically instantiates the built-in `ReActAgentExecutor`:\n```javascript\nimport { Tool, createAgentWorker } from './src/index.js';\n\nconst calcTool = new Tool(\"Calculator\", \"Evaluates math\", expr =\u003e eval(expr));\ncreateAgentWorker([calcTool]); // Runs standard 7-turn ReAct reasoning loop\n```\n\n### 7. Custom Agent Topologies (Bypassing ReAct)\nYou can pass **any custom Runnable chain** directly into `createAgentWorker()`:\n```javascript\nimport { RunnableSequence, RunnableLambda, createAgentWorker } from './src/index.js';\n\nconst directAnswerChain = RunnableSequence.from([\n    new RunnableLambda(async ({ userPrompt, logToMain }) =\u003e {\n        logToMain(\"Thought: Bypassing ReAct loop for linear execution...\");\n        return `Answer directly: ${userPrompt}`;\n    }),\n    myLLMRunnable // Any custom model wrapper or pipeline step\n]);\n```\n\n### 8. Human-in-the-Loop Interruption (`requiresApproval`)\nFlag sensitive tools with `{ requiresApproval: true }` to suspend execution before high-impact operations occur:\n```javascript\n// Worker side (my-agent.js)\nconst bookFlightTool = new Tool(\n    \"bookFlight\",\n    \"Books a flight ticket.\",\n    async ({ origin, dest, passengers }) =\u003e `Booked flight to ${dest}!`,\n    flightSchema,\n    { requiresApproval: true } // Execution pauses right before running this tool\n);\n\n// Host UI side (index.html)\nwindow.addEventListener(CallbackEvents.eventDispatch, (e) =\u003e {\n    if (e.detail.event === CallbackEvents.userApprovalRequired) {\n        const { checkpointId, toolName, toolInput } = e.detail;\n        // Prompt human user for review or modifications...\n        host.resume(checkpointId, approvedToolInput); // Rehydrate state and complete execution\n    }\n});\n```\n\n### 9. StateGraph \u0026 Multi-Agent Supervisor Swarms\nOrchestrate complex cyclical workflows and multi-agent swarms using LangGraph-style state graphs and LLM supervisors:\n```javascript\nimport { Tool, StateGraph, START, END, createAgentSupervisor, createAgentWorker, RunnableLambda } from './src/index.js';\n\n// 1. Define specialized worker runnables\nconst researcherAgent = new RunnableLambda(async (state) =\u003e {\n    const res = await searchTool.invoke(state.userPrompt);\n    return { messages: [`Researcher: ${res}`] };\n});\n\nconst mathAgent = new RunnableLambda(async (state) =\u003e {\n    const res = await calcTool.invoke(\"542 * 13\");\n    return { messages: [`MathExpert: ${res}`], finalAnswer: res };\n});\n\n// 2. Create an LLM Supervisor Router\nconst supervisor = createAgentSupervisor({\n    agents: [\n        { name: \"Researcher\", description: \"Searches documentation and specs\" },\n        { name: \"MathExpert\", description: \"Performs mathematical calculations\" }\n    ]\n});\n\n// 3. Build the cyclical StateGraph with state reducers\nconst graph = new StateGraph({\n    reducers: { messages: (old, add) =\u003e (old || []).concat(add) }\n});\n\ngraph.addNode(\"supervisor\", supervisor);\ngraph.addNode(\"Researcher\", researcherAgent);\ngraph.addNode(\"MathExpert\", mathAgent);\n\n// 4. Connect cyclical routing: Supervisor -\u003e Worker -\u003e Supervisor -\u003e END\ngraph.setEntryPoint(\"supervisor\");\ngraph.addConditionalEdges(\"supervisor\", (state) =\u003e state.next, {\n    \"Researcher\": \"Researcher\",\n    \"MathExpert\": \"MathExpert\",\n    \"FINISH\": END\n});\ngraph.addEdge(\"Researcher\", \"supervisor\");\ngraph.addEdge(\"MathExpert\", \"supervisor\");\n\n// 5. Host compiled swarm inside Web Worker runtime!\ncreateAgentWorker(graph.compile());\n```\n\n### 10. Enterprise Observability \u0026 OpenTelemetry Tracing (`Tracer` \u0026 Exporters)\nBridge flat lifecycle events into hierarchical parent-child span trees with multi-destination export (Console DevTools, local IndexedDB, or remote OTLP collectors like Jaeger / OpenTelemetry Collector):\n```javascript\nimport { Tracer, ConsoleTraceExporter, IndexedDBTraceExporter, OTLPTraceExporter, CallbackManager, createAgentWorker } from './src/index.js';\n\n// 1. Initialize hierarchical Tracer with desired exporters\nconst tracer = new Tracer(\"ProductionAgentTracer\")\n    .addExporter(new ConsoleTraceExporter()) // Styled parent-child tree logs in DevTools\n    .addExporter(new IndexedDBTraceExporter(\"AgentMemoryDB\", \"traces\")) // Persistent local storage\n    .addExporter(new OTLPTraceExporter({ endpointUrl: \"http://localhost:4318/v1/traces\" })); // OTLP HTTP JSON\n\n// 2. Attach Tracer to CallbackManager (or pass directly to worker runtime)\nconst callbacks = new CallbackManager().attachTracer(tracer);\n\n// 3. Spans (`AgentExecution` -\u003e `LLMInference` / `Tool.Calculator`) are generated automatically!\ncreateAgentWorker(myAgentRunnable, [], callbacks);\n```\n\n---\n\n## Prerequisites (How to Setup Chrome Built-in AI)\n\nThis project requires a Chrome version (or Chromium-based browser like Chrome Canary) with the experimental Prompt API enabled.\n\n1. Open Google Chrome.\n2. Navigate to `chrome://flags/#optimization-guide-on-device-model` and set it to **Enabled BypassPrefRequirement** (or **Enabled**).\n3. Navigate to `chrome://flags/#prompt-api-for-gemini-nano` and set it to **Enabled**.\n4. Relaunch Chrome.\n5. Wait for the on-device model to download in the background (you can verify it by opening DevTools console and checking if `window.LanguageModel` is defined).\n\n---\n\n## How to Run the Project\n\nBecause the project loads ES6 modules (`import/export`) and spins up Web Workers dynamically, opening `index.html` directly from your file system (`file://` protocol) will fail due to CORS security policies. You **must** serve it using a local web server.\n\n### Option 1: Using Node.js (npx)\n```bash\nnpx serve\n```\n\n### Option 2: Using Python\n```bash\npython -m http.server 8000\n```\n\n---\n\n## License\n\nThis project is licensed under the [MIT License](file:///c:/Lectures/Demo/LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgilf%2Fprompt-chain","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgilf%2Fprompt-chain","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgilf%2Fprompt-chain/lists"}