Skip to content
English

AgentCoreEngine ​

CORE · class · 运行时值

Bounded execution shared by applications; business rules are registered by each host.

Configuration is bound before a run and may be bound only once per model, tool runtime and workflow. A run resolves its signal from the engine, the request runtime and the caller, then executes either the bound workflow or a supplied step function until the round budget, cancellation or a completion stops it.

导入 ​

ts
import { AgentCoreEngine } from '@jangts/agent-core/engine';
js
import { AgentCoreEngine } from '@jangts/agent-core/engine';

其他公开入口:@jangts/agent-core、@jangts/agent-core/engine、@jangts/agent-core/types。

定义 ​

ts
class AgentCoreEngine<Result, State, App>

泛型参数 ​

类型参数约束默认类型
Result——
State—unknown
App—undefined

构造函数 ​

ts
new AgentCoreEngine<Result, State = unknown, App = undefined>(settings?: AgentCoreEngineSetup<State, Result, App>): AgentCoreEngine<Result, State, App>

Build an engine and validate its wiring.

Legacy top-level names (maxSteps, exhausted, signal, diagnostics, onWorkflowEvent, observe) are rejected rather than ignored, because silently dropping them would change budgets or observation.

参数类型传递说明
settingsAgentCoreEngineSetup<State, Result, App>可省略—

参数 settings的可选结构: 选择其中一种结构,各分支的字段要求分别列出。

分支 1
字段类型必需说明
cacheEngineCacheOptions | undefined可省略Engine-local LRU bounds; not copied as cache data when forking.
agentCacheAgentCachePort | undefined可省略Borrowed App service cache; forks must explicitly provide their own port.
maxRoundsnumber | undefined可省略Round budget; must be a positive safe integer. Defaults to 8 rounds.
executionExecutionOptions | undefined可省略Cancellation and diagnostics shared by every round.
errors{ exhausted?: () => Error; } | undefined可省略Builds the error thrown when the round budget is exhausted (defaults to a BudgetError).
branchAgentBranch | undefined可省略只读。见类型定义及调用场景。
toolsToolBinding | undefined可省略只读。见类型定义及调用场景。
modelAgentModelBinding | undefined可省略见类型定义及调用场景。
modelsundefined可省略见类型定义及调用场景。
workflowundefined可省略见类型定义及调用场景。
appundefined可省略见类型定义及调用场景。
分支 2
字段类型必需说明
cacheEngineCacheOptions | undefined可省略Engine-local LRU bounds; not copied as cache data when forking.
agentCacheAgentCachePort | undefined可省略Borrowed App service cache; forks must explicitly provide their own port.
maxRoundsnumber | undefined可省略Round budget; must be a positive safe integer. Defaults to 8 rounds.
executionExecutionOptions | undefined可省略Cancellation and diagnostics shared by every round.
errors{ exhausted?: () => Error; } | undefined可省略Builds the error thrown when the round budget is exhausted (defaults to a BudgetError).
branchAgentBranch | undefined可省略只读。见类型定义及调用场景。
toolsToolBinding | undefined可省略只读。见类型定义及调用场景。
modelstring | undefined可省略见类型定义及调用场景。
modelsReadonly<Record<string, AgentModelBinding>>必需见类型定义及调用场景。
maxModelCallsnumber | undefined可省略见类型定义及调用场景。
workflowundefined可省略见类型定义及调用场景。
appundefined可省略见类型定义及调用场景。
分支 3
字段类型必需说明
cacheEngineCacheOptions | undefined可省略Engine-local LRU bounds; not copied as cache data when forking.
agentCacheAgentCachePort | undefined可省略Borrowed App service cache; forks must explicitly provide their own port.
maxRoundsnumber | undefined可省略Round budget; must be a positive safe integer. Defaults to 8 rounds.
executionExecutionOptions | undefined可省略Cancellation and diagnostics shared by every round.
errors{ exhausted?: () => Error; } | undefined可省略Builds the error thrown when the round budget is exhausted (defaults to a BudgetError).
branchAgentBranch | undefined可省略只读。见类型定义及调用场景。
toolsToolBinding | undefined可省略只读。见类型定义及调用场景。
modelAgentModelBinding | undefined可省略见类型定义及调用场景。
modelsundefined可省略见类型定义及调用场景。
workflowAgentWorkflow<State, Result, App>必需只读。见类型定义及调用场景。
appApp | undefined可省略只读。见类型定义及调用场景。

类型条件: AgentCoreEngineOptions & { readonly branch?: AgentBranch; readonly tools?: ToolBinding; } & { model?: AgentModelBinding; models?: never; } & { readonly workflow: AgentWorkflow<State, Result, App>; } & ([App] extends [undefined] ? { readonly app?: undefined; } : { readonly app: App; })

分支 4
字段类型必需说明
cacheEngineCacheOptions | undefined可省略Engine-local LRU bounds; not copied as cache data when forking.
agentCacheAgentCachePort | undefined可省略Borrowed App service cache; forks must explicitly provide their own port.
maxRoundsnumber | undefined可省略Round budget; must be a positive safe integer. Defaults to 8 rounds.
executionExecutionOptions | undefined可省略Cancellation and diagnostics shared by every round.
errors{ exhausted?: () => Error; } | undefined可省略Builds the error thrown when the round budget is exhausted (defaults to a BudgetError).
branchAgentBranch | undefined可省略只读。见类型定义及调用场景。
toolsToolBinding | undefined可省略只读。见类型定义及调用场景。
modelstring | undefined可省略见类型定义及调用场景。
modelsReadonly<Record<string, AgentModelBinding>>必需见类型定义及调用场景。
maxModelCallsnumber | undefined可省略见类型定义及调用场景。
workflowAgentWorkflow<State, Result, App>必需只读。见类型定义及调用场景。
appApp | undefined可省略只读。见类型定义及调用场景。

类型条件: AgentCoreEngineOptions & { readonly branch?: AgentBranch; readonly tools?: ToolBinding; } & { model?: string; models: Readonly<Record<string, AgentModelBinding>>; maxModelCalls?: number; } & { readonly workflow: AgentWorkflow<State, Result, App>; } & ([App] extends [undefined] ? { readonly app?: undefined; } : { readonly app: App; })

返回: AgentCoreEngine<Result, State, App>。

实例属性 ​

字段类型必需说明
workflowAgentWorkflow<State, Result, App>必需只读。The bound workflow.
branchAgentBranch必需只读。Identity of this engine's branch.

成员目录 ​

成员用途
Workflow静态。Workflow catalog constructor, exposed so hosts do not import two modules.
AttemptBudget静态。Attempt budget, exposed for hosts that gate their own sub-steps.
createWorkflow静态。Factory for a validated workflow definition.
bindModelBind the single model this engine will use.
bindModelRuntimeBind an existing request lifetime once, for App services sharing this Runner's budget. Callbacks are bound to the source runtime and the counters stay live getters, so the engine and the App observe exactly the same budget and signal.
switchModelSelect a configured model, or replace the single bound model's configuration.
bindToolRuntimeBind the tool runtime used by workflow context.
bindWorkflowBind a workflow, narrowing the engine's state and App types. Binding changes the engine's type parameters without changing its identity, so the same instance keeps its model, tools and branch. Bind a workflow together with its App dependencies.
checkpointTake an in-memory checkpoint of host-owned data. The data is cloned on write and on every read, so neither side can mutate the other.
exportCheckpointExport a checkpoint for host-owned persistence.
restoreCheckpointRecreate a checkpoint from a persisted record. The record's branch must match this engine's branch exactly; otherwise persisted data from another branch would be adopted silently.
forkCreate an engine on a new branch forked at a checkpoint. The forked engine keeps the round budget, observation and configuration, receives an optional workflow extension, and gets a new branch identity whose parent ids point at this engine. Live handles are not copied: an App dependency, request runtime or tool runtime must be restored by the resume callback, because they cannot be serialized.
runRun the loop with a step function when no workflow is bound. Run a bound workflow from an initial state.

成员详情 ​

Workflow ​

静态成员。

Workflow catalog constructor, exposed so hosts do not import two modules.

ts
new AgentCoreEngine.Workflow<State, Result, Runtime = undefined>(definition: AgentWorkflowDefinition<State, Result, Runtime>): AgentWorkflow<State, Result, Runtime>

Build and validate a workflow.

The entry node must start a round, because otherwise a workflow could loop forever without consuming the round budget. Renamed top-level fields are rejected as well.

参数类型传递说明
definitionAgentWorkflowDefinition<State, Result, Runtime>必需—
definition 的字段
字段类型必需说明
idstring必需只读。Stable workflow id, also reported in every event.
chainSourceWorkflowChainSource | undefined可省略只读。App-owned authorized diagnostic reader; no global run storage is installed.
revisionstring | undefined可省略只读。Definition revision; lets hosts distinguish executions of different graph versions.
nodesreadonly WorkflowNode<State, Result, Runtime>[]必需只读。见类型定义及调用场景。
isResult((result: Result) => boolean) | undefined可省略只读。Synchronous result adjudicator; returning anything other than true is a contract error.
entryNodeIdstring | undefined可省略只读。First node to enter; defaults to the first declared node, which must start a round.

返回: AgentWorkflow<State, Result, Runtime>。

AttemptBudget ​

静态成员。

Attempt budget, exposed for hosts that gate their own sub-steps.

ts
new AgentCoreEngine.AttemptBudget(limit: number): AttemptBudget
参数类型传递说明
limitnumber必需—

返回: AttemptBudget。

createWorkflow ​

静态成员。

Factory for a validated workflow definition.

ts
AgentCoreEngine.createWorkflow<State, Result, Runtime = undefined>(definition: AgentWorkflowDefinition<State, Result, Runtime>): AgentWorkflow<State, Result, Runtime>

Build a validated workflow from a definition.

类型参数约束默认类型
State——
Result——
Runtime—undefined
参数类型传递说明
definitionAgentWorkflowDefinition<State, Result, Runtime>必需—
definition 的字段
字段类型必需说明
idstring必需只读。Stable workflow id, also reported in every event.
chainSourceWorkflowChainSource | undefined可省略只读。App-owned authorized diagnostic reader; no global run storage is installed.
revisionstring | undefined可省略只读。Definition revision; lets hosts distinguish executions of different graph versions.
nodesreadonly WorkflowNode<State, Result, Runtime>[]必需只读。见类型定义及调用场景。
isResult((result: Result) => boolean) | undefined可省略只读。Synchronous result adjudicator; returning anything other than true is a contract error.
entryNodeIdstring | undefined可省略只读。First node to enter; defaults to the first declared node, which must start a round.

返回: AgentWorkflow<State, Result, Runtime>。

bindModel ​

实例方法。

Bind the single model this engine will use.

ts
bindModel(options: AgentModelBinding): AgentCoreEngine<Result, State, App>

Bind the single model this engine will use.

参数类型传递说明
optionsAgentModelBinding必需—
options 的字段
字段类型必需说明
providerChatProvider必需见类型定义及调用场景。
executionundefined可省略见类型定义及调用场景。
transportsreadonly ModelTransportDefinition<unknown>[] | undefined可省略见类型定义及调用场景。
sink{ output?: ModelRunnerPorts["onOutput"]; } | undefined可省略见类型定义及调用场景。
errors{ inputBudget?: ModelRunnerPorts["inputBudgetError"]; outputBudget?: ModelRunnerPorts["outputBudgetError"]; } | undefined可省略见类型定义及调用场景。
childrenModelChildPolicy | undefined可省略只读。见类型定义及调用场景。
maxInputCharsnumber | undefined可省略Character budget for the assembled input.
maxSchemaCharsnumber | undefined可省略Character allowance for registered capability schemas.
tokenBudgetModelTokenBudget | undefined可省略见类型定义及调用场景。
maxOutputTokensnumber | undefined可省略Default output reservation; invoke can override it for one call.
maxCallsnumber | undefined可省略Calls allowed for the whole request, including descendant runners' reservations.
callTimeoutMsnumber | undefined可省略Deadline for one provider call, in milliseconds.
maxOutputCharsnumber | undefined可省略Cap on streamed output characters; exceeding it fails the call.
usageboolean | undefined可省略Request and record provider usage for each call.
signalundefined可省略见类型定义及调用场景。

返回: AgentCoreEngine<Result, State, App>。

bindModelRuntime ​

实例方法。

Bind an existing request lifetime once, for App services sharing this Runner's budget.

Callbacks are bound to the source runtime and the counters stay live getters, so the engine and the App observe exactly the same budget and signal.

ts
bindModelRuntime(source: AgentModelRuntime): AgentCoreEngine<Result, State, App>

Bind an existing request lifetime once, for App services sharing this Runner's budget.

Callbacks are bound to the source runtime and the counters stay live getters, so the engine and the App observe exactly the same budget and signal.

参数类型传递说明
sourceAgentModelRuntime必需—
source 的字段
字段类型必需说明
invoke{ (request: string): Promise<ModelResult<string>>; <Result>(request: ModelCallRequest<never> & { readonly prepared: PreparedModelCall<Result>; }): Promise<ModelResult<Result>>; (request: ModelCallRequest<never>): Promise<ModelResult<string>>; <Result>(request: ModelCallRequest<ModelTransportDefinition<Result>> & { transport: ModelTransportDefinition<Result>; }): Promise<ModelResult<Result>>; <const Id extends string>(request: ModelCallRequest<Id> & { readonly transport: Id; }): Promise<ModelResult<RegisteredTransportOutput<readonly ModelTransportDefinition<unknown>[], Id>>>; (request: ModelCallRequest<string | ModelTransportDefinition<unknown>>): Promise<ModelResult<unknown>>; }必需Invoke one model call. Named and shorthand input share the same lifecycle: validation, measurement, budget charge, streaming, commit. A caller-supplied signal only shortens the call lifetime. Invoke a prepared call whose settings cannot be replaced. Invoke with the default transport and a plain-text result. Invoke with a transport instance supplied at the call site. Invoke with a transport id registered on this runner. Invoke without narrowing the transport type.
prepare{ (request?: import("../structs/model/runtime.js").ModelPrepareRequest<never>): import("../structs/model/runtime.js").PreparedModelCall<string>; <Result>(request: ModelPrepareRequest<ModelTransportDefinition<Result>> & { readonly transport: ModelTransportDefinition<Result>; }): PreparedModelCall<Result>; <const Id extends string>(request: ModelPrepareRequest<Id> & { readonly transport: Id; }): PreparedModelCall<RegisteredTransportOutput<readonly ModelTransportDefinition<unknown>[], Id>>; (request: import("../structs/model/runtime.js").ModelPrepareRequest<string | ModelTransportDefinition>): import("../structs/model/runtime.js").PreparedModelCall; }必需Prepare a call and measure it before invocation. A prepared call is single-use and bound to the stage, output tokens and transport it was measured with; invoke rejects any attempt to replace those settings. Prepare a call for a transport instance supplied at the call site. Prepare a call for a transport id, typed by the runner's registered transports. Prepare a call without narrowing the transport type.
executionExecutionContext必需只读。见类型定义及调用场景。
remainingCallsnumber必需只读。Calls still available to this runner after the parent's reserve is applied.
callCountnumber必需只读。Completed calls observed by this runner only.
totalCallCountnumber必需只读。Includes descendant attempts; local callCount and journal remain isolated.

返回: AgentCoreEngine<Result, State, App>。

switchModel ​

实例方法。

Select a configured model, or replace the single bound model's configuration.

ts
switchModel(options: AgentModelBinding | string): AgentCoreEngine<Result, State, App>

Select a configured model, or replace the single bound model's configuration.

参数类型传递说明
optionsstring | AgentModelBinding必需—

参数 options的可选结构: 选择其中一种结构,各分支的字段要求分别列出。

分支 1

string

分支 2
字段类型必需说明
providerChatProvider必需见类型定义及调用场景。
executionundefined可省略见类型定义及调用场景。
transportsreadonly ModelTransportDefinition<unknown>[] | undefined可省略见类型定义及调用场景。
sink{ output?: ModelRunnerPorts["onOutput"]; } | undefined可省略见类型定义及调用场景。
errors{ inputBudget?: ModelRunnerPorts["inputBudgetError"]; outputBudget?: ModelRunnerPorts["outputBudgetError"]; } | undefined可省略见类型定义及调用场景。
childrenModelChildPolicy | undefined可省略只读。见类型定义及调用场景。
maxInputCharsnumber | undefined可省略Character budget for the assembled input.
maxSchemaCharsnumber | undefined可省略Character allowance for registered capability schemas.
tokenBudgetModelTokenBudget | undefined可省略见类型定义及调用场景。
maxOutputTokensnumber | undefined可省略Default output reservation; invoke can override it for one call.
maxCallsnumber | undefined可省略Calls allowed for the whole request, including descendant runners' reservations.
callTimeoutMsnumber | undefined可省略Deadline for one provider call, in milliseconds.
maxOutputCharsnumber | undefined可省略Cap on streamed output characters; exceeding it fails the call.
usageboolean | undefined可省略Request and record provider usage for each call.
signalundefined可省略见类型定义及调用场景。

返回: AgentCoreEngine<Result, State, App>。

bindToolRuntime ​

实例方法。

Bind the tool runtime used by workflow context.

ts
bindToolRuntime(tools: ToolBinding): AgentCoreEngine<Result, State, App>

Bind the tool runtime used by workflow context.

参数类型传递说明
toolsToolBinding必需—

参数 tools的可选结构: 选择其中一种结构,各分支的字段要求分别列出。

分支 1
字段类型必需说明
invokeInvokeTool必需见类型定义及调用场景。
分支 2
字段类型必需说明
invokeAsync(request: ToolInvocationRequest) => Promise<ToolResult<unknown>>必需Invoke a registered tool and await its result.

返回: AgentCoreEngine<Result, State, App>。

bindWorkflow ​

实例方法。

Bind a workflow, narrowing the engine's state and App types.

Binding changes the engine's type parameters without changing its identity, so the same instance keeps its model, tools and branch. Bind a workflow together with its App dependencies.

ts
bindWorkflow<NextState>(workflow: AgentWorkflow<NextState, Result, undefined>): AgentCoreEngine<Result, NextState, undefined>

Bind a workflow, narrowing the engine's state and App types.

Binding changes the engine's type parameters without changing its identity, so the same instance keeps its model, tools and branch.

类型参数约束默认类型
NextState——
参数类型传递说明
workflowAgentWorkflow<NextState, Result, undefined>必需—

返回: AgentCoreEngine<Result, NextState, undefined>。

ts
bindWorkflow<NextState, NextApp>(workflow: AgentWorkflow<NextState, Result, NextApp>, app: NextApp): AgentCoreEngine<Result, NextState, NextApp>

Bind a workflow together with its App dependencies.

类型参数约束默认类型
NextState——
NextApp——
参数类型传递说明
workflowAgentWorkflow<NextState, Result, NextApp>必需—
appNextApp必需—

返回: AgentCoreEngine<Result, NextState, NextApp>。

checkpoint ​

实例方法。

Take an in-memory checkpoint of host-owned data.

The data is cloned on write and on every read, so neither side can mutate the other.

ts
checkpoint<Data>(data: Data): AgentCheckpoint<Data>

Take an in-memory checkpoint of host-owned data.

The data is cloned on write and on every read, so neither side can mutate the other.

类型参数约束默认类型
Data——
参数类型传递说明
dataData必需—

返回: AgentCheckpoint<Data>。

返回值结构
字段类型必需说明
idstring必需只读。Checkpoint identifier, unique within the engine.
sourceAgentBranch必需只读。Branch the checkpoint was taken on.
read() => Data必需见类型定义及调用场景。

exportCheckpoint ​

实例方法。

Export a checkpoint for host-owned persistence.

ts
exportCheckpoint<Data>(checkpoint: AgentCheckpoint<Data>): AgentCheckpointRecord<Data>

Export a checkpoint for host-owned persistence.

类型参数约束默认类型
Data——
参数类型传递说明
checkpointAgentCheckpoint<Data>必需—
checkpoint 的字段
字段类型必需说明
idstring必需只读。Checkpoint identifier, unique within the engine.
sourceAgentBranch必需只读。Branch the checkpoint was taken on.
read() => Data必需见类型定义及调用场景。

返回: AgentCheckpointRecord<Data>。

返回值结构
字段类型必需说明
idstring必需只读。Checkpoint identifier, preserved across export and restore.
sourceAgentBranch必需只读。Validated branch identity captured at checkpoint time.
dataData必需只读。Detached data payload; serializable by the host.

restoreCheckpoint ​

实例方法。

Recreate a checkpoint from a persisted record.

The record's branch must match this engine's branch exactly; otherwise persisted data from another branch would be adopted silently.

ts
restoreCheckpoint<Data>(record: AgentCheckpointRecord<Data>): AgentCheckpoint<Data>

Recreate a checkpoint from a persisted record.

The record's branch must match this engine's branch exactly; otherwise persisted data from another branch would be adopted silently.

类型参数约束默认类型
Data——
参数类型传递说明
recordAgentCheckpointRecord<Data>必需—
record 的字段
字段类型必需说明
idstring必需只读。Checkpoint identifier, preserved across export and restore.
sourceAgentBranch必需只读。Validated branch identity captured at checkpoint time.
dataData必需只读。Detached data payload; serializable by the host.

返回: AgentCheckpoint<Data>。

返回值结构
字段类型必需说明
idstring必需只读。Checkpoint identifier, unique within the engine.
sourceAgentBranch必需只读。Branch the checkpoint was taken on.
read() => Data必需见类型定义及调用场景。

fork ​

实例方法。

Create an engine on a new branch forked at a checkpoint.

The forked engine keeps the round budget, observation and configuration, receives an optional workflow extension, and gets a new branch identity whose parent ids point at this engine. Live handles are not copied: an App dependency, request runtime or tool runtime must be restored by the resume callback, because they cannot be serialized.

ts
fork<Data>({ at, workflow, routes, resume, }: { at: AgentCheckpoint<Data>; workflow?: AgentWorkflow<State, Result, App> | WorkflowExtension<State, Result, App>; routes?: WorkflowExtension<State, Result, App>["routes"]; resume?: (checkpoint: Data) => { app?: App; tools?: ToolBinding; model?: AgentModelRuntime; agentCache?: AgentCachePort; }; }): AgentCoreEngine<Result, State, App>

Create an engine on a new branch forked at a checkpoint.

The forked engine keeps the round budget, observation and configuration, receives an optional workflow extension, and gets a new branch identity whose parent ids point at this engine. Live handles are not copied: an App dependency, request runtime or tool runtime must be restored by the resume callback, because they cannot be serialized.

类型参数约束默认类型
Data——
参数类型传递说明
__0{ at: AgentCheckpoint<Data>; workflow?: AgentWorkflow<State, Result, App> | WorkflowExtension<State, Result, App>; routes?: WorkflowExtension<State, Result, App>["routes"]; resume?: (checkpoint: Data) => { app?: App; tools?: ToolBinding; model?: AgentModelRuntime; agentCache?: AgentCachePort; }; }必需—
__0 的字段
字段类型必需说明
atAgentCheckpoint<Data>必需见类型定义及调用场景。
workflowAgentWorkflow<State, Result, App> | WorkflowExtension<State, Result, App> | undefined可省略见类型定义及调用场景。
routesReadonly<Record<string, readonly WorkflowRoute<State, Result, App>[]>> | undefined可省略见类型定义及调用场景。
resume((checkpoint: Data) => { app?: App; tools?: ToolBinding; model?: AgentModelRuntime; agentCache?: AgentCachePort; }) | undefined可省略见类型定义及调用场景。

返回: AgentCoreEngine<Result, State, App>。

run ​

实例方法。

Run the loop with a step function when no workflow is bound. Run a bound workflow from an initial state.

ts
run(step: CoreStep<Result>, options?: { signal?: AbortSignal; modelId?: never; }): Promise<Result>

Run the loop with a step function when no workflow is bound.

参数类型传递说明
stepCoreStep<Result>必需—
options{ signal?: AbortSignal; modelId?: never; } | undefined可省略—

参数 options的可选结构: 选择其中一种结构,各分支的字段要求分别列出。

分支 1

undefined

分支 2
字段类型必需说明
signalAbortSignal | undefined可省略见类型定义及调用场景。
modelIdundefined可省略见类型定义及调用场景。

返回: Promise<Result>。

等待后的值: Awaited<Result>。

ts
run(state: State, options?: { signal?: AbortSignal; modelId?: string; }): Promise<Result>

Run a bound workflow from an initial state.

参数类型传递说明
stateState必需—
options{ signal?: AbortSignal; modelId?: string; } | undefined可省略—

参数 options的可选结构: 选择其中一种结构,各分支的字段要求分别列出。

分支 1

undefined

分支 2
字段类型必需说明
signalAbortSignal | undefined可省略见类型定义及调用场景。
modelIdstring | undefined可省略见类型定义及调用场景。

返回: Promise<Result>。

等待后的值: Awaited<Result>。

使用示例 ​

一个普通步骤即可运行 ​

入门 · Node.js

ts
import { AgentCoreEngine } from '@jangts/agent-core/engine';

const agent = new AgentCoreEngine<string>();
const answer = await agent.run(() => ({ type: 'complete', value: '你好,Core' }));
console.log(answer);
js
import { AgentCoreEngine } from '@jangts/agent-core/engine';
const agent = new AgentCoreEngine();
const answer = await agent.run(() => ({ type: 'complete', value: '你好,Core' }));
console.log(answer);

增加显式 Workflow,仍然调用 run ​

配置 · Node.js

ts
import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';

type State = { name: string; answer?: string };
const workflow = defineWorkflow<State, string>({
  id: 'greeting',
  nodes: [{
    id: 'greet', description: '根据本次姓名生成问候', startsRound: true,
    run: state => ({ answer: '你好,' + state.name }),
    routes: [route.deliver('answer')],
  }],
});

const agent = new AgentCoreEngine({ workflow });
console.log(await agent.run({ name: 'Ivan' }));
console.log(await agent.run({ name: '访客' }));
js
import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';
const workflow = defineWorkflow({
    id: 'greeting',
    nodes: [{
            id: 'greet', description: '根据本次姓名生成问候', startsRound: true,
            run: state => ({ answer: '你好,' + state.name }),
            routes: [route.deliver('answer')],
        }],
});
const agent = new AgentCoreEngine({ workflow });
console.log(await agent.run({ name: 'Ivan' }));
console.log(await agent.run({ name: '访客' }));

依赖稍后就绪时绑定一次 ​

扩展 · Node.js

没有重新传 Workflow。传入的信号与实例信号合并;取消不会让迟到结果成为成功提交。

ts
import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';

type State = { name: string; answer?: string };
const workflow = defineWorkflow<State, string>({
  id: 'greeting',
  nodes: [{
    id: 'greet', description: '根据本次姓名生成问候', startsRound: true,
    run: state => ({ answer: '你好,' + state.name }),
    routes: [route.deliver('answer')],
  }],
});

const agent = new AgentCoreEngine<string>({ maxRounds: 2 }).bindWorkflow(workflow);
const controller = new AbortController();
console.log(await agent.run({ name: 'Ivan' }, { signal: controller.signal }));
js
import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core/engine';
const workflow = defineWorkflow({
    id: 'greeting',
    nodes: [{
            id: 'greet', description: '根据本次姓名生成问候', startsRound: true,
            run: state => ({ answer: '你好,' + state.name }),
            routes: [route.deliver('answer')],
        }],
});
const agent = new AgentCoreEngine({ maxRounds: 2 }).bindWorkflow(workflow);
const controller = new AbortController();
console.log(await agent.run({ name: 'Ivan' }, { signal: controller.signal }));

相关策略源码 ​

相关定义 ​

接口参考、使用示例与开发指南。