@ flatfile/ improv (帮助)
一个强大的TypeScript库,用于构建AI动力应用程序,并配有三个互补的API:Solo用于简单结构化输出,Agent用于复杂的工具启用工作流程,Gig用于协调多步AI操作. 特性类型安全输出,内置重试/倒置机制,以及支持多个LLM提供者.
核心特征
- 🎯 独奏: 用于一次性LLM调用且结构化输出的简单、类型安全 API
- 🤖 探员:具有工具使用、知识基础和多步骤推理的高级AI代理
- 🎭 盖克: 有相继/平行执行和依赖性的管弦乐团复杂工作流程
- 🧩 块: 创建具有内置评价支持的可重复使用的工作流程组件
- 🛠️ 工具整合: 使用 Zod schemas 定义并执行带有类型安全参数的自定义工具
- 📎 附件支持: 处理各类附件(文件、图像、视频)
- 🔄 事件串流: 内建事件系统,用于实时监测和反应处理
- 💾 内存管理: 跟踪并坚持对话历史和代理状态
- 🔧 多服务支持: AWS Bedrock, OpenAI, Cohere, 双子座, Cerebras, 等
目录
快速启动
import { Agent, Tool, BedrockThreadDriver } from '@flatfile/improv';
import { z } from 'zod';
// Create a custom tool
const calculatorTool = new Tool({
name: 'calculator',
description: 'Performs basic arithmetic operations',
parameters: z.object({
operation: z.enum(['add', 'subtract', 'multiply', 'divide']),
a: z.number(),
b: z.number(),
}),
executeFn: async (args) => {
const { operation, a, b } = args;
switch (operation) {
case 'add': return a + b;
case 'subtract': return a - b;
case 'multiply': return a * b;
case 'divide': return a / b;
}
}
});
// Initialize the Bedrock driver
const driver = new BedrockThreadDriver({
model: 'anthropic.claude-3-haiku-20240307-v1:0',
temperature: 0.7,
});
// Create an agent
const agent = new Agent({
knowledge: [
{ fact: 'The agent can perform basic arithmetic operations.' }
],
instructions: [
{ instruction: 'Use the calculator tool for arithmetic operations.', priority: 1 }
],
tools: [calculatorTool],
driver,
});
// Create and use a thread
const thread = agent.createThread({
prompt: 'What is 25 multiplied by 4?',
onResponse: async (message) => {
console.log('Agent response:', message.content);
}
});
// Send the thread
await thread.send();
// Stream the response
const stream = await thread.stream();
for await (const text of stream) {
process.stdout.write(text); // Print each chunk as it arrives
}
页:1
综合指南和API参考文献:
- 完整文档 - 所有指南和参考资料
- API 概览 - 全面概述所有API
- 事件系统指南 - 利用事件和监测
- 事件参考 - 完成事件登记
- * 结构化产出 - 安全型LLM反应
- & Solo 代理模式 - 何时使用每个API
- QQ 创建片段 - 建筑可再利用组件
新:独行侠、特工和吉格
Improv现在为不同的AI使用案例提供了简化的API:
Solo - 结构化 LLM 呼叫
简而言之,一次性的LLM调用具有结构化输出:
import { Solo } from '@flatfile/improv';
import { z } from 'zod';
const solo = new Solo({
driver,
outputSchema: z.object({
sentiment: z.enum(["positive", "negative", "neutral"]),
confidence: z.number().min(0).max(1)
})
});
const result = await solo.ask("Analyze the sentiment: 'This product is amazing!'");
// result.output is fully typed: { sentiment: "positive", confidence: 0.95 }
关键特性 :
- 带有 Zod 计划的结构化类型安全输出
- 内置重试逻辑, 以指数倒置
- 后退驱动程序支持
- 流动支助
- 用于分类和提取任务的简单 API
代理 - 工具启用的工作流程
对于需要使用工具的复杂多步骤工作流程:
import { Agent, Tool } from '@flatfile/improv';
const searchTool = new Tool({
name: "search",
description: "Search the knowledge base",
parameters: z.object({ query: z.string() }),
executeFn: async ({ query }) => {
// Your search implementation
return { results: ["Result 1", "Result 2"] };
}
});
const agent = new Agent({
driver,
tools: [searchTool],
instructions: [
{ instruction: "Always search before answering", priority: 1 }
]
});
const thread = agent.createThread({
prompt: "What are the best practices for error handling?"
});
await thread.send();
Gig - 工作流程管弦乐
管弦乐器具有依赖性和控制流的多个AI操作:
import { Gig, PieceDefinition } from '@flatfile/improv';
const gig = new Gig({
label: "Customer Support Workflow",
driver
});
// Add pieces sequentially (default behavior)
gig
.add("classify", groove =>
`Classify this support request: "${groove.feelVibe("request")}"`, {
outputSchema: z.enum(["technical", "billing", "general"])
})
.add("sentiment", groove =>
`Analyze sentiment: "${groove.feelVibe("request")}"`, {
outputSchema: z.enum(["positive", "negative", "neutral"])
})
// Pieces can access previous results
.add("research", groove => {
const category = groove.recall("classify");
return `Research solutions for ${category} issue`;
}, {
tools: [searchTool],
driver: cheaperModel // Override driver for cost optimization
})
// Explicit parallel execution when needed
.parallel([
["check_status", "Check system status"],
["find_similar", "Find similar resolved issues"]
])
.add("respond", groove => {
const sentiment = groove.recall("sentiment");
const research = groove.recall("research");
return `Generate ${sentiment} response using: ${research}`;
});
// Execute the workflow
const results = await gig.perform({
request: "My invoice is wrong and I'm very frustrated!"
});
console.log(results.recordings.get("classify")); // "billing"
console.log(results.recordings.get("sentiment")); // "negative"
关键特性 :
- 默认顺序执行( 可预测的流量)
- 明确
parallel()用于同时进行的业务 - 自动检测:将Solo用于结构化输出, 工具代理
- 为优化每个部件的驱动程序覆盖
- 访问上一个结果
groove.recall() - 具有完整类型脚本支持的类型安全
片段 - 可重复使用的组件
创建可在项目间共享的可重复使用的工作流程组件:
import { PieceDefinition } from '@flatfile/improv';
import { z } from 'zod';
// Define a reusable piece
export const sentimentAnalysis: PieceDefinition<"positive" | "negative" | "neutral"> = {
name: "sentiment",
play: (groove) => {
const text = groove.feelVibe("text");
return `Analyze sentiment of: "${text}"`;
},
config: {
outputSchema: z.enum(["positive", "negative", "neutral"]),
temperature: 0.1
},
meta: {
version: "1.0.0",
description: "Analyzes emotional tone of text"
}
};
// Use in any Gig
gig.add(sentimentAnalysis);
组织有评价的小块:
src/
pieces/
sentiment/
index.ts # Piece definition (production)
eval.ts # Evaluation data (dev only)
这种分离确保了评价数据集不会被捆绑在生产建设中.
能力
Emprov通过 reasoning_config 选项。 这使得AI在提供最后答案之前可以进行分步推理.
import { Agent, BedrockThreadDriver } from '@flatfile/improv';
const driver = new BedrockThreadDriver({
model: 'anthropic.claude-3-7-sonnet-20250219-v1:0',
temperature: 1,
reasoning_config: {
budget_tokens: 1024,
type: 'enabled',
},
});
const agent = new Agent({
driver,
});
const thread = agent.createThread({
systemPrompt: 'You are a helpful assistant that can answer questions about the world.',
prompt: 'How many people will live in the world in 2040?',
});
const result = await thread.send();
console.log(result.last());
这个例子使大赦国际能够通过其推理程序,在就人口预测提供最后答案之前,象征性的预算为1024个符号.
核心组成部分
探员
管理知识,指令,工具和对话线索的主要代理类.
const agent = new Agent({
knowledge?: AgentKnowledge[], // Array of facts with optional source and timestamp
instructions?: AgentInstruction[], // Array of prioritized instructions
memory?: AgentMemory[], // Array of stored thread histories
systemPrompt?: string, // Base system prompt
tools?: Tool[], // Array of available tools
driver: ThreadDriver, // Thread driver implementation
evaluators?: Evaluator[] // Array of evaluators for response processing
});
线索
管理有消息历史和工具执行的单个对话线索.
const thread = new Thread({
messages?: Message[], // Array of conversation messages
tools?: Tool[], // Array of available tools
driver: ThreadDriver, // Thread driver implementation
toolChoice?: 'auto' | 'any', // Tool selection mode
maxSteps?: number // Maximum number of tool execution steps
});
工具
定义代理在对话中可以使用的自定义工具 .
const tool = new Tool({
name: string, // Tool name
description: string, // Tool description
parameters: z.ZodTypeAny, // Zod schema for parameter validation
followUpMessage?: string, // Optional message to guide response evaluation
executeFn: (args: Record<string, any>, toolCall: ToolCall) => Promise<any> // Tool execution function
});
消息
代表谈话线索中的单个信息 .
const message = new Message({
content?: string, // Message content
role: 'system' | 'user' | 'assistant' | 'tool', // Message role
toolCalls?: ToolCall[], // Array of tool calls
toolResults?: ToolResult[], // Array of tool results
attachments?: Attachment[], // Array of attachments
cache?: boolean // Whether to cache the message
});
事件系统
文库采用事件驱动架构. 所有主要部分都延长 EventSource,允许您聆听各种事件:
// Agent events
agent.on('agent.thread-added', ({ agent, thread }) => {});
agent.on('agent.thread-removed', ({ agent, thread }) => {});
agent.on('agent.knowledge-added', ({ agent, knowledge }) => {});
agent.on('agent.instruction-added', ({ agent, instruction }) => {});
// Thread events
thread.on('thread.response', ({ thread, message }) => {});
thread.on('thread.max_steps_reached', ({ thread, steps }) => {});
// Tool events
tool.on('tool.execution.started', ({ tool, name, args }) => {});
tool.on('tool.execution.completed', ({ tool, name, args, result }) => {});
tool.on('tool.execution.failed', ({ tool, name, args, error }) => {});
最佳做法
-
选择正确的 API
- 使用 独奏 分类、取出、结构化输出、简单QQA
- 使用 探员 工具使用、多步骤推理、复杂决策
- 使用 盖克 用于: 操作多个操作,具有依赖性的工作流程
-
块设计
- 保持单项任务的片段焦点
- 使用说明文件目的的名称
- 杠杆
groove.recall()获取以往结果 - 取代成本优化的驱动程序(例如,简单任务的更便宜的模型)
-
工具设计
- 保持工具原子化,并注重单一责任
- 使用 Zod schemas 进行强参数验证
- 在工具执行中执行适当的错误处理
- 利用后续信息指导应对评估
-
工作流程组织
- 默认按顺序执行可预见流量
- 使用
parallel()只有在操作真正独立时 - 将评价数据分开
eval.ts文件 - 为共同操作创建可重复使用的部件
-
处理错误和复原力
- 配置带有适当备份的再试逻辑
- 为关键业务设置后退驱动器
- 使用
onError以 Gig 为单位的处理器 - 监视调试和可观察性事件
-
类型安全
- 为 Solo 操作定义与 Zod 的输出计划
- 使用
PieceDefinition<T>用于类型安全部件 - 利用类型Script的推论
groove.recall()
许可证
麻省理工学院
捐款
欢迎捐款! 请阅读我们提供的详细指导.
后续信件
工具可以包括指导AI评估工具响应的后续信息. 这对于:
- 提供工具成果的背景
- 指导大赦国际对数据的解释
- 保持一致的反应模式
- 建议今后的步骤或行动
const tool = new Tool({
name: 'dataAnalyzer',
description: 'Analyzes data and returns insights',
parameters: z.object({
data: z.array(z.any()),
metrics: z.array(z.string())
}),
followUpMessage: `Review the analysis results:
1. What are the key insights from the data?
2. Are there any concerning patterns?
3. What actions should be taken based on these results?`,
executeFn: async (args) => {
// Tool implementation
}
});
州管理层
该图书馆提供几种管理状态的机制:
代理国
- 储存事实的知识库
- 行为指导的优先指示
- 存储线程历史的内存系统
- 基础背景的系统提示
线索状态
- 信件历史跟踪
- 工具执行状态
- 最大步数限制
- 反应处理器
工具状态
- 参数验证
- 执行跟踪
- 结果处理
- 事件排放
评价员系统
评价员提供了一种处理和验证代理人反应的方法:
const evaluator: Evaluator = async ({ thread, agent }, complete) => {
// Process the thread response
const lastMessage = thread.last();
if (lastMessage?.content.includes('done')) {
complete(); // Signal completion
} else {
// Continue processing
thread.send(new Message({
content: 'Please continue with the task...'
}));
}
};
const agent = new Agent({
// ... other options ...
evaluators: [evaluator]
});
评价人员可以:
- 加工剂回复
- 触发附加动作
- 控制对话流程
- 验证结果
州管理模式
三眼锁模式
三键锁模式是一种状态管理模式,通过工具执行,评价,和完成阶段确保有控制的流量. 作为可重复使用的评价人执行:
import { threeKeyedLockEvaluator } from '@flatfile/improv';
const agent = new Agent({
// ... other options ...
evaluators: [
threeKeyedLockEvaluator({
evalPrompt: "Are there other items to process? If not, say 'done'",
exitPrompt: "Please provide a final summary of all actions taken."
})
]
});
该模式通过三个不同的状态发挥作用:
stateDiagram-v2
[*] --> ToolExecution
state "Tool Execution" as ToolExecution {
[*] --> Running
Running --> Complete
Complete --> [*]
}
state "Evaluation" as Evaluation {
[*] --> CheckMore
CheckMore --> [*]
}
state "Summary" as Summary {
[*] --> Summarize
Summarize --> [*]
}
ToolExecution --> Evaluation: Non-tool response
Evaluation --> ToolExecution: Tool called
Evaluation --> Summary: No more items
Summary --> [*]: Complete
note right of ToolExecution
isEvaluatingTools = true
Handles tool execution
end note
note right of Evaluation
isEvaluatingTools = false
nextMessageIsSummary = false
Checks for more work
end note
note right of Summary
nextMessageIsSummary = true
Gets final summary
end note
评价员通过以下方式管理这些状况:
-
工具执行状态
- 工具执行时的跟踪
- 调用新工具时重新设置状态
- 处理多工具处决
-
评价国
- 工具完成后触发
- 要求处理更多项目的提示
- 必要时可以返回工具执行
-
摘要
- 完成前的最后状态
- 收集行动摘要
- 完成时完成信号
关键特性:
- 自动状态过渡
- 基于事件的流动控制
- 清除事件听众管理
- 可配置的提示
- 支持多种工具处决
带有自定义提示的用法示例 :
const workflowAgent = new Agent({
// ... agent configuration ...
evaluators: [
threeKeyedLockEvaluator({
evalPrompt: "Review the results. Should we process more items?",
exitPrompt: "Provide a detailed summary of all processed items."
})
]
});
// The evaluator will automatically:
// 1. Let tools execute freely
// 2. After each tool completion, check if more processing is needed
// 3. When no more items need processing, request a final summary
// 4. Complete the evaluation after receiving the summary
这种模式特别有利于:
- 连续处理多个项目
- 需要在步骤之间验证的工作流程
- 动态工具使用的任务
- 需要最后摘要的业务
AWS 贝德洛克集成
库使用AWS Bedrock(克洛德)作为其默认的LLM提供者. 配置您的 AWS 证书 :
// Required environment variables
process.env.AWS_ACCESS_KEY_ID = 'your-access-key';
process.env.AWS_SECRET_ACCESS_KEY = 'your-secret-key';
process.env.AWS_REGION = 'your-region';
// Initialize the driver
const driver = new BedrockThreadDriver({
model: 'anthropic.claude-3-haiku-20240307-v1:0', // Default model
temperature?: number, // Default: 0.7
maxTokens?: number, // Default: 4096
cache?: boolean // Default: false
});
模型驱动程序
Improv通过专用线程驱动支持多个LLM提供者:
可用的驱动程序
| 驱动程序 | 提供者 | 文档 |
|---|---|---|
BedrockThreadDriver | AWS 贝德罗克(克洛德) | Bedrock 驱动文档 |
OpenAIThreadDriver | 开放AI | OpenAI 驱动文档 |
CohereThreadDriver | 代码 | Cohere 驱动文档 |
GeminiThreadDriver | 谷歌双子座 | 双子座驱动文档 |
CerebrasThreadDriver | 心管 | Cerebras 驱动文档 |
每个驱动程序提供一致的接口,同时支持模型特定特性:
// OpenAI example
import { OpenAIThreadDriver } from '@flatfile/improv';
const driver = new OpenAIThreadDriver({
model: 'gpt-4o',
apiKey: process.env.OPENAI_API_KEY,
temperature: 0.7
});
// Cohere example
import { CohereThreadDriver } from '@flatfile/improv';
const driver = new CohereThreadDriver({
model: 'command-r-plus',
apiKey: process.env.COHERE_API_KEY
});
// Gemini example
import { GeminiThreadDriver } from '@flatfile/improv';
const driver = new GeminiThreadDriver({
model: 'gemini-1.5-pro',
apiKey: process.env.GOOGLE_API_KEY
});
// Cerebras example
import { CerebrasThreadDriver } from '@flatfile/improv';
const driver = new CerebrasThreadDriver({
model: 'llama-4-scout-17b-16e-instruct',
apiKey: process.env.CEREBRAS_API_KEY
});
参考每个驱动程序的文件,以获取可用的模型和特定配置选项.
工具装饰器
库为代理类直接创建工具提供装饰:
class CustomAgent extends Agent {
@ToolName("sampleData")
@ToolDescription("Sample the original data with the mapping program")
private async sampleData(
@ToolParam("count", "Number of records to sample", z.number())
count: number,
@ToolParam("seed", "Random seed", z.number().optional())
seed?: number
): Promise<any> {
return { count, seed };
}
}
该条规定:
- 类型安全工具定义
- 自动参数验证
- 清洁方法工具
- 综合错误处理
流程支持
库为AI模式的流回响应提供内置支持. 密钥特性 :
- 生成的实时文本块
- 线索中的自动信件管理
- 流量进展的排放事件
- 处理和恢复错误
- 兼容包括工具调用在内的所有线程特性
const thread = agent.createThread({
prompt: 'What is 25 multiplied by 4?',
});
const stream = await thread.stream();
for await (const text of stream) {
process.stdout.write(text);
}
// The final response is also available in the thread
console.log(thread.last()?.content);