@flatfile/improv

中文文档
0.3.1发布于 2025/11/04ISCTypeScriptESM + CJS近 30 天下载 1.7万

一个强大的TypeScript库,用于构建具有多线程对话、工具执行和事件处理能力的AI代理

中文使用文档
文档目录32 节
  1. 核心特征
  2. 目录
  3. 快速启动
  4. 页:1
  5. 新:独行侠、特工和吉格
  6. Solo - 结构化 LLM 呼叫
  7. 代理 - 工具启用的工作流程
  8. Gig - 工作流程管弦乐
  9. 片段 - 可重复使用的组件
  10. 能力
  11. 核心组成部分
  12. 探员
  13. 线索
  14. 工具
  15. 消息
  16. 事件系统
  17. 最佳做法
  18. 许可证
  19. 捐款
  20. 后续信件
  21. 州管理层
  22. 代理国
  23. 线索状态
  24. 工具状态
  25. 评价员系统
  26. 州管理模式
  27. 三眼锁模式
  28. AWS 贝德洛克集成
  29. 模型驱动程序
  30. 可用的驱动程序
  31. 工具装饰器
  32. 流程支持

@ 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参考文献:

新:独行侠、特工和吉格

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 }) => {});

最佳做法

  1. 选择正确的 API

    • 使用 独奏 分类、取出、结构化输出、简单QQA
    • 使用 探员 工具使用、多步骤推理、复杂决策
    • 使用 盖克 用于: 操作多个操作,具有依赖性的工作流程
  2. 块设计

    • 保持单项任务的片段焦点
    • 使用说明文件目的的名称
    • 杠杆 groove.recall() 获取以往结果
    • 取代成本优化的驱动程序(例如,简单任务的更便宜的模型)
  3. 工具设计

    • 保持工具原子化,并注重单一责任
    • 使用 Zod schemas 进行强参数验证
    • 在工具执行中执行适当的错误处理
    • 利用后续信息指导应对评估
  4. 工作流程组织

    • 默认按顺序执行可预见流量
    • 使用 parallel() 只有在操作真正独立时
    • 将评价数据分开 eval.ts 文件
    • 为共同操作创建可重复使用的部件
  5. 处理错误和复原力

    • 配置带有适当备份的再试逻辑
    • 为关键业务设置后退驱动器
    • 使用 onError 以 Gig 为单位的处理器
    • 监视调试和可观察性事件
  6. 类型安全

    • 为 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

评价员通过以下方式管理这些状况:

  1. 工具执行状态

    • 工具执行时的跟踪
    • 调用新工具时重新设置状态
    • 处理多工具处决
  2. 评价国

    • 工具完成后触发
    • 要求处理更多项目的提示
    • 必要时可以返回工具执行
  3. 摘要

    • 完成前的最后状态
    • 收集行动摘要
    • 完成时完成信号

关键特性:

  • 自动状态过渡
  • 基于事件的流动控制
  • 清除事件听众管理
  • 可配置的提示
  • 支持多种工具处决

带有自定义提示的用法示例 :

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提供者:

可用的驱动程序

驱动程序提供者文档
BedrockThreadDriverAWS 贝德罗克(克洛德)Bedrock 驱动文档
OpenAIThreadDriver开放AIOpenAI 驱动文档
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);

版本与发布记录

@flatfile/improv 共发布 69 个版本,首次发布于 2025/02/03;过去 12 个月发布了 0 个版本。

版本发布日期距今
0.3.1latest2025/11/041 年前
0.3.0-beta.62025/11/041 年前
0.3.0-beta.52025/11/041 年前
0.3.0-beta.42025/11/041 年前
0.3.0-beta.32025/11/041 年前
0.3.0-beta.22025/11/041 年前

关于 @flatfile/improv 的常见问题

@flatfile/improv 是什么?

一个强大的TypeScript库,用于构建具有多线程对话、工具执行和事件处理能力的AI代理

如何安装 @flatfile/improv?

在项目目录运行 npm install @flatfile/improv,或使用 pnpm add / yarn add / bun add。

@flatfile/improv 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@flatfile/improv 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@flatfile/improv 可以商用吗?

@flatfile/improv 使用 ISC 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@flatfile/improv 的下载量有多少?

根据 npm 官方下载统计,@flatfile/improv 在 2026/10/15 – 2026/11/13 这 30 天内被下载 17,040 次,日均约 568 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@flatfile/improv 还在维护吗?

最新版本 0.3.1 发布于 2025/11/04(1 年前);至今共发布 69 个版本,其中过去 12 个月发布了 0 个;首次发布于 2025/02/03。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。