@chronoai/toolkit/llm

LlmFeature

npm install @chronoai/toolkit

@chronoai/toolkit/llm — LlmFeature

LlmFeature 提供 OpenAI Chat Completions API 兼容的流式 LLM 调用封装,同时导出 LlmCall 命令种类,在自定义反应的 plan() 中使用即可触发调用。

兼容 OpenAI / Azure / DeepSeek / Moonshot / 通义千问等 OpenAI 格式接口。

快速上手

import { Agent, defineFeature, useTimeline, useCommand } from 'chronoai';
import { LlmFeature, LlmCall } from '@chronoai/toolkit/llm';

const agent = new Agent();

// 注册 LlmFeature,提供连接信息
agent.use(LlmFeature, {
  apiKey: 'sk-xxx',
  model: 'gpt-4o',
});

// 自定义 Feature:当用户提问时,触发 LLM 调用
const QAFeature = defineFeature('qa', () => {
  const question = useTimeline<string>({ name: 'question' });
  useTimeline<string>({ name: 'answer' });

  useCommand('ask', {
    when({ read }) {
      return !!read(question, 'current')?.value;
    },
    plan({ read }) {
      return LlmCall.plan({
        messages: [
          { role: 'system', content: '简洁回答。' },
          { role: 'user', content: read(question, 'current')!.value },
        ],
        target: 'answer',
      });
    },
  });
});

agent.use(QAFeature);
agent.initialize();

await agent.write('question', '什么是时间轴?');
console.log(agent.read('answer', 'current')?.value);

按次覆盖模型参数

LlmFeatureConfig 中的 modeltemperature 是默认值,每次 plan() 时可以按需覆盖:

LlmCall.plan({
  messages: [...],
  target: 'answer',
  model: 'gpt-4o-mini',       // 本次使用更轻量的模型
  temperature: 0.2,            // 本次使用更低的温度
});

流式进度回调

通过 onStream 配置全局流式进度回调:

agent.use(LlmFeature, {
  apiKey: 'sk-xxx',

  onStream(accumulated) {
    process.stdout.write('\r' + accumulated);
  },
});

配置参数

agent.use(LlmFeature, config)config 支持以下参数:

参数类型必填默认值说明
apiKeystringAPI 密钥
baseUrlstringhttps://api.openai.com/v1API 端点
modelstringgpt-4o默认模型
temperaturenumber0.7默认温度
onStream(accumulated: string) => void全局流式进度回调,每次有新内容时触发,参数为累积全文

LlmCall payload 参数

LlmCall.plan(payload)payload 支持以下字段:

字段类型必填说明
messagesLlmMessage[]发送给模型的消息数组
targetstring流式写入的目标时间轴名称
modelstring覆盖 config 中的默认模型
temperaturenumber覆盖 config 中的默认温度

时间轴

LlmFeature 本身不声明任何固定时间轴。

外部时间轴

名称值类型方向说明
LlmCall.plan({ target }) 指定string写入LLM 流式输出写入目标,名称由调用方在 plan() 中指定

内部时间轴

无。