@cogitator-ai/ 类型
用于 Cogitator AI 代理运行时间的共享类型脚本 .
安装
pnpm add @cogitator-ai/types
只类型, 加上一些运行时值( Q)CogitatorError, (中文(简体) ), ErrorCode, (中文(简体) ), DEFAULT_* (原始内容存档于2017-10-21). contigs. zod 是一个依赖性,因为工具参数和结构化输出计划是Zod类型. 大多数应用程序从 @cogitator-ai/core; 直接安装此软件包以实施适配器或存储而无需运行时间.
网站参考: 类型 API。 。 。 .
快速启动
import type {
Agent,
AgentConfig,
Tool,
ToolConfig,
Message,
RunResult,
CogitatorConfig,
} from '@cogitator-ai/types';
类型
| 类别 | 说明 |
|---|---|
| 消息 | 聊天信息、工具呼叫、工具结果 |
| 工具 | 带有 Zod 方案的工具定义 |
| 探员 | 代理配置和接口 |
| LLM 语言 | LLM 后端和提供者类型 |
| 运行时间 | 协作配置、 运行选项、 结果 |
| 错误 | 结构化错误处理 |
| 反思 | 自分析剂类型 |
| 理由 | 思维之树推理 |
| 学习 | DSPy 风格优化 |
| 时间 旅行 | 执行调试 |
| 知识图 | 实体关系记忆 |
| 快速优化 | A/B 测试、监测、回滚 |
| 其他模块 | 工作流量,群,安全,RAG,语音.. |
信件类型
LLM对话的类型和工具交互.
import type {
Message,
MessageRole,
ToolCall,
ToolResult,
ToolCallMessage,
ToolResultMessage,
} from '@cogitator-ai/types';
// Basic message
const userMessage: Message = {
role: 'user',
content: 'What is 2 + 2?',
};
// Assistant message with tool calls
const assistantMessage: ToolCallMessage = {
role: 'assistant',
content: '',
toolCalls: [
{
id: 'call_123',
name: 'calculator',
arguments: { expression: '2 + 2' },
},
],
};
// Tool result message
const toolResult: ToolResultMessage = {
role: 'tool',
content: '4',
toolCallId: 'call_123',
name: 'calculator',
};
信件接口
| 类型 | 说明 |
|---|---|
MessageRole | 'system' | 'user' | 'assistant' | 'tool' |
Message | 带有角色、内容、可选名称/工具CallId的基础消息 |
MessageContent | string 或者说 ContentPart[] (案文, image_url, (中文(简体) ), image_base64(中文(简体) ) |
ToolCallMessage | 包含工具呼叫的助理信息 |
ToolResultMessage | 工具执行结果 |
ToolCall | 使用 id 、 名称、 参数、 思想、 签名、 重放的工具引用 |
ToolResult | 有 callId、 名称、 结果、 错误的工具执行结果 |
工具类型
用Zod schemas定义代理工具的类型.
import type { ToolConfig } from '@cogitator-ai/types';
import { z } from 'zod';
// Tool configuration
const calculatorConfig: ToolConfig<{ expression: string }, number> = {
name: 'calculator',
description: 'Evaluate mathematical expressions',
category: 'math',
parameters: z.object({
expression: z.string().describe('Math expression to evaluate'),
}),
execute: async (params, context) => {
console.log(`Run ${context.runId} executing calculator`);
return Number(params.expression);
},
timeout: 5000,
sideEffects: [],
};
// Tool context available during execution
interface BaseToolContext<TDeps = unknown> {
agentId: string;
runId: string;
signal: AbortSignal; // aborted on run cancel or tool timeout
toolCallId?: string;
threadId?: string;
userId?: string;
channelType?: string;
channelId?: string;
deps?: TDeps; // RunOptions.deps, never sent to the model
update?: (progress: ToolProgress) => void; // what the tool has so far, never sent to the model
}
// ToolContext<AppDeps> has deps present and typed
type ToolContext<TDeps = unknown> = unknown extends TDeps
? BaseToolContext
: BaseToolContext<TDeps> & { deps: TDeps };
工具接口
| 类型 | 说明 |
|---|---|
ToolConfig<TParams, TResult> | 带有执行函数的工具定义 |
Tool<TParams, TResult> | 全用 JSON () 方法的工具 |
ToolContext | 执行上下文有代理 Id、 runId、 信号、 线程 Id、 用户 Id、 频道和运行 deps |
SideEffectType | 'filesystem' | 'network' | 'database' | 'process' | 'external' |
ApprovalCheck | (params) => boolean 形式 requiresApproval |
ToolSchema | JSON Schema LLM 代表 |
ToolCategory | 'math' | 'text' | 'file' | 'network' | 'system' | 'utility' | 'web' | 'database' | 'communication' | 'development' |
ToolContentResult | 由部件制成的结果,使用 toolContent() 联 合 国 @cogitator-ai/core |
ToolContentPart | ToolTextPart | ToolImagePart | ToolFilePart | ToolJsonPart | ToolResourcePart |
ToolOutputResult | 由阅读器拆分的结果 toolOutput()数字 : content 为模型, details 财务报告和审定财务报表 presentation 申请 |
ToolPresentation | 客户端如何显示一个呼叫 : label, (中文(简体) ), icon?, (中文(简体) ), detail? |
ToolProgress, (中文(简体) ), ToolUpdate | 什麽 context.update() 报告,以及 onToolUpdate 获取( 与 callId 财务报告和审定财务报表 name(中文(简体) ) |
ToolInputStart, (中文(简体) ), ToolInputDelta, (中文(简体) ), ToolInputAvailable, (中文(简体) ), ToolInputAbandoned | 一个工具调用如模型所写, 或者一个不会运行, 在流流运行中 |
ToolInputStreamPart | A 类 start, (中文(简体) ), delta 或者说 end 部分内容 ChatStreamChunk.delta.toolInput后端 |
RunTimeouts | totalMs, (中文(简体) ), stepMs, (中文(简体) ), chunkMs, (中文(简体) ), toolMs 联 合 国 RunOptions.timeouts 财务报告和审定财务报表 AgentConfig.timeouts |
工具选项
import type { ToolConfig } from '@cogitator-ai/types';
import { z } from 'zod';
const advancedTool: ToolConfig<{ path: string; content: string }, void> = {
name: 'file_write',
description: 'Write content to a file',
parameters: z.object({
path: z.string(),
content: z.string(),
}),
execute: async ({ path, content }) => {
console.log(`Writing ${content.length} chars to ${path}`);
},
// Optional configuration
category: 'file',
tags: ['io', 'filesystem'],
sideEffects: ['filesystem'],
requiresApproval: true, // or (params) => params.path.includes('/etc')
timeout: 10000,
sandbox: { type: 'docker', image: 'node:20' },
maxResultLength: 20_000, // characters of the result the model reads
isConcurrencySafe: false, // or (params) => boolean, default: annotations.readOnlyHint
lockKeys: ({ path }) => [`file:${path}`], // calls whose keys meet never run at the same time
presentation: ({ path }) => ({ label: 'Write file', icon: 'file-plus', detail: path }),
};
providerTypes (单位:千美元)ProviderToolTypes)在提供者自己的目录中命名工具的类型,将其发送给提供者而不是计划,例如 { anthropic: 'memory_20250818' } 克劳德从训练中知道一个工具, 而其他的提供者都得到这个计划. ToolSchema 带着它.
读取工具结果
少数无依赖的帮助者读取工具的结果与运行的方式相同,所以不依赖的软件包 @cogitator-ai/core (语音会话,适配器)同样对待. @cogitator-ai/core 再出口它们.
| 函数 | 说明 |
|---|---|
isToolContentResult(value) | 结果是否是 ToolContentResult |
isToolOutputResult(value) | 结果是否是 ToolOutputResult |
toolOutputContent(value) | 模型读到的结果是: content 页:1 toolOutput() 结果,否则结果 |
toolResultParts(value) | 与媒体有关的部分(a) toolContent() 结果或具有基数的物体64 image(中文(简体) ) |
toolPartsToText(parts) | 描述的部件、图像、文件和二进制资源的文本, JSON 作为 JSON 文本 |
truncateToolResultText(text, max) | text 切为 max 字符, 起始和结尾保存, 并注明留下多少 |
DEFAULT_TOOL_RESULT_MAX_LENGTH | 100_000,结果的字符读取,除非另作配置 |
代理类型
代理配置的类型 .
import type { Agent, AgentConfig, ResponseFormat, Tool } from '@cogitator-ai/types';
import { z } from 'zod';
declare const calculatorTool: Tool;
declare const billingAgent: Agent;
const config: AgentConfig = {
name: 'research-agent',
model: 'openai/gpt-6.1-sol',
instructions: 'You are a research assistant...',
// Optional settings
description: 'Helps with research tasks',
tools: [calculatorTool],
temperature: 0.7,
topP: 0.9,
maxTokens: 4096,
stopSequences: ['END'],
maxIterations: 10,
timeout: 60000,
// Response format
responseFormat: { type: 'json' },
// Reasoning effort for reasoning models, in one vocabulary for every provider
reasoning: { effort: 'medium', summary: true },
// Agents this one can hand the conversation to (transfer_to_<name> tools)
handoffs: [
billingAgent,
{ agent: billingAgent, toolName: 'to_billing', description: 'Invoices' },
],
};
// Response format options
const textFormat: ResponseFormat = { type: 'text' };
const jsonFormat: ResponseFormat = { type: 'json' };
const schemaFormat: ResponseFormat = {
type: 'json_schema',
schema: z.object({ answer: z.string() }),
};
AgentConfig 还要 id, (中文(简体) ), provider (一个明确的后端名称), skills (单位:千美元)Skill 成套工具和指示)和 fallbackModels (单位:千美元)FallbackModel: 模拟一转动到何时 model 失败). AgentConfig<TDeps> 带有道克类型 拒绝其道克类型与其无关的工具,以及 RunOptions<TDeps>.deps 把他们带到工具那里去RunDeps<TDeps> 要求这样做). AgentSnapshot 编号 : SerializedAgentConfig 说明JSON的形式 agent.serialize()。 。 。 .
LLM 类型
LLM 后端和提供者的类型 .
import type {
LLMProvider,
LLMBackendProvider,
LLMConfig,
LLMBackend,
ChatRequest,
ChatResponse,
ChatStreamChunk,
ChatUsage,
OpenAIProviderConfig,
OpenAICompatibleProfile,
OpenAICompatibleServer,
ModelPriceConfig,
ReasoningConfig,
PromptCacheConfig,
} from '@cogitator-ai/types';
// Supported providers
type LLMProvider =
| 'ollama'
| 'openai'
| 'anthropic'
| 'google'
| 'azure'
| 'bedrock'
| 'vllm'
| 'mistral'
| 'groq'
| 'together'
| 'deepseek';
// What LLMBackend.provider reports: a built-in provider, or the name of your
// own backend (llm.backends) or of a registered plugin
type LLMBackendProvider = LLMProvider | (string & {});
// LLM configuration
const llmConfig: LLMConfig = {
provider: 'openai',
model: 'gpt-6.1-sol',
temperature: 0.7,
maxTokens: 4096,
};
// Chat request
const request: ChatRequest = {
model: 'gpt-6.1-sol',
messages: [{ role: 'user', content: 'Hello' }],
tools: [{ name: 'calc', description: '...', parameters: { type: 'object', properties: {} } }],
stream: true,
};
// Chat response
const response: ChatResponse = {
id: 'chatcmpl-123',
content: 'Hello! How can I help?',
finishReason: 'stop',
usage: { inputTokens: 10, outputTokens: 20, totalTokens: 30 },
};
// Token usage; cached and reasoning tokens are already included in the totals
const usage: ChatUsage = {
inputTokens: 1200,
outputTokens: 300,
totalTokens: 1500,
cachedInputTokens: 1024,
reasoningTokens: 120,
};
// OpenAI provider: Responses API for api.openai.com, Chat Completions for other base URLs
const openaiConfig: OpenAIProviderConfig = {
apiKey: process.env.OPENAI_API_KEY!,
api: 'chat-completions', // force a wire API: 'responses' | 'chat-completions'
};
// An OpenAI-compatible server: what it takes (OpenAICompatibleProfile over an OpenAICompatibleServer preset)
const lmStudio: OpenAIProviderConfig = {
apiKey: 'lm-studio',
baseUrl: 'http://localhost:1234/v1',
profile: { server: 'lmstudio', reasoningEffort: ['low', 'medium', 'high'] },
headers: { 'X-Team': 'search' }, // sent with every request
};
// A price of your own for CogitatorConfig.llm.pricing, USD per million tokens
const price: ModelPriceConfig = { input: 0.6, output: 0.6, inputCached: 0.06 };
// Reasoning effort, mapped per provider (Anthropic effort / thinking, OpenAI reasoning.effort, Gemini thinking, Ollama think)
const reasoning: ReasoningConfig = { effort: 'high', budgetTokens: 8000, summary: true };
// effort: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max'
// Prompt caching for agent runs (CogitatorConfig.llm.promptCache)
const promptCache: PromptCacheConfig = { ttl: '1h' }; // '5m' (default) | '1h'
OllamaProviderConfig, (中文(简体) ), AnthropicProviderConfig 财务报告和审定财务报表 GoogleProviderConfig 带 baseUrl 财务报告和审定财务报表 headers (谷歌声) baseUrl 包括API版本),, VLLMProviderConfig 带 profile 财务报告和审定财务报表 headers, (中文(简体) ), OpenRouterProviderConfig 带 headers,以及 BedrockProviderConfig 带 endpoint 用于 VPC 端点或代理 。 Ollama将这些带有非流式和流式聊天请求的头像发送到 /api/chat,保留 JSON 内容类型并给出 apiKey 优于自定义授权标题,不论外壳.
LLMRetryConfig (单位:千美元)maxRetries, (中文(简体) ), baseDelay, (中文(简体) ), maxDelay, (中文(简体) ), maxRetryAfter, (中文(简体) ), requestTimeout, (中文(简体) ), onRetry)类型 CogitatorConfig.llm.retry· ; ModelRoute 这是什么 cog.route() 解决模式字符串.
ToolCall.argumentsError 说为什么无法读取一个电话的参数, 例如提供商的JSON断了: 电话是空的 arguments永远不要运行,模型被告知原因.
ToolCall.replay (单位:千美元)ToolCallReplayState)载有不透明的提供者输出,在下个回合的呼叫中必须送回,例如OpenAI Response推理项目. 它具有JSON的序列性,因此它能活下来的记忆持续;没有产生它的后端忽略它.
运行时间类型
Cogitator 运行时配置和执行的类型 .
import type { CogitatorConfig, RunOptions, RunResult, Span } from '@cogitator-ai/types';
// Cogitator configuration
const config: CogitatorConfig = {
llm: {
defaultProvider: 'openai',
defaultModel: 'gpt-6.1-sol',
providers: {
openai: { apiKey: process.env.OPENAI_API_KEY! },
ollama: { baseUrl: 'http://localhost:11434' },
anthropic: { apiKey: process.env.ANTHROPIC_API_KEY! },
},
},
limits: {
maxConcurrentRuns: 10,
defaultTimeout: 30000,
maxTokensPerRun: 100000,
},
memory: { adapter: 'redis', redis: { host: 'localhost' } },
sandbox: { defaults: { type: 'docker', image: 'node:20-alpine' } },
reflection: { enabled: true, reflectAfterError: true },
security: {
promptInjection: { action: 'block' },
pii: { mode: 'mask', custom: [{ type: 'customer_id', pattern: /CUS-\d{6}/ }] },
},
prompts: { autoDeployWinner: true }, // versioned instructions and A/B tests
};
// Run options with callbacks
const runOptions: RunOptions = {
input: 'Calculate 2 + 2',
context: { plan: 'pro' },
threadId: 'thread_abc',
userId: 'user_123', // owns the thread; reaches tools as context.userId
threadAccess: 'owner', // or 'shared'
timeout: 30000,
timeouts: { stepMs: 20_000, chunkMs: 10_000, toolMs: 5_000 }, // RunTimeouts, each off unless set
stream: true,
reasoning: { effort: 'low' },
// Callbacks
onToken: (token) => process.stdout.write(token),
onToolCall: (call) => console.log('Tool called:', call.name),
onToolResult: (result) => console.log('Tool result:', result.result, result.details),
onToolUpdate: (update) => console.log('Progress:', update.callId, update.content),
onToolInputDelta: ({ toolCallId, delta }) => console.log(toolCallId, delta), // needs stream: true
onRunStart: ({ runId }) => console.log('Started:', runId),
onRunComplete: (result) => console.log('Done:', result.output),
onRunError: (error) => console.error('Error:', error),
onSpan: (span) => console.log('Span:', span.name),
onReasoning: (delta) => process.stdout.write(delta),
onHandoff: (handoff) => console.log(`${handoff.from} -> ${handoff.to}`),
onApproval: (request) => (request.toolName === 'refund' ? 'pause' : { approved: true }),
// Memory options
useMemory: true,
loadHistory: true,
saveHistory: true,
parallelToolCalls: true, // concurrency-safe calls of a step run together (default: false)
maxParallelToolCalls: 4, // default: 10
};
核准、处理和暂停
| 类型 | 说明 |
|---|---|
ToolApprovalRequest | 一个等待决定的工具呼叫: toolCallId, (中文(简体) ), toolName, (中文(简体) ), arguments, (中文(简体) ), description, (中文(简体) ), sideEffects |
ToolApprovalDecision | { approved: true } 或者说 { approved: false; reason? } |
RunCheckpoint | JSON 暂停运行的快照 传递给 cogitator.resume() |
RunCheckpointStore | save 编号 : load(threadId) 编号 : delete 用于暂停运行( e)CogitatorConfig.runCheckpoints(中文(简体) ) |
ResumeOptions | 运行选项 resume() 加号 userId, (中文(简体) ), decisions 财务报告和审定财务报表 defaultDecision |
HandoffEvent | { from, to, reason? } 每次交接时 |
PromptsConfig | versions 编号 : abTests 仓库, score, (中文(简体) ), autoDeployWinner |
RunPrompt | 指令版本或使用的 A/B 变体 |
PiiConfig | mode (单位:千美元)mask | redact | block, (中文(简体) ), detect, (中文(简体) ), custom, (中文(简体) ), onDetect |
运行中间软件
RunMiddleware 在运行的模型和工具调用上勾 middleware 联 合 国 CogitatorConfig, (中文(简体) ), AgentConfig 或者说 RunOptions (参见核心README).
| 类型 | 说明 |
|---|---|
RunMiddleware | name, (中文(简体) ), holdsStream? 和钩子 beforeRun, (中文(简体) ), beforeModel, (中文(简体) ), wrapModelCall, (中文(简体) ), afterModel, (中文(简体) ), wrapToolCall |
RunMiddlewareContext | runId, (中文(简体) ), threadId, (中文(简体) ), agentId, (中文(简体) ), agentName, (中文(简体) ), userId频道, iteration, (中文(简体) ), signal, (中文(简体) ), deps 共享 state |
RunInputEvent | 一个新的跑步 input 编辑 messages 它的第一个转会开始于 |
ModelTurnEvent | 这个 messages 财务报告和审定财务报表 model 即下一个转弯, ModelTurnUpdate 返回新内容 messages |
ModelCallRequest | 这个 ChatRequest,则 provider/model 它去,当流出,它的 ModelStreamSink |
ModelResponseEvent | 转弯 response, (中文(简体) ), ModelResponseUpdate 替换其 content 或者说 toolCalls |
ToolCallRequest | 这个 toolCall,则 tool计划分解 args 一个人是否 approved 这个 |
运行结果
import type { RunResult } from '@cogitator-ai/types';
const result: RunResult = {
output: 'The answer is 4',
structured: { answer: 4 }, // if responseFormat was json_schema
runId: 'run_123',
agentId: 'agent_456',
threadId: 'thread_789',
usage: {
inputTokens: 100,
outputTokens: 50,
totalTokens: 150,
cost: 0.0023,
duration: 1500,
},
toolCalls: [{ id: 'call_1', name: 'calculator', arguments: { expression: '2+2' } }],
messages: [],
trace: {
traceId: 'trace_abc',
spans: [],
},
status: 'completed', // 'paused' when tool calls wait for approval
};
可选字段 : structured, (中文(简体) ), modelUsed, (中文(简体) ), usage.reasoningTokens 编号 : cachedInputTokens 编号 : cacheWriteTokens, (中文(简体) ), reasoning, (中文(简体) ), prompt, (中文(简体) ), handoffs, (中文(简体) ), finalAgent, (中文(简体) ), status, (中文(简体) ), pendingApprovals, (中文(简体) ), checkpoint, (中文(简体) ), reflections, (中文(简体) ), reflectionSummary。所有字段为 readonly。 。 。 .
错误类型
结构化错误处理与打出错误代码.
import {
CogitatorError,
ErrorCode,
ERROR_STATUS_CODES,
isRetryableError,
getRetryDelay,
} from '@cogitator-ai/types';
// Create a structured error
const error = new CogitatorError({
message: 'LLM backend unavailable',
code: ErrorCode.LLM_UNAVAILABLE,
details: { provider: 'openai', endpoint: 'https://api.openai.com' },
retryable: true,
retryAfter: 5000,
});
// Check error type
if (CogitatorError.isCogitatorError(error)) {
console.log(error.code); // 'LLM_UNAVAILABLE'
console.log(error.statusCode); // 503
console.log(error.retryable); // true
}
// Wrap any error
const wrapped = CogitatorError.wrap(new Error('timeout'), ErrorCode.LLM_TIMEOUT);
// Check if retryable
if (isRetryableError(error)) {
const delay = getRetryDelay(error, 1000); // retryAfter, or the default
await new Promise((resolve) => setTimeout(resolve, delay));
}
console.log(ERROR_STATUS_CODES[ErrorCode.LLM_RATE_LIMITED]); // 429
错误代码
| 域名 | 代码 |
|---|---|
| LLM 语言 | LLM_UNAVAILABLE, (中文(简体) ), LLM_RATE_LIMITED, (中文(简体) ), LLM_QUOTA_EXCEEDED, (中文(简体) ), LLM_TIMEOUT, (中文(简体) ), LLM_INVALID_RESPONSE, (中文(简体) ), LLM_CONTEXT_LENGTH_EXCEEDED, (中文(简体) ), LLM_CONTENT_FILTERED |
| 沙盒 | SANDBOX_UNAVAILABLE, (中文(简体) ), SANDBOX_TIMEOUT, (中文(简体) ), SANDBOX_OOM, (中文(简体) ), SANDBOX_EXECUTION_FAILED, (中文(简体) ), SANDBOX_INVALID_MODULE |
| 工具 | TOOL_NOT_FOUND, (中文(简体) ), TOOL_INVALID_ARGS, (中文(简体) ), TOOL_EXECUTION_FAILED, (中文(简体) ), TOOL_TIMEOUT, (中文(简体) ), TOOL_LOCK_CYCLE |
| 内存 | MEMORY_UNAVAILABLE, (中文(简体) ), MEMORY_WRITE_FAILED, (中文(简体) ), MEMORY_READ_FAILED, (中文(简体) ), THREAD_ACCESS_DENIED |
| 探员 | AGENT_NOT_FOUND, (中文(简体) ), AGENT_ALREADY_RUNNING, (中文(简体) ), AGENT_MAX_ITERATIONS, (中文(简体) ), RUN_TOKEN_LIMIT_EXCEEDED, (中文(简体) ), RUN_NOT_PAUSED, (中文(简体) ), RUN_TIMEOUT, (中文(简体) ), RUN_STEP_TIMEOUT, (中文(简体) ), RUN_CHUNK_TIMEOUT, (中文(简体) ), BUDGET_EXCEEDED |
| 工作流程 | WORKFLOW_NOT_FOUND, (中文(简体) ), WORKFLOW_STEP_FAILED, (中文(简体) ), WORKFLOW_CYCLE_DETECTED |
| 沼泽 | SWARM_NO_WORKERS, (中文(简体) ), SWARM_CONSENSUS_FAILED |
| 警卫 | PROMPT_INJECTION_DETECTED, (中文(简体) ), PII_DETECTED, (中文(简体) ), GUARDRAIL_TRIPPED |
| 常规 | VALIDATION_ERROR, (中文(简体) ), CONFIGURATION_ERROR, (中文(简体) ), INTERNAL_ERROR, (中文(简体) ), NOT_IMPLEMENTED, (中文(简体) ), CIRCUIT_OPEN |
LLMErrorKind 说为什么一个模型提供者的呼叫失败,比代码更细: rate_limit, (中文(简体) ), quota, (中文(简体) ), authentication, (中文(简体) ), permission, (中文(简体) ), not_found, (中文(简体) ), invalid_request, (中文(简体) ), context_overflow, (中文(简体) ), content_filter, (中文(简体) ), overloaded, (中文(简体) ), server_error, (中文(简体) ), timeout, (中文(简体) ), network 或者说 invalid_response。一个 LLMError 联 合 国 @cogitator-ai/core 把它当作 kind 财务报告和审定财务报表 details.kind。 。 。 . LLM_QUOTA_EXCEEDED (HTTP 402)是信用账户或超过配额的账户,等待片刻不会升起,并且永远不会被重审.
运行时间抛出 RUN_TIMEOUT (HTTP 504),为一跑打出其超时(出道后)Run timed out after <n>ms, (中文(简体) ), RUN_STEP_TIMEOUT 财务报告和审定财务报表 RUN_CHUNK_TIMEOUT (504) 模式呼叫结束 timeouts.stepMs 或静静的溪流 timeouts.chunkMs, (中文(简体) ), BUDGET_EXCEEDED (429) 费用细目预算 LLM_CONTENT_FILTERED (400) 当护栏挡住输入或输出时(Input blocked: … 编号 : Output blocked: …) (中文(简体) ).
反射类型
自我分析剂的类型 学习他们的行为.
import type {
Reflection,
ReflectionConfig,
ReflectionAction,
Insight,
InsightStore,
ReflectionSummary,
} from '@cogitator-ai/types';
// Reflection configuration
const reflectionConfig: ReflectionConfig = {
enabled: true,
reflectAfterToolCall: true,
reflectAfterError: true,
reflectAtEnd: true,
storeInsights: true,
maxInsightsPerAgent: 100,
minConfidenceToStore: 0.7,
useSmallModelForReflection: true,
reflectionModel: 'gpt-6-luna',
};
// Insight types
type InsightType = 'pattern' | 'mistake' | 'success' | 'tip' | 'warning';
// Reflection result
const reflection: Reflection = {
id: 'ref_123',
runId: 'run_456',
agentId: 'agent_789',
timestamp: new Date(),
action: {
type: 'tool_call',
toolName: 'search',
input: { query: 'AI news' },
output: { results: [] },
duration: 500,
},
analysis: {
wasSuccessful: false,
confidence: 0.8,
reasoning: 'Search returned no results, should try broader query',
whatCouldImprove: 'Use more general search terms',
},
insights: [
{
id: 'ins_1',
type: 'tip',
content: 'Broaden search queries when results are empty',
context: 'search operations',
confidence: 0.85,
usageCount: 0,
createdAt: new Date(),
lastUsedAt: new Date(),
agentId: 'agent_789',
source: { runId: 'run_456', reflectionId: 'ref_123' },
},
],
goal: 'Find recent AI news',
iterationIndex: 2,
};
理由类型
树取(ToT)推理类型分枝探索.
import type {
ToTConfig,
ThoughtTree,
ThoughtNode,
ThoughtBranch,
ToTResult,
ExplorationStrategy,
} from '@cogitator-ai/types';
// ToT configuration
const totConfig: ToTConfig = {
branchFactor: 3, // Generate 3 candidate thoughts per step
beamWidth: 2, // Queue the best 2 candidates per expanded node
maxDepth: 5, // Max reasoning depth
explorationStrategy: 'beam', // 'beam' | 'best-first' | 'dfs'
confidenceThreshold: 0.3,
terminationConfidence: 0.8,
maxTotalNodes: 50,
maxIterationsPerBranch: 3, // Iteration cap for each branch run
// Callbacks
onBranchGenerated: (node, branches) => console.log('Generated:', branches.length),
onBranchEvaluated: (branch, score) => console.log('Score:', score.composite),
onNodeExplored: (node) => console.log('Explored:', node.id),
onBacktrack: (from, to) => console.log('Backtracking...'),
};
// Thought branch with proposed action
const branch: ThoughtBranch = {
id: 'branch_1',
parentId: 'node_0',
thought: 'I should search for the latest information first',
proposedAction: { type: 'tool_call', toolName: 'search', arguments: { query: 'AI news 2024' } },
score: { confidence: 0.8, progress: 0.3, novelty: 0.6, composite: 0.57, reasoning: '...' },
messagesSnapshot: [/* ... */],
};
beam 按级别运行树级, best-first 运行其分支得分最高的节点 dfs 先深入; 候选人 beamWidth 等待等待等待的反向跟踪选项. maxTotalNodes 盖已执行节点,以及 maxIterationsPerBranch 每个分支运行封顶( 绝不高于代理服务器自身) maxIterations) (中文(简体) ).
学习类型
DSPY-灵感代理优化类型.
import type {
ExecutionTrace,
TraceStore,
Demo,
OptimizerConfig,
OptimizationResult,
LearningConfig,
} from '@cogitator-ai/types';
// Learning configuration
const learningConfig: LearningConfig = {
enabled: true,
captureTraces: true,
traceRetention: 1000,
maxDemosPerAgent: 5,
minScoreForDemo: 0.8,
defaultMetrics: ['success', 'tool_accuracy', 'efficiency'],
customMetrics: [
{ name: 'tool_accuracy', type: 'numeric', description: 'Tools worked', weight: 0.5 },
],
};
// autoOptimize, optimizeAfterRuns and traceStore are deprecated and not read
// Optimizer configuration
const optimizerConfig: OptimizerConfig = {
type: 'full', // 'bootstrap-few-shot' | 'instruction' | 'full'
maxBootstrappedDemos: 5,
maxRounds: 3,
instructionCandidates: 3,
metricThreshold: 0.7,
teacherModel: 'gpt-6.1-sol',
};
// Execution trace
const trace: ExecutionTrace = {
id: 'trace_123',
runId: 'run_456',
agentId: 'agent_789',
threadId: 'thread_abc',
input: 'Calculate compound interest',
output: 'The compound interest is $1,628.89',
steps: [],
toolCalls: [],
reflections: [],
metrics: {
success: true,
toolAccuracy: 0.95,
efficiency: 0.8,
completeness: 1.0,
coherence: 0.9,
},
score: 0.92,
model: 'gpt-6.1-sol',
createdAt: new Date(),
duration: 1500,
usage: {
inputTokens: 100,
outputTokens: 50,
cost: 0.0023,
},
isDemo: true,
};
时间旅行类型
执行调试与检查站, 重放,和伪造.
import type {
ExecutionCheckpoint,
TimeTravelCheckpointStore,
ReplayOptions,
ReplayResult,
ForkOptions,
TraceDiff,
} from '@cogitator-ai/types';
// Checkpoint
const checkpoint: ExecutionCheckpoint = {
id: 'cp_123',
traceId: 'trace_456',
runId: 'run_789',
agentId: 'agent_abc',
stepIndex: 5,
messages: [],
toolResults: { call_1: 42, call_2: 'result' },
pendingToolCalls: [],
label: 'before-critical-decision',
createdAt: new Date(),
};
// Replay options
const replayOptions: ReplayOptions = {
fromCheckpoint: 'cp_123',
mode: 'live', // 'deterministic' | 'live'
modifiedToolResults: { web_search: { results: [] } }, // by tool name
skipTools: ['expensive_api'], // removed from the replayed agent
};
// Fork options (branch execution with modifications)
const forkOptions: ForkOptions = {
checkpointId: 'cp_123',
input: 'Try a different approach',
additionalContext: 'Focus on efficiency',
mockToolResults: { api_call: { mocked: true } },
label: 'efficiency-experiment',
};
// Compare two execution traces
const diff: TraceDiff = {
trace1Id: 'trace_a',
trace2Id: 'trace_b',
stepDiffs: [
{ index: 0, status: 'identical' },
{ index: 1, status: 'similar', differences: ['different tool args'] },
{ index: 2, status: 'different' }, // step1 / step2 hold the ExecutionSteps
],
commonSteps: 2,
divergencePoint: 2,
trace1OnlySteps: 1,
trace2OnlySteps: 0,
metricsDiff: {
success: { trace1: true, trace2: false },
score: { trace1: 0.9, trace2: 0.6, delta: -0.3 },
tokens: { trace1: 1200, trace2: 1500, delta: 300 },
duration: { trace1: 2100, trace2: 2600, delta: 500 },
},
};
内存类型
见 @cogitator-ai/纪念 用于详细的内存适配器类型.
内存文件, 记录一个代理保存在 /memories 使用内存工具,保留为版本:
| 类型 | 说明 |
|---|---|
MemoryFileVersion | 文件的一个版本 : scope, (中文(简体) ), path, (中文(简体) ), sequence (它在其路径的版本中在其范围中的位置), content (单位:千美元)null (删除), sha256, (中文(简体) ), previousId, (中文(简体) ), place, (中文(简体) ), renamedFrom, (中文(简体) ), author, (中文(简体) ), createdAt, (中文(简体) ), redacted |
MemoryFileHeadFilter | MemoryFileFilter 无 ids,以及 place (单位:千美元){ threadId, pathIds }),树枝起跑 |
MemoryFileAdapter | 版本存储 : putFileVersions (不论有无, MEMORY_FILE_CONFLICT 当一个地方被占据的时候, findFileVersions, (中文(简体) ), redactFileVersions, (中文(简体) ), deleteFileVersions选项 withdrawFileVersions (已撤回的版本, MemoryFileVersion.withdrawn,从不在前面,但保持它的位置 在历史上),可选 findFileHeads (每个范围的最新版本和路径 过滤器和分支见, MemoryFileHeadFilter) (中文(简体) ). 每个内置的内存适配器都是一个 |
MemoryFileFilter | agentId,以及 ids, (中文(简体) ), paths, (中文(简体) ), prefix, (中文(简体) ), visibleTo 财务报告和审定财务报表 scope 缩小范围 |
MemoryFileAuthor | 'model' | 'user' | 'system' |
MemoryFilesConfig | MemoryConfig.files数字 : scope (单位:千美元)user, (中文(简体) ), agent 或者说 thread, (中文(简体) ), readOnly 财务报告和审定财务报表 indexChars,一个 Cogitator 给每个代理的内存工具 |
记忆在运行之间也有作用. 它的设置和传球报告:
| 类型 | 说明 |
|---|---|
MemoryBriefConfig | MemoryConfig.brief数字 : model, (中文(简体) ), maxCards (1至4个), timeoutMs, (中文(简体) ), maxTokens 财务报告和审定财务报表 prompt 在卡片中,一个便宜的模型在转弯前写出 |
BriefCard | 一张牌: kind (单位:千美元)BriefCardKind数字 : constraint, (中文(简体) ), knowledge, (中文(简体) ), consequence 或者说 open_thread, (中文(简体) ), text, (中文(简体) ), quote 财务报告和审定财务报表 source (单位:千美元)turn:<id> 或者说 item:<id>(中文(简体) ) |
MemoryObservationsConfig | MemoryConfig.observations数字 : model, (中文(简体) ), maxEntities, (中文(简体) ), minItems 财务报告和审定财务报表 prompt 每个实体的观察内存,只显示为 contextBuilder 设定 |
MemoryConsolidationConfig | MemoryConfig.consolidation数字 : model, (中文(简体) ), everyRuns, (中文(简体) ), afterCompaction, (中文(简体) ), maxChanges, (中文(简体) ), maxSubjects, (中文(简体) ), playbook (单位:千美元)apply, (中文(简体) ), shadow 或者说 false, (中文(简体) ), showPlaybook, (中文(简体) ), prompt 财务报告和审定财务报表 afterConsolidate |
MemoryConsolidationReport | 通行证怎么变了 scope, (中文(简体) ), observations 财务报告和审定财务报表 observationsDeleted (路径), stale, (中文(简体) ), playbook (单位:千美元)path, (中文(简体) ), editCount, (中文(简体) ), lessonIds和 dedupe (单位:千美元)complete, (中文(简体) ), through,其中后传去) |
StaleMark | 标记为 stale 的通行证: itemId, (中文(简体) ), keptId (它让位给)和 reason (单位:千美元)duplicate 或者说 contradiction(中文(简体) ) |
RunMiddlewareContext.memoryAgentId 是运行的代理将内存保存在其中的id,其配置 id,否则其名称,未设定用于工具呼叫 invokeTool()。 。 。 . ContextBuildError.source 也许 observations 我也一样.
条目可以编译到位,这些条目会通过Cogitator来忘记并编辑:
| 类型 | 说明 |
|---|---|
EntryRedaction | 编辑其条目记录 metadata.redacted数字 : at 和可选 reason |
MemoryAdapter.redactEntry | 可选,在每个内置适配器中:文本、工具调用参数和工具结果 message 或者说 tool_result 条目改为 [redacted],它的工具调用会失去它们的重放状态和参数错误,一个用户信息它的发送者 name,它的位置,父母,角色和呼叫ids留下, null 对于缺失的条目,拒绝一个事件条目 |
MemoryChange | 什麽 onChange 听众听到: entry-added, (中文(简体) ), entry-deleted, (中文(简体) ), entry-redacted (单位:千美元)entryId, (中文(简体) ), threadId, (中文(简体) ), thread-cleared 财务报告和审定财务报表 thread-deleted一. 详尽无遗 switch 过它需要 entry-redacted 大小写 |
MemoryAdapter.forkThread | 还列出原产地中的分叉 metadata.memoryForks,不复制源代码已暂停运行 |
知识图类型
实体关系记忆与转录和推论.
import type {
GraphNode,
GraphEdge,
EntityType,
RelationType,
GraphAdapter,
TraversalOptions,
TraversalResult,
GraphPath,
ExtractionResult,
InferredEdge,
} from '@cogitator-ai/types';
// EntityType: 'person' | 'organization' | 'location' | 'concept' | 'event' | 'object' | 'custom'
// RelationType: 'knows' | 'works_at' | 'located_in' | 'part_of' | 'related_to' | 'created_by'
// | 'belongs_to' | 'associated_with' | 'causes' | 'precedes' | 'custom'
// Graph node
const node: GraphNode = {
id: 'node_123',
agentId: 'agent-1',
type: 'person',
name: 'Alice',
aliases: ['alice_dev'],
description: 'Software engineer',
properties: { role: 'developer', team: 'platform' },
embedding: [0.1, 0.2, 0.3],
confidence: 1.0,
source: 'extracted', // 'extracted' | 'user' | 'inferred'
createdAt: new Date(),
updatedAt: new Date(),
lastAccessedAt: new Date(),
accessCount: 0,
};
// Graph edge
const edge: GraphEdge = {
id: 'edge_456',
agentId: 'agent-1',
sourceNodeId: 'node_123',
targetNodeId: 'node_789',
type: 'works_at',
label: 'Senior Developer',
weight: 1.0,
bidirectional: false,
confidence: 0.95,
source: 'extracted',
properties: { since: '2020' },
createdAt: new Date(),
updatedAt: new Date(),
};
// Traversal options
const traversalOptions: TraversalOptions = {
agentId: 'agent-1',
startNodeId: 'node_123',
maxDepth: 3,
direction: 'outgoing', // 'outgoing' | 'incoming' | 'both'
edgeTypes: ['works_at', 'knows'],
minEdgeWeight: 0.5,
minConfidence: 0.7,
limit: 100,
};
// Traversal result
const path: GraphPath = { nodes: [node], edges: [edge], totalWeight: 1.0, length: 1 };
const result: TraversalResult = {
paths: [path],
visitedNodes: [node],
visitedEdges: [edge],
depth: 1,
};
快速优化类型
A/B测试,监控,以及代理指令的版本控制.
import type {
CapturedPrompt,
PromptStore,
ABTest,
ABTestResults,
ABTestOutcome,
ABTestStore,
InstructionVersion,
InstructionVersionStore,
PromptPerformanceMetrics,
DegradationAlert,
OptimizationRun,
} from '@cogitator-ai/types';
// Captured prompt
const prompt: CapturedPrompt = {
id: 'prompt_123',
runId: 'run_456',
agentId: 'agent-1',
threadId: 'thread_789',
model: 'gpt-6.1-sol',
provider: 'openai',
timestamp: new Date(),
systemPrompt: 'You are a helpful assistant.',
messages: [{ role: 'user', content: 'Hello' }],
tools: [
{
name: 'calculator',
description: 'Evaluate math',
parameters: { type: 'object', properties: {} },
},
],
promptTokens: 150,
response: {
content: 'Hi there!',
completionTokens: 10,
finishReason: 'stop',
latencyMs: 450,
},
};
// A/B test
const abTest: ABTest = {
id: 'test_123',
agentId: 'agent-1',
name: 'Instruction Experiment',
description: 'Testing concise vs verbose',
status: 'running',
controlInstructions: 'You are helpful.',
treatmentInstructions: 'Be concise and direct.',
treatmentAllocation: 0.5,
minSampleSize: 100,
maxDuration: 7 * 24 * 60 * 60 * 1000,
confidenceLevel: 0.95,
metricToOptimize: 'score',
controlResults: {
sampleSize: 50,
successRate: 0.9,
avgScore: 0.82,
avgLatency: 900,
totalCost: 0.4,
scores: [],
},
treatmentResults: {
sampleSize: 48,
successRate: 0.94,
avgScore: 0.87,
avgLatency: 850,
totalCost: 0.38,
scores: [],
},
createdAt: new Date(),
startedAt: new Date(),
};
// A/B test outcome
const outcome: ABTestOutcome = {
winner: 'treatment',
pValue: 0.023,
confidenceInterval: [0.02, 0.08],
effectSize: 0.45,
isSignificant: true,
recommendation: 'Treatment performs significantly better.',
};
// Instruction version
const version: InstructionVersion = {
id: 'ver_123',
agentId: 'agent-1',
version: 3,
instructions: 'Optimized instructions...',
source: 'optimization',
sourceId: 'opt-run-456',
deployedAt: new Date(),
metrics: { runCount: 100, avgScore: 0.88, successRate: 0.95, avgLatency: 1200, totalCost: 1.4 },
};
// Degradation alert
const alert: DegradationAlert = {
id: 'alert_123',
agentId: 'agent-1',
type: 'score_drop',
severity: 'warning',
currentValue: 0.72,
baselineValue: 0.85,
threshold: 0.15,
percentChange: 0.153,
detectedAt: new Date(),
autoAction: 'rollback',
actionTaken: false,
};
其他模块
下面的每个模块都从包根导出;自有的包文档如何使用类型.
| 模块 | 主要类型 | 用于 |
|---|---|---|
| 内存 | MemoryAdapter, (中文(简体) ), MemoryResult, (中文(简体) ), Thread, (中文(简体) ), MemoryEntry, (中文(简体) ), Fact, (中文(简体) ), Embedding, (中文(简体) ), EmbeddingService, (中文(简体) ), ContextBuilderConfig, (中文(简体) ), BuiltContext, (中文(简体) ), DroppedContext, (中文(简体) ), ContextPartition, (中文(简体) ), ContextPartitionBudget, (中文(简体) ), DroppedReason, (中文(简体) ), DroppedBlock, (中文(简体) ), MemoryConfig | @cogitator-ai/纪念 |
| 沙盒 | SandboxConfig, (中文(简体) ), SandboxManagerConfig (单位:千美元)allowNativeFallback默认值 true: Docker 不可用时在主机上运行的多克-沙箱命令), SandboxPoolConfig (单位:千美元)reuseContainers默认值 false: 每一次执行都得到一个新鲜的容器, SandboxWasmConfig (单位:千美元)memoryPages 盖住模块自身的内存, SandboxExecutionRequest | @cogitator-ai/ sandbox (英语) |
| 工作流程 | WorkflowState, (中文(简体) ), Workflow, (中文(简体) ), CheckpointStore, (中文(简体) ), RunStore, (中文(简体) ), ApprovalStore, (中文(简体) ), TimerStore (可选) claimTtl, (中文(简体) ), renew, (中文(简体) ), release, (中文(简体) ), WorkflowRunStats | @cogitator-ai/ 工作流程 |
| 沼泽,谈判 | SwarmConfig, (中文(简体) ), SwarmStrategy, (中文(简体) ), SwarmResult,谈判类型 | @cogitator-ai/ swarms (英语) |
| 宪政、安全 | GuardrailConfig, (中文(简体) ), Constitution, (中文(简体) ), PromptInjectionConfig, (中文(简体) ), PiiConfig, (中文(简体) ), PiiType | @cogitator-ai/core |
| 成本路由、上下文、工具缓存 | CostRoutingConfig, (中文(简体) ), BudgetConfig, (中文(简体) ), ContextManagerConfig, (中文(简体) ), ToolCacheConfig, (中文(简体) ), RedisClientLike (一个胆小鬼客户适合) | @cogitator-ai/core |
| 因果关系 | CausalGraph, (中文(简体) ), StructuralEquation (单位:千美元)custom 类型 customFn 表达式), InterventionQuery, (中文(简体) ), CounterfactualQuery, (中文(简体) ), CausalReasoningConfig | @cogitator-ai/core |
| 神经符号 | NeuroSymbolicConfig, (中文(简体) ), ResolvedNeuroSymbolicConfig (每一节到场,由 getConfig()(中文(简体) ) | @cogitator-ai/ 神经符号 |
| 自修改 | SelfModifyingConfig,生成的工具和架构类型 | @cogitator-ai/ 自我修改 |
| 频道网关 | GatewayConfig, (中文(简体) ), ChannelMessage, (中文(简体) ), HookRegistry, (中文(简体) ), HookPayloads (每个钩名的有效载荷: MessageReceivedEvent, (中文(简体) ), AgentErrorEvent, (中文(简体) ), ApprovalResolvedEvent, (...) (中文(简体) ) | @cogitator-ai/频道 |
| RAG、语音、浏览器、会话、部署 | RAGPipelineConfig,语音/STT/TTS类型,浏览器会话类型,会话类型, DeployConfig | 同名软件包 |
| 技能、伐木 | Skill, (中文(简体) ), SkillConfig, (中文(简体) ), LoggingConfig (单位:千美元)level 最多 'silent', (中文(简体) ), destination: 'file' 与 filePath(中文(简体) ) | @cogitator-ai/core |
HookPayloads 类型网关钩名: HookRegistry.on('agent:error', ({ error, threadId }) => …) 得到一个 AgentErrorEvent (单位:千美元)error 总是一个 Error),以及 HookName 实值 keyof HookPayloads操作器 HookHandler (单位:千美元)unknown 有效载荷)被接受用于任何钩. GatewayConfig.owner 已贬值:所有者设定在 ownerCommands({ ownerIds }) 财务报告和审定财务报表 dmPolicy({ ownerIds })。 。 。 .
许可证
麻省理工学院