@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 中的 model 和 temperature 是默认值,每次 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 支持以下参数:
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---|---|---|
apiKey | string | 是 | — | API 密钥 |
baseUrl | string | 否 | https://api.openai.com/v1 | API 端点 |
model | string | 否 | gpt-4o | 默认模型 |
temperature | number | 否 | 0.7 | 默认温度 |
onStream | (accumulated: string) => void | 否 | — | 全局流式进度回调,每次有新内容时触发,参数为累积全文 |
LlmCall payload 参数
LlmCall.plan(payload) 的 payload 支持以下字段:
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
messages | LlmMessage[] | 是 | 发送给模型的消息数组 |
target | string | 是 | 流式写入的目标时间轴名称 |
model | string | 否 | 覆盖 config 中的默认模型 |
temperature | number | 否 | 覆盖 config 中的默认温度 |
时间轴
LlmFeature 本身不声明任何固定时间轴。
外部时间轴
| 名称 | 值类型 | 方向 | 说明 |
|---|---|---|---|
LlmCall.plan({ target }) 指定 | string | 写入 | LLM 流式输出写入目标,名称由调用方在 plan() 中指定 |
内部时间轴
无。