Files

68 lines
2.2 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 第二课:模型可调用工具
目标:创建 src/learning-tool.ts,注册 learning_greet 工具。输入 name 字符串,返回问候。先不实现持久化或 Todo。
当前 Pi 1.2.0 示例依据:examples/extensions/hello.ts。
## 骨架(学习者填写 TODO)
```ts
import { Type } from "@earendil-works/pi-ai";
import {
defineTool,
type ExtensionAPI,
} from "@earendil-works/pi-coding-agent";
const greetingTool = defineTool({
name: "learning_greet",
label: "Learning Greet",
description: "返回给指定名字的问候,用于学习 Pi 工具调用。",
parameters: Type.Object({
name: Type.String({ description: "被问候者的名字" }),
}),
async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
// TODO:构造问候 message,然后返回:
// { content: [{ type: "text", text: message }],
// details: { greeted: params.name } }
},
});
export default function (pi: ExtensionAPI) {
// TODO:把 greetingTool 注册给 Pi。
}
```
提示:注册方法是 pi.registerTool(...)。message 用模板字符串构造。
## 核心区别
- import type 的类型导入被擦除;这里 Type 和 defineTool 是运行时的值,必须保留普通导入。
- Type.Object / Type.String 在运行时构造输入 schema,Pi 据此校验工具参数。
- params 的类型由 defineTool 与 parameters schema 推导,不要主动加 any。
- execute 返回 content,模型能看到其中的文本;details 是结构化详情,可用于 UI 或状态恢复,不要当作秘密存储。
- 下划线开头的参数名只是未使用参数的常见命名习惯,不是 TS 特殊语法。
- 工具执行不依赖 ctx.hasUI,不需要显示通知。
## 测试
```bash
cd /root/pi-lesson/harness-learning
pi --extension ./src/learning-tool.ts
```
向模型发送:
> 请调用 learning_greet 工具,参数 name 为 Alice,然后告诉我工具结果。
观察是否真的出现工具调用及结果,不把模型直接输出问候当作验收通过。
## 验收
- 扩展加载成功。
- 模型实际调用 learning_greet,参数 name 为 Alice。
- 工具返回问候文本。
- 能解释为什么 Type 不能用 import type 导入。
完成后让教学 agent review 文件并报告实际运行结果。