@picoflow/ezgraph 0.0.10 → 0.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
CHANGED
|
@@ -294,7 +294,6 @@ export class WeatherGraph extends BaseGraph<WeatherGraphStateType> {
|
|
|
294
294
|
return {
|
|
295
295
|
llmConfig: ModelCatalog.model("openai:gpt-5.4", { retries: 2 }),
|
|
296
296
|
endNode: GRAPH_END_NODE,
|
|
297
|
-
initialHistorySpace: "weather",
|
|
298
297
|
historySpaces: [
|
|
299
298
|
[CityNode, "weather"],
|
|
300
299
|
[WeatherNode, "weather"],
|
|
@@ -322,6 +321,12 @@ const result = await engine.run({
|
|
|
322
321
|
});
|
|
323
322
|
```
|
|
324
323
|
|
|
324
|
+
The first turn uses the initial `currentNode` declared by
|
|
325
|
+
`createGraphStateAnnotation(CityNode.id(), ...)`. EZGraph resolves that cursor
|
|
326
|
+
before appending the first user message, then uses the node's `historySpaces`
|
|
327
|
+
mapping (`"weather"` here). Later turns use the persisted current node. Nodes
|
|
328
|
+
without a mapping use `"default"`; no separate initial history setting is needed.
|
|
329
|
+
|
|
325
330
|
`GraphEngine.create()` loads the selected session store from environment
|
|
326
331
|
configuration. The result contains an HTTP-ready status/body envelope and a
|
|
327
332
|
session ID for the next customer turn.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var c=Object.defineProperty;var n=(o,e)=>c(o,"name",{value:e,configurable:!0});import{GraphLlm as p}from"./graph-llm.config.js";import{GraphNodeRuntime as
|
|
1
|
+
var c=Object.defineProperty;var n=(o,e)=>c(o,"name",{value:e,configurable:!0});import{GraphLlm as p}from"./graph-llm.config.js";import{GraphNodeRuntime as u}from"./graph-node.js";import{StateGraphExt as l}from"./state-graph-ext.js";import{assertEmptyResponseRetries as g,assertMaxAgentRounds as f,DEFAULT_CONVERSATION_POLICY as h,DEFAULT_MAX_AGENT_ROUNDS as y}from"./conversation-runner.js";import{assertLlmTimeoutMs as w}from"./llm-gateway.js";import{assertGraphSchemaVersion as m,assertStableId as E,stableClassId as a}from"./stable-id.js";class d{static{n(this,"BaseGraph")}llmGateway;static id(){return this.name}static assertName(e){return d.assertId(e)}static assertId(e){return E(e,"graph")}name;id;schemaVersion;llmConfig;requiresUserMessage;responseMode;maxAgentRounds;conversationPolicy;compiledGraph;runtime;nodeMap=new Map;endNode;migrations;constructor(e,r){this.llmGateway=e;const t=new.target;this.name=t.name,this.id=a(t,"graph"),this.schemaVersion=m(r.schemaVersion??1),this.migrations=N(r.migrations,this.schemaVersion),this.llmConfig=p.resolveConfig(r.llmConfig),this.requiresUserMessage=r.requiresUserMessage??!0,this.responseMode=r.responseMode??"chat",this.maxAgentRounds=f(r.maxAgentRounds??y),this.conversationPolicy=v(r),this.endNode=r.endNode,this.runtime=new u(r.endNode,this.llmConfig,R(r.historySpaces),this.responseMode,this.maxAgentRounds,this.conversationPolicy,r.decisionConfig,s=>this.onDecisionError(s),{onLlmBlocked:n(s=>this.onLlmBlocked(s),"onLlmBlocked"),shouldRetryLlmError:n(s=>this.shouldRetryLlmError(s),"shouldRetryLlmError"),onLlmError:n(s=>this.onLlmError(s),"onLlmError")})}async onLlmBlocked(e){return null}shouldRetryLlmError(e){}async onLlmError(e){return null}onDecisionError(e){return null}attachDecisionProviderResolver(e){this.runtime.attachDecisionProviderResolver(e)}get graph(){return this.compiledGraph??=this.buildGraph()}prepareInput(e,r){const t=e?.currentNode??this.initialNodeId(),s=this.runtime.historySpace(t);return{...e??{},currentNode:t,histories:{...e?.histories??{},[s]:[...e?.histories[s]??[],r]}}}initialNodeId(){const e=this.graph.channels?.currentNode;if(!e||typeof e.fromCheckpoint!="function")throw new Error(`Graph '${this.id}' must declare a currentNode default before preparing its first message.`);let r;try{r=e.fromCheckpoint().get()}catch(t){throw new Error(`Graph '${this.id}' must declare a currentNode default before preparing its first message.`,{cause:t})}if(typeof r!="string"||!r.trim())throw new Error(`Graph '${this.id}' must declare a non-empty currentNode default.`);return r}saveNodeState(e,r){this.runtime.saveNode(a(e,"graph node"),r)}async restoreSessionDoc(e){if(e.graph.id!==this.id)throw new Error(`Session '${e.id}' belongs to graph '${e.graph.id}', not '${this.id}'. Start a new session to run a different graph.`);if(e.graph.schemaVersion>this.schemaVersion)throw new Error(`Session '${e.id}' uses graph '${this.id}' schema version ${e.graph.schemaVersion}, but this runtime supports version ${this.schemaVersion}.`);let r=e;for(;r.graph.schemaVersion<this.schemaVersion;){const t=r.graph.schemaVersion,s=this.migrations.get(t);if(!s)throw new Error(`Graph '${this.id}' has no migration from schema version ${t} to ${t+1}.`);const i=await s.migrate(r);if(i.graph.id!==this.id)throw new Error(`Graph '${this.id}' migration from schema version ${t} changed the persisted graph ID.`);r={...i,graph:{...i.graph,schemaVersion:t+1}}}return await this.onRestoreSessionDoc(r)}async onRestoreSessionDoc(e){return e}idleMs(e){const r=Date.parse(e.modifiedAt);return Number.isFinite(r)?Date.now()-r:0}createStateGraph(e){return new l(e,(r=>this.createNode(r)),this.endNode)}createNode(e){const r=new e(this.llmGateway,this.runtime),t=a(e,"graph node");if(r.id!==t)throw new Error(`Graph node factory for '${t}' constructs '${r.id}'.`);if(this.nodeMap.has(r.id))throw new Error(`Graph node '${r.id}' is already registered.`);return this.nodeMap.set(r.id,r),this.runtime.registerTools(r.id,r.defineTool()),Object.freeze(r),r}}function v(o){const e=o.emptyResponseRecovery===void 0?h.emptyResponseRecovery:o.emptyResponseRecovery;return e&&g(e.retries),{...o.llmTimeoutMs===void 0?{}:{llmTimeoutMs:w(o.llmTimeoutMs)},emptyHistorySeed:o.emptyHistorySeed===void 0?h.emptyHistorySeed:o.emptyHistorySeed,emptyResponseRecovery:e}}n(v,"resolveConversationPolicy");function R(o){return Object.fromEntries((o??[]).map(([e,r])=>[a(e,"graph node"),r]))}n(R,"historySpaceMap");function N(o,e){const r=new Map;let t;for(const s of o??[]){const i=m(s.from);if(i>=e)throw new Error(`A graph migration from version ${i} cannot target schema version ${e}.`);if(r.has(i))throw new Error(`More than one graph migration starts at version ${i}.`);if(t!==void 0&&i!==t+1)throw new Error(`Graph migrations must be ordered and contiguous; version ${t} must be followed by ${t+1}.`);r.set(i,s),t=i}return r}n(N,"migrationMap");export{d as BaseGraph};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var E=Object.defineProperty;var i=(n,e)=>E(n,"name",{value:e,configurable:!0});import"reflect-metadata";import{AIMessage as p,HumanMessage as R}from"@langchain/core/messages";import{Command as c,END as f,isCommand as w}from"@langchain/langgraph";import{GraphLlm as u}from"./graph-llm.config.js";import{GraphStateSupport as T}from"./graph-state-support.js";import{ConversationRunner as O,DEFAULT_CONVERSATION_POLICY as H,DEFAULT_MAX_AGENT_ROUNDS as L,EmptyModelResponseError as $}from"./conversation-runner.js";import{currentTurnSignal as A}from"./turn-context.js";import{combineGraphNodeUpdates as b}from"./node-outcome.js";import{parseJsonObjectResponse as S}from"./json-response.js";import{stableClassId as g}from"./stable-id.js";import{SessionLogWarning as G}from"./session-log.js";import{isToolResponse as N,stay as k}from"./tool-response.js";import{invocationGraphState as I,hasNodeInvocation as M,invocationHistory as P,invocationNodeState as _,invocationUpdate as D,appendInvocationHistory as U,replaceInvocationNodeState as j,saveInvocationNodeState as x,withNodeInvocation as J}from"./node-invocation.js";import{DecisionConfigurationError as q,resolveDecisionOptions as F}from"./decision/decision-types.js";import{GRAPH_NODE_LOCAL_STATE as fe}from"./node-outcome.js";const z=Symbol("GRAPH_NODE_CLASS"),y=Symbol("graph-node-tool-handlers");function ce(n){if(!n.trim())throw new Error("A tool handler requires a tool name.");return(e,t)=>{const o=Reflect.getOwnMetadata(y,e)??[];if(o.some(r=>r.toolName===n))throw new Error(`Tool '${n}' already has a handler.`);o.push({toolName:n,methodName:t}),Reflect.defineMetadata(y,o,e)}}i(ce,"Tool");class C{static{i(this,"GraphNode")}llmGateway;runtime;static[z]=!0;static id(){return this.name}name;id;constructor(e,t){this.llmGateway=e,this.runtime=t;const o=new.target;this.name=o.name,this.id=g(o,"graph node")}get graph(){return this.runtime}defineTool(){return[]}getLlmConfig(){return{}}route(e){throw new Error(`Graph node '${this.id}' does not define a branch route.`)}async handleTool(e,t,o){const r=this.toolHandler(t.name);if(!r)return this.rejectToolCall(t.name,`Unsupported tool '${t.name}'.`);const d=this.runtime.requireTool(r.toolName),s=X(t.args);if(!s.ok)return this.rejectToolCall(r.toolName,s.error);const a=d.schema.safeParse(s.value);if(!a.success)return this.rejectToolCall(r.toolName,Y(a.error));const h=a.data,l=this[r.methodName];if(!l)throw new Error(`Tool '${r.toolName}' is decorated on missing method '${String(r.methodName)}'.`);const m=await l.call(this,h,o,e);if(N(m))return m;throw new Error(`Tool '${r.toolName}' on '${this.id}' must return a ToolResponse.`)}rejectToolCall(e,t){return G({tool_call:t,node:this.id,tool:e}),k(JSON.stringify({accepted:!1,error:t}))}usesChatModel(){return!0}onInvalidJsonResponse(e){throw e.error}onEmptyModelResponse(e){throw new $(e.reason)}invoke=i(e=>this.runtime.withInvocation(this.id,e,async()=>{const t=this.resolveNodeResponse(await this.run(e)),o=W(t),r=await this.resolveJsonResponse(e,o);if(this.runtime.stageNodeEntries(r.nodes),this.usesChatModel()){const s=this.runtime.resolveLlmConfig(this.getLlmConfig()),a=V(s,this.runtime.resolveLlmConfig()),h=(e.nodes??{})[this.id];(!a||h?.model!==void 0)&&this.runtime.saveNode(this.id,{model:a?void 0:u.modelMetadata(s)})}const d=b(r,this.runtime.stagedUpdate());return w(t)?new c({update:d,...t.goto===void 0?{}:{goto:t.goto},...t.graph===void 0?{}:{graph:t.graph},...t.resume===void 0?{}:{resume:t.resume}}):d}),"invoke");obtainTools(){return this.toolHandlers().map(({toolName:e})=>this.runtime.requireTool(e)).sort((e,t)=>e.name==="terminate_session"?1:t.name==="terminate_session"?-1:0)}validateTools(){this.obtainTools()}llmConfig(){return this.runtime.resolveLlmConfig(this.getLlmConfig())}llmCallOptions(){return this.runtime.llmCallOptions()}async runConversation(e,t){const o=await this.runAgentLoop(e,t);if(!o.stopReason)return o;const r=await this.onEmptyModelResponse({state:e,conversation:o,reason:o.stopReason});return{...o,response:r}}conversationLlmLifecycle(){}runAgentLoop(e,t){const o=this.conversationLlmLifecycle();return new O(this.llmGateway).run({...o===void 0?{}:{lifecycle:o},systemPrompt:this.getPrompt(e),history:this.history(e),tools:this.obtainTools(),llmConfig:this.llmConfig(),executeTool:i(r=>this.handleTool(e,r,t),"executeTool"),maxAgentRounds:this.runtime.maxAgentRounds,emptyHistorySeed:this.runtime.conversationPolicy.emptyHistorySeed,emptyResponseRecovery:this.runtime.conversationPolicy.emptyResponseRecovery,callOptions:this.llmCallOptions()})}historySpace(){return this.runtime.historySpace(this.id)}history(e){return this.runtime.hasInvocation()?this.runtime.invocationHistory(this.historySpace()):e.histories[this.historySpace()]??[]}historyUpdate(e){return{histories:{[this.historySpace()]:e}}}respond(e){return{...this.runtime.respond(e),...this.historyUpdate([new p(e)])}}complete(e){return{...this.runtime.complete(e),...this.historyUpdate([new p(e)])}}resolveNodeResponse(e){if(!N(e))return e;if(e.kind==="stay")throw new Error(`Graph node '${this.id}' can only return stay() from a tool handler.`);if(e.cleanup)throw new Error(`Graph node '${this.id}' can only use withCleanup() from a tool handler.`);if(e.feedback!==void 0)throw new Error(`Graph node '${this.id}' can only use withToolFeedback() from a tool handler.`);if(e.messages&&this.graph.appendHistory(this.historySpace(),e.messages),e.kind==="go"||e.kind==="directTo"){if(!e.target)throw new Error(`Graph node '${this.id}' selected ${e.kind}() without a target.`);const t=g(e.target,"graph node"),o=this.graph.historySpace(t);if(e.state&&this.graph.saveNodeState(e.target,e.state),e.message&&this.graph.appendHistory(o,[e.message]),e.kind==="directTo"){const r=v(this.id,e);return this.graph.appendHistory(o,[new p(r)]),new c({update:{currentNode:t,response:r,inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:f})}return new c({update:{currentNode:t,response:"",inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:t})}if(e.message)throw new Error(`Graph node '${this.id}' can only use withMessage() with go() or directTo().`);if(e.kind==="direct"){const t=v(this.id,e);return this.graph.appendHistory(this.historySpace(),[new p(t)]),new c({update:{currentNode:this.id,response:t,inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:f})}if(e.kind==="finish"){const t=v(this.id,e);return this.graph.appendHistory(this.historySpace(),[new p(t)]),new c({update:{...this.graph.complete(t),...e.usage===void 0?{}:{tokens:e.usage}},goto:f})}throw new Error(`Graph node '${this.id}' returned an unsupported response kind '${e.kind}'.`)}state(e){return this.runtime.hasInvocation()?this.runtime.nodeState(this.id):e.nodes[this.id]??{}}getState(){return this.runtime.nodeState(this.id)}saveState(e){this.runtime.saveNode(this.id,e)}save(e){return this.runtime.saveNode(this.id,e)}remove(...e){return this.runtime.removeNode(this.id,...e)}toolHandler(e){return this.toolHandlers().find(t=>t.toolName===e)}async resolveJsonResponse(e,t){if(!this.runtime.expectsJsonResponse()||t.completed!==!0)return t;try{return S(t.response??""),t}catch(o){const r=await this.onInvalidJsonResponse({state:e,update:t,response:t.response??"",error:o instanceof Error?o:new Error(String(o))});return(r.completed===!0||r.response)&&S(r.response??""),r}}toolHandlers(){let e=Object.getPrototypeOf(this);const t=[];for(;e&&e!==C.prototype;){const r=Reflect.getOwnMetadata(y,e)??[];t.push(...r),e=Object.getPrototypeOf(e)}const o=new Set;for(const r of t){if(o.has(r.toolName))throw new Error(`Graph node '${this.id}' has more than one handler for tool '${r.toolName}'.`);o.add(r.toolName)}return t}}function V(n,e){return n.model===e.model&&JSON.stringify(u.parameters(n))===JSON.stringify(u.parameters(e))}i(V,"sameLlmConfig");class le extends T{static{i(this,"GraphNodeRuntime")}defaultLlmConfig;historySpaces;initialHistorySpace;responseMode;maxAgentRounds;conversationPolicy;decisionOptions;decisionErrorHandler;llmLifecycle;tools=new Map;constructor(e,t,o={},r="default",d="chat",s=L,a=H,h={},l,m){super(e),this.defaultLlmConfig=t,this.historySpaces=o,this.initialHistorySpace=r,this.responseMode=d,this.maxAgentRounds=s,this.conversationPolicy=a,this.decisionOptions=h,this.decisionErrorHandler=l,this.llmLifecycle=m}llmCallOptions(){const{llmTimeoutMs:e}=this.conversationPolicy,t=A();return{...e===void 0?{}:{timeoutMs:e},...t===void 0?{}:{signal:t}}}expectsJsonResponse(){return this.responseMode==="json"}historySpace(e){return e?this.historySpaces[e]??this.initialHistorySpace:this.initialHistorySpace}resolveLlmConfig(e={}){return u.resolveConfig(this.defaultLlmConfig,e)}resolveDecisionOptions(e={}){return F(this.decisionOptions,e)}decisionProviderResolver;attachDecisionProviderResolver(e){this.decisionProviderResolver=e}resolveDecisionProvider(e){if(!this.decisionProviderResolver)throw new q(`Decision provider '${e}' cannot be resolved before the graph is attached to an engine.`);return this.decisionProviderResolver(e)}async handleDecisionError(e){return await this.decisionErrorHandler?.(e)??null}registerTools(e,t){for(const o of t){const r=this.tools.get(o.name);if(r)throw new Error(`Tool '${o.name}' is defined by both '${r.owner}' and '${e}'.`);this.tools.set(o.name,{definition:o,owner:e})}}requireTool(e){const t=this.tools.get(e);if(!t)throw new Error(`Tool '${e}' is not defined in this graph.`);return t.definition}input(e){return this.latestInput({messages:e.histories[this.historySpace(e.currentNode)]??[]})}getConversation(e){const o=(this.hasInvocation()?this.invocationHistory(e):[]).filter(r=>R.isInstance(r)&&r.additional_kwargs?.ezgraphInternal!==!0).map(r=>typeof r.content=="string"?r.content:JSON.stringify(r.content));return{request:o.at(-1)??"",priorRequests:o.slice(-5,-1)}}respond(e){return this.responseUpdate(e)}complete(e){return this.endUpdate(e)}withInvocation(e,t,o){return J(this,e,t,o)}nodeState(e){return _(this,e)}hasInvocation(){return M(this)}graphState(){return I(this)}appendHistory(e,t){U(this,e,t)}invocationHistory(e){return P(this,e)}stagedUpdate(){return D(this)}stageNodeEntries(e){for(const[t,o]of Object.entries(e??{}))!o||typeof o!="object"||Array.isArray(o)||j(this,t,o)}saveNode(e,t){return x(this,e,t),{nodes:{[e]:this.nodeState(e)}}}saveNodeState(e,t){this.saveNode(g(e,"graph node"),t)}removeNode(e,...t){return this.saveNode(e,Object.fromEntries(t.map(o=>[o,void 0])))}}function W(n){if(!w(n))return n;if(Array.isArray(n.update))throw new Error("GraphNode Command updates must be state objects.");return n.update??{}}i(W,"commandUpdate");function v(n,e){if(!e.response?.trim())throw new Error(`Graph node '${n}' selected ${e.kind}() without a response.`);return e.response}i(v,"requireNodeResponse");function X(n){if(typeof n!="string")return{ok:!0,value:n};try{return{ok:!0,value:JSON.parse(n)}}catch(e){return{ok:!1,error:`Tool arguments were not valid JSON: ${e instanceof Error?e.message:String(e)}`}}}i(X,"coerceToolArgs");function Y(n){return n.issues.map(e=>e.path.length>0?`${e.path.join(".")}: ${e.message}`:e.message).join("; ")}i(Y,"formatToolArgumentError");export{z as GRAPH_NODE_CLASS,fe as GRAPH_NODE_LOCAL_STATE,C as GraphNode,le as GraphNodeRuntime,ce as Tool};
|
|
1
|
+
var E=Object.defineProperty;var i=(n,e)=>E(n,"name",{value:e,configurable:!0});import"reflect-metadata";import{AIMessage as p,HumanMessage as R}from"@langchain/core/messages";import{Command as c,END as u,isCommand as w}from"@langchain/langgraph";import{GraphLlm as m}from"./graph-llm.config.js";import{GraphStateSupport as T}from"./graph-state-support.js";import{ConversationRunner as O,DEFAULT_CONVERSATION_POLICY as H,DEFAULT_MAX_AGENT_ROUNDS as L,EmptyModelResponseError as $}from"./conversation-runner.js";import{currentTurnSignal as A}from"./turn-context.js";import{combineGraphNodeUpdates as b}from"./node-outcome.js";import{parseJsonObjectResponse as S}from"./json-response.js";import{stableClassId as f}from"./stable-id.js";import{SessionLogWarning as G}from"./session-log.js";import{isToolResponse as N,stay as k}from"./tool-response.js";import{invocationGraphState as I,hasNodeInvocation as M,invocationHistory as P,invocationNodeState as _,invocationUpdate as D,appendInvocationHistory as U,replaceInvocationNodeState as j,saveInvocationNodeState as x,withNodeInvocation as J}from"./node-invocation.js";import{DecisionConfigurationError as q,resolveDecisionOptions as F}from"./decision/decision-types.js";import{GRAPH_NODE_LOCAL_STATE as fe}from"./node-outcome.js";const z=Symbol("GRAPH_NODE_CLASS"),g=Symbol("graph-node-tool-handlers");function ce(n){if(!n.trim())throw new Error("A tool handler requires a tool name.");return(e,t)=>{const o=Reflect.getOwnMetadata(g,e)??[];if(o.some(r=>r.toolName===n))throw new Error(`Tool '${n}' already has a handler.`);o.push({toolName:n,methodName:t}),Reflect.defineMetadata(g,o,e)}}i(ce,"Tool");class C{static{i(this,"GraphNode")}llmGateway;runtime;static[z]=!0;static id(){return this.name}name;id;constructor(e,t){this.llmGateway=e,this.runtime=t;const o=new.target;this.name=o.name,this.id=f(o,"graph node")}get graph(){return this.runtime}defineTool(){return[]}getLlmConfig(){return{}}route(e){throw new Error(`Graph node '${this.id}' does not define a branch route.`)}async handleTool(e,t,o){const r=this.toolHandler(t.name);if(!r)return this.rejectToolCall(t.name,`Unsupported tool '${t.name}'.`);const d=this.runtime.requireTool(r.toolName),s=X(t.args);if(!s.ok)return this.rejectToolCall(r.toolName,s.error);const a=d.schema.safeParse(s.value);if(!a.success)return this.rejectToolCall(r.toolName,Y(a.error));const h=a.data,l=this[r.methodName];if(!l)throw new Error(`Tool '${r.toolName}' is decorated on missing method '${String(r.methodName)}'.`);const v=await l.call(this,h,o,e);if(N(v))return v;throw new Error(`Tool '${r.toolName}' on '${this.id}' must return a ToolResponse.`)}rejectToolCall(e,t){return G({tool_call:t,node:this.id,tool:e}),k(JSON.stringify({accepted:!1,error:t}))}usesChatModel(){return!0}onInvalidJsonResponse(e){throw e.error}onEmptyModelResponse(e){throw new $(e.reason)}invoke=i(e=>this.runtime.withInvocation(this.id,e,async()=>{const t=this.resolveNodeResponse(await this.run(e)),o=W(t),r=await this.resolveJsonResponse(e,o);if(this.runtime.stageNodeEntries(r.nodes),this.usesChatModel()){const s=this.runtime.resolveLlmConfig(this.getLlmConfig()),a=V(s,this.runtime.resolveLlmConfig()),h=(e.nodes??{})[this.id];(!a||h?.model!==void 0)&&this.runtime.saveNode(this.id,{model:a?void 0:m.modelMetadata(s)})}const d=b(r,this.runtime.stagedUpdate());return w(t)?new c({update:d,...t.goto===void 0?{}:{goto:t.goto},...t.graph===void 0?{}:{graph:t.graph},...t.resume===void 0?{}:{resume:t.resume}}):d}),"invoke");obtainTools(){return this.toolHandlers().map(({toolName:e})=>this.runtime.requireTool(e)).sort((e,t)=>e.name==="terminate_session"?1:t.name==="terminate_session"?-1:0)}validateTools(){this.obtainTools()}llmConfig(){return this.runtime.resolveLlmConfig(this.getLlmConfig())}llmCallOptions(){return this.runtime.llmCallOptions()}async runConversation(e,t){const o=await this.runAgentLoop(e,t);if(!o.stopReason)return o;const r=await this.onEmptyModelResponse({state:e,conversation:o,reason:o.stopReason});return{...o,response:r}}conversationLlmLifecycle(){}runAgentLoop(e,t){const o=this.conversationLlmLifecycle();return new O(this.llmGateway).run({...o===void 0?{}:{lifecycle:o},systemPrompt:this.getPrompt(e),history:this.history(e),tools:this.obtainTools(),llmConfig:this.llmConfig(),executeTool:i(r=>this.handleTool(e,r,t),"executeTool"),maxAgentRounds:this.runtime.maxAgentRounds,emptyHistorySeed:this.runtime.conversationPolicy.emptyHistorySeed,emptyResponseRecovery:this.runtime.conversationPolicy.emptyResponseRecovery,callOptions:this.llmCallOptions()})}historySpace(){return this.runtime.historySpace(this.id)}history(e){return this.runtime.hasInvocation()?this.runtime.invocationHistory(this.historySpace()):e.histories[this.historySpace()]??[]}historyUpdate(e){return{histories:{[this.historySpace()]:e}}}respond(e){return{...this.runtime.respond(e),...this.historyUpdate([new p(e)])}}complete(e){return{...this.runtime.complete(e),...this.historyUpdate([new p(e)])}}resolveNodeResponse(e){if(!N(e))return e;if(e.kind==="stay")throw new Error(`Graph node '${this.id}' can only return stay() from a tool handler.`);if(e.cleanup)throw new Error(`Graph node '${this.id}' can only use withCleanup() from a tool handler.`);if(e.feedback!==void 0)throw new Error(`Graph node '${this.id}' can only use withToolFeedback() from a tool handler.`);if(e.messages&&this.graph.appendHistory(this.historySpace(),e.messages),e.kind==="go"||e.kind==="directTo"){if(!e.target)throw new Error(`Graph node '${this.id}' selected ${e.kind}() without a target.`);const t=f(e.target,"graph node"),o=this.graph.historySpace(t);if(e.state&&this.graph.saveNodeState(e.target,e.state),e.message&&this.graph.appendHistory(o,[e.message]),e.kind==="directTo"){const r=y(this.id,e);return this.graph.appendHistory(o,[new p(r)]),new c({update:{currentNode:t,response:r,inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:u})}return new c({update:{currentNode:t,response:"",inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:t})}if(e.message)throw new Error(`Graph node '${this.id}' can only use withMessage() with go() or directTo().`);if(e.kind==="direct"){const t=y(this.id,e);return this.graph.appendHistory(this.historySpace(),[new p(t)]),new c({update:{currentNode:this.id,response:t,inputConsumed:!0,completed:!1,...e.usage===void 0?{}:{tokens:e.usage}},goto:u})}if(e.kind==="finish"){const t=y(this.id,e);return this.graph.appendHistory(this.historySpace(),[new p(t)]),new c({update:{...this.graph.complete(t),...e.usage===void 0?{}:{tokens:e.usage}},goto:u})}throw new Error(`Graph node '${this.id}' returned an unsupported response kind '${e.kind}'.`)}state(e){return this.runtime.hasInvocation()?this.runtime.nodeState(this.id):e.nodes[this.id]??{}}getState(){return this.runtime.nodeState(this.id)}saveState(e){this.runtime.saveNode(this.id,e)}save(e){return this.runtime.saveNode(this.id,e)}remove(...e){return this.runtime.removeNode(this.id,...e)}toolHandler(e){return this.toolHandlers().find(t=>t.toolName===e)}async resolveJsonResponse(e,t){if(!this.runtime.expectsJsonResponse()||t.completed!==!0)return t;try{return S(t.response??""),t}catch(o){const r=await this.onInvalidJsonResponse({state:e,update:t,response:t.response??"",error:o instanceof Error?o:new Error(String(o))});return(r.completed===!0||r.response)&&S(r.response??""),r}}toolHandlers(){let e=Object.getPrototypeOf(this);const t=[];for(;e&&e!==C.prototype;){const r=Reflect.getOwnMetadata(g,e)??[];t.push(...r),e=Object.getPrototypeOf(e)}const o=new Set;for(const r of t){if(o.has(r.toolName))throw new Error(`Graph node '${this.id}' has more than one handler for tool '${r.toolName}'.`);o.add(r.toolName)}return t}}function V(n,e){return n.model===e.model&&JSON.stringify(m.parameters(n))===JSON.stringify(m.parameters(e))}i(V,"sameLlmConfig");class le extends T{static{i(this,"GraphNodeRuntime")}defaultLlmConfig;historySpaces;responseMode;maxAgentRounds;conversationPolicy;decisionOptions;decisionErrorHandler;llmLifecycle;tools=new Map;constructor(e,t,o={},r="chat",d=L,s=H,a={},h,l){super(e),this.defaultLlmConfig=t,this.historySpaces=o,this.responseMode=r,this.maxAgentRounds=d,this.conversationPolicy=s,this.decisionOptions=a,this.decisionErrorHandler=h,this.llmLifecycle=l}llmCallOptions(){const{llmTimeoutMs:e}=this.conversationPolicy,t=A();return{...e===void 0?{}:{timeoutMs:e},...t===void 0?{}:{signal:t}}}expectsJsonResponse(){return this.responseMode==="json"}historySpace(e){return e?this.historySpaces[e]??"default":"default"}resolveLlmConfig(e={}){return m.resolveConfig(this.defaultLlmConfig,e)}resolveDecisionOptions(e={}){return F(this.decisionOptions,e)}decisionProviderResolver;attachDecisionProviderResolver(e){this.decisionProviderResolver=e}resolveDecisionProvider(e){if(!this.decisionProviderResolver)throw new q(`Decision provider '${e}' cannot be resolved before the graph is attached to an engine.`);return this.decisionProviderResolver(e)}async handleDecisionError(e){return await this.decisionErrorHandler?.(e)??null}registerTools(e,t){for(const o of t){const r=this.tools.get(o.name);if(r)throw new Error(`Tool '${o.name}' is defined by both '${r.owner}' and '${e}'.`);this.tools.set(o.name,{definition:o,owner:e})}}requireTool(e){const t=this.tools.get(e);if(!t)throw new Error(`Tool '${e}' is not defined in this graph.`);return t.definition}input(e){return this.latestInput({messages:e.histories[this.historySpace(e.currentNode)]??[]})}getConversation(e){const o=(this.hasInvocation()?this.invocationHistory(e):[]).filter(r=>R.isInstance(r)&&r.additional_kwargs?.ezgraphInternal!==!0).map(r=>typeof r.content=="string"?r.content:JSON.stringify(r.content));return{request:o.at(-1)??"",priorRequests:o.slice(-5,-1)}}respond(e){return this.responseUpdate(e)}complete(e){return this.endUpdate(e)}withInvocation(e,t,o){return J(this,e,t,o)}nodeState(e){return _(this,e)}hasInvocation(){return M(this)}graphState(){return I(this)}appendHistory(e,t){U(this,e,t)}invocationHistory(e){return P(this,e)}stagedUpdate(){return D(this)}stageNodeEntries(e){for(const[t,o]of Object.entries(e??{}))!o||typeof o!="object"||Array.isArray(o)||j(this,t,o)}saveNode(e,t){return x(this,e,t),{nodes:{[e]:this.nodeState(e)}}}saveNodeState(e,t){this.saveNode(f(e,"graph node"),t)}removeNode(e,...t){return this.saveNode(e,Object.fromEntries(t.map(o=>[o,void 0])))}}function W(n){if(!w(n))return n;if(Array.isArray(n.update))throw new Error("GraphNode Command updates must be state objects.");return n.update??{}}i(W,"commandUpdate");function y(n,e){if(!e.response?.trim())throw new Error(`Graph node '${n}' selected ${e.kind}() without a response.`);return e.response}i(y,"requireNodeResponse");function X(n){if(typeof n!="string")return{ok:!0,value:n};try{return{ok:!0,value:JSON.parse(n)}}catch(e){return{ok:!1,error:`Tool arguments were not valid JSON: ${e instanceof Error?e.message:String(e)}`}}}i(X,"coerceToolArgs");function Y(n){return n.issues.map(e=>e.path.length>0?`${e.path.join(".")}: ${e.message}`:e.message).join("; ")}i(Y,"formatToolArgumentError");export{z as GRAPH_NODE_CLASS,fe as GRAPH_NODE_LOCAL_STATE,C as GraphNode,le as GraphNodeRuntime,ce as Tool};
|
|
@@ -26,7 +26,6 @@ export type GraphDefinition<NodeId extends string = string, State extends GraphS
|
|
|
26
26
|
requiresUserMessage?: boolean;
|
|
27
27
|
responseMode?: "chat" | "json";
|
|
28
28
|
historySpaces?: readonly HistorySpace[];
|
|
29
|
-
initialHistorySpace?: string;
|
|
30
29
|
maxAgentRounds?: number;
|
|
31
30
|
llmTimeoutMs?: number;
|
|
32
31
|
emptyHistorySeed?: string | null;
|
|
@@ -69,6 +68,7 @@ export declare abstract class BaseGraph<State extends GraphState> {
|
|
|
69
68
|
}): Promise<AsyncIterable<State>>;
|
|
70
69
|
};
|
|
71
70
|
prepareInput(state: State | undefined, message: HumanMessage): Partial<State>;
|
|
71
|
+
private initialNodeId;
|
|
72
72
|
saveNodeState<NodeClass extends GraphNodeTarget>(NodeClass: NodeClass, patch: Partial<GraphNodeLocalState<NodeClass>>): void;
|
|
73
73
|
restoreSessionDoc(sessionDoc: SessionDocument<State>): Promise<SessionDocument<State> | null>;
|
|
74
74
|
protected onRestoreSessionDoc(sessionDoc: SessionDocument<State>): Promise<SessionDocument<State> | null>;
|
|
@@ -78,7 +78,6 @@ export declare abstract class GraphNode<State extends GraphState, LocalState ext
|
|
|
78
78
|
export declare class GraphNodeRuntime<State extends GraphState> extends GraphStateSupport<State["currentNode"], State["nodes"]> {
|
|
79
79
|
private readonly defaultLlmConfig;
|
|
80
80
|
private readonly historySpaces;
|
|
81
|
-
private readonly initialHistorySpace;
|
|
82
81
|
private readonly responseMode;
|
|
83
82
|
readonly maxAgentRounds: number;
|
|
84
83
|
readonly conversationPolicy: ConversationPolicy;
|
|
@@ -86,7 +85,7 @@ export declare class GraphNodeRuntime<State extends GraphState> extends GraphSta
|
|
|
86
85
|
private readonly decisionErrorHandler?;
|
|
87
86
|
readonly llmLifecycle?: GraphLlmLifecycle | undefined;
|
|
88
87
|
private readonly tools;
|
|
89
|
-
constructor(endNode: State["currentNode"], defaultLlmConfig: GraphLlmConfig, historySpaces?: Readonly<Record<string, string>>,
|
|
88
|
+
constructor(endNode: State["currentNode"], defaultLlmConfig: GraphLlmConfig, historySpaces?: Readonly<Record<string, string>>, responseMode?: "chat" | "json", maxAgentRounds?: number, conversationPolicy?: ConversationPolicy, decisionOptions?: DecisionOptions, decisionErrorHandler?: ((context: DecisionErrorContext<State>) => GraphNodeResponse<State> | null | Promise<GraphNodeResponse<State> | null>) | undefined, llmLifecycle?: GraphLlmLifecycle | undefined);
|
|
90
89
|
llmCallOptions(): LlmCallOptions;
|
|
91
90
|
expectsJsonResponse(): boolean;
|
|
92
91
|
historySpace(currentNode?: string): string;
|