# 接入方式
小程序 AI 开发模式(下文简称"此模式")提供了一套智能化的运行环境与开发框架。开发者可根据自身业务需求,参考本文档将小程序的功能抽象为原子接口与原子组件,并封装成 SKILL,供小程序 AI 调用。
# 一、全局提示词
全局提示词用于整体说明此模式下提供的服务范围,提供相关的背景知识、行为逻辑与回答风格,并引导小程序 AI 生成"猜你想问"等内容。
此外,一个小程序可能存在多个 SKILLs,多个 SKILLs 之间的关联关系与介绍也可以在全局提示词中说明,帮助模型选择合适的 SKILL 与原子接口来服务用户。
全局提示词通常是一个名为 AGENTS.md 的文件,可以在 app.json 中指定其路径:
// app.json
{
"agent": {
"skills": [],
"instruction": "path/to/AGENTS.md"
}
}
instruction 字段目前非必填,文件大小最大为 10000 字节。
# 二、SKILL 声明
一个小程序可声明多个 SKILLs。SKILL 必须封装在独立分包中,一个独立分包可以放置多个 SKILLs,且需要全局开启按需注入(lazyCodeLoading)。
在 app.json 中增加 agent 字段声明 SKILL 列表(agent.skills),每个 SKILL 的字段说明如下:
| 字段 | 必填 | 说明 |
|---|---|---|
| name | 是 | SKILL 名称 |
| description | 是 | SKILL 简要说明 |
| path | 是 | SKILL 分包路径(绝对路径) |
// app.json
{
"lazyCodeLoading": "requiredComponents",
"subPackages": [
{
"root": "path/to/pkg",
"independent": true,
"pages": []
}
],
"agent": {
"skills": [
{
"name": "weatherSkill",
"description": "查询天气业务",
"path": "path/to/pkg/weatherSkill"
},
{
"name": "shoppingSkill",
"description": "购物业务",
"path": "path/to/pkg/shoppingSkill"
}
]
}
}
# 三、SKILL 封装
SKILL 包含业务说明(SKILL.md)、模型可调用能力的声明(mcp.json)、原子接口(apis/)与原子组件(components/)的实现,目录结构如下:
| 文件 | 说明 | 是否必须 |
|---|---|---|
| SKILL.md | SKILL 的详细说明,仅支持单文件,不支持引用其他 md 文件,最大 16000 字节 | 是 |
| index.js | 注册当前 SKILL 所涉及的所有原子接口 | 是 |
| mcp.json | 模型可调用能力的声明(当前 SKILL 所有原子接口的声明),最大 24000 字节 | 是 |
| components/ | 原子组件代码实现所在目录 | 否,仅作为建议 |
| apis/ | 原子接口代码实现所在目录 | 否,仅作为建议 |
请注意
计算 mcp.json 的长度时,会先除去所有 outputSchema 字段及空格、换行符,再进行计算。
|-- path/to/pkg/weatherSkill
| |-- SKILL.md
| |-- mcp.json
| |-- components/
| |-- apis/
| |-- index.js
# 3.1 模型可调用能力的声明
mcp.json 包含所有原子接口的 Schema 声明。其中 componentPath 表示该原子接口的返回结果可由原子组件渲染卡片;inputSchema 与 outputSchema 需遵循 JSON Schema 规范。
| 属性 | 是否必填 | 说明 |
|---|---|---|
| name | 是 | 标识符,需与 index.js 中导出的原子接口函数名一致 |
| description | 是 | 原子接口的功能描述 |
| inputSchema | 是 | 原子接口的入参 Schema,需为对象格式 |
| outputSchema | 建议填写 | 原子接口返回的 structuredContent 对应的 Schema |
| _meta | 否 | 可指定渲染的原子组件与接力页面,componentPath 相对于 SKILL 目录,如 { "ui": { "componentPath": "path/to/comp" } } |
下面是只包含一个 getWeather 原子接口的声明示例:
{
"apis": [
{
"name": "getWeather",
"description": "查询当前位置或某地未来一段时间的天气",
"_meta": {
"ui": {
"componentPath": "path/to/comp",
"pagePath": "path/to/page"
}
},
"inputSchema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "要查询天气的地点,如城市名、行政区名或经纬度。不传则默认取当前位置"
},
"days": {
"type": "number",
"description": "预报天数,范围 1-15,默认 7"
}
},
"required": ["days"]
},
"outputSchema": {}
}
]
}
# 处理图片/文件内容
小程序 AI 的输入框支持多模态上传,用户可以发送图片/文件给小程序 AI。如果需要处理用户上传的图片/文件,可以在原子接口声明的 inputSchema 字段中标记 "format": "image" | "file"。小程序 AI 会调用相应的原子接口,并将接收到的图片/文件传给对应字段。
{
"name": "EditPhoto",
"description": "帮用户 P 图",
"inputSchema": {
"type": "object",
"properties": {
"imagePath": {
"type": "string",
"description": "本地图片路径",
"format": "image"
},
"query": {
"type": "string",
"description": "用户的 P 图需求"
}
},
"required": ["imagePath", "query"]
}
}
# 3.2 原子接口实现
以原子接口 getWeather 为例,其返回值说明如下:
| 属性 | 类型 | 必填 |
|---|---|---|
| isError | boolean | 否,默认为 false |
| content | ContentBlock[] | 是,返回给 LLM 的文本内容,不超过 200 KB |
| structuredContent | Record | 否,返回给 LLM 的结构化数据,不超过 200 KB |
| handoff | HandoffResolver | 否,接力到小程序页面的数据,见「接力到小程序页面」 |
| _meta | Record | 否,对 LLM 不可见,可携带元数据,不超过 200 KB |
| apiCalls | { name: string; arguments: Record }[] | 否,显式指定下一步调用的原子接口 |
其中 isError、structuredContent、content 三个字段的数据会作为 LLM 的上下文供模型理解;_meta 的内容对 LLM 不可见,用于携带私有数据并传递给原子组件。
- 当
isError: true时,不会进行 GUI 卡片渲染,structuredContent将被忽略,content常用于异常流程的引导。 - 当
isError: false且该原子接口绑定了原子组件时,小程序 AI 会倾向于渲染 GUI 卡片,structuredContent的数据会传给原子组件用于渲染(便于模型理解卡片内容),content用于后续流程引导。如需强制展示 GUI 卡片,可在content中追加引导,例如:「接下来为用户展示 XXX UI 卡片」。
ContentBlock[] 目前只支持文本内容,定义如下:
interface TextContent {
type: "text";
text: string;
}
HandoffResolver 定义如下:
type HandoffResolver = (data: {
result: {
isError: boolean;
content: ContentBlock[];
structuredContent: Record<string, unknown>;
_meta: Record<string, unknown>;
};
}) => { query: string; payload: Record<string, unknown> };
在原子接口的内部实现中,可以通过 ft.request 从开发者自己的服务器请求数据,也可以通过云开发接口调用云函数或数据库获取数据。
下面是 getWeather 的代码实现示例:
async function getWeather({ location, days }) {
// 原子接口内部实现,此处省略
// ft.request({ url: 'https://www.example.com/get_weather' })
return {
isError: false,
content: [{ type: "text", text: "已为您查询到北京未来3天天气" }],
structuredContent: {
location: "北京",
forecasts: [
{ date: "2026-04-23", dayWeather: "晴", tempHigh: 28, tempLow: 14 },
{ date: "2026-04-24", dayWeather: "多云", tempHigh: 25, tempLow: 13 },
{ date: "2026-04-25", dayWeather: "小雨", tempHigh: 20, tempLow: 12 }
]
}
};
}
# 显式指定下一步调用的原子接口
在某些流程较固定的场景中,需要在一个原子接口调用完成后明确触发下一个原子接口。此时可以在返回值中显式指定要调用的原子接口(apiCalls),以减少模型推理的耗时。
ft.modelContext.registerAPI('placeOrder', async ({ skuId, count }) => {
const loggedIn = await checkUserLogin();
// 未登录:指示下一步调用 login
if (!loggedIn) {
return {
isError: false,
content: [{ type: 'text', text: '用户未登录' }],
apiCalls: [{ name: 'login', arguments: {} }]
};
}
// 已登录:正常下单
const order = await createOrder({ skuId, count });
return {
isError: false,
content: [{ type: 'text', text: '订单已创建' }]
};
});
# 3.3 注册原子接口
在 SKILL 目录的 index.js 中进行注册。当小程序 AI 发起原子接口调用时,会在注册列表中找到对应的函数入口并执行:
const getWeather = require('./apis/getWeather');
const skill = ft.modelContext.createSkill('/path/to/pkg/weatherSkill');
// name 需与 mcp.json 中声明的一致
skill.registerAPI('getWeather', getWeather);
# 中间件机制
为了方便在多个原子接口之间复用公共逻辑,此模式提供了原子接口中间件机制,可用于统一登录态、统一上报与错误监听等场景。
ft.modelContext.createSkill(skillPath: string); // 创建 skill,skillPath 与 app.json 中 agent.skills[].path 一致
skill.use(Middleware); // 注册中间件
skill.registerAPI(name, handler); // 注册原子接口,等同于 ft.modelContext.registerAPI('name', handler)
interface MiddlewareContext {
name: string; // 当前执行的原子接口名
skillPath: string; // 中间件执行时所在的 skill
arguments: Record<string, any>; // 原子接口的入参
}
type Middleware = (ctx: MiddlewareContext, next: () => Promise<void>) => Promise<void>;
示例:
const skill = ft.modelContext.createSkill('path/to/pkg/weatherSkill');
skill.registerAPI('getWeather', getWeather);
skill.use(async (ctx, next) => {
// 1. 统一登录(仅首次)
const token = ft.getStorageSync('token');
if (!token) {
const { code } = await ft.login();
const res = await ft.request({ url: '...', data: { code } });
ft.setStorageSync('token', res.data.token);
// 也可以直接抛出错误,让小程序 AI 走其他处理流程
}
// 2. 上报:记录开始时间
const start = Date.now();
try {
await next(); // 执行实际的原子接口 handler
reportLog({ name: ctx.name, cost: Date.now() - start });
} catch (err) {
// 3. 统一错误监听
reportError({ name: ctx.name, error: err, cost: Date.now() - start });
throw err;
}
});
核心语义:
- 每次原子接口调用都会执行中间件;
next()之前是前置逻辑,next()之后是后置逻辑,可用 try/catch 捕获错误;- 整个中间件链与原子接口的执行时间共享超时上限(当前为 300s);
- 支持注册多个中间件,按注册顺序形成调用链:外层 → 内层 → handler → 内层 → 外层;
- 中间件函数须为 async 类型,运行时会 await 整个链路。
# 3.4 接力到小程序页面
原子接口返回的结构化数据有两种呈现方式,其中一种是小程序页面:对话流程中,原子接口被调用后返回的数据会传入小程序页面,将对话流程接力到小程序页面内,以无缝衔接当前的流程状态。
请注意
若只需在回复文字中给出详情入口,而不把当前对话流程整段接力进页面,应使用 outputSchema 的 format: "page-link"(见「文本混排链接」),而不是返回 handoff。两种能力可以同时存在,互不替代。
实现上分为以下三步:
1. 在 mcp.json 中声明原子接口对应的 pagePath
{
"apis": [
{
"name": "getWeather",
"_meta": {
"ui": {
"pagePath": "/path/to/page"
}
}
}
]
}
请注意
pagePath 暂不支持动态改变。
2. 原子接口返回 handoff 对象
在原子接口返回值中携带 handoff 对象,与 content / structuredContent 字段同级。handoff 包含 query 与 payload 字段:query 与前面的 pagePath 共同构造出打开小程序页面的链接,payload 则通过 ft.onAgentHandoff 接口传递给小程序。
| 字段 | 必填 | 说明 |
|---|---|---|
| path | 否 | 允许动态指定页面路径 |
| query | 否 | 页面 query 字符串,小程序页面通过 Page 的 onLoad 与 ft.onAgentHandoff 获取 |
| payload | 否 | 可传递原子接口返回的业务数据,用于小程序页面同步对应的流程状态,通过 ft.onAgentHandoff 获取 |
async function getWeather({ location, days }) {
// 原子接口内部实现,此处省略
return {
isError: false,
content: [{ type: "text", text: "已为您查询到北京未来3天天气" }],
structuredContent: {},
handoff: (data) => {
// data.result.structuredContent 为模型根据用户意图过滤后的数据
// query 包含特殊字符时,开发者需自行 encodeURIComponent
return {
query: `poi=${encodeURIComponent('北京')}`,
payload: {
location: '北京',
forecasts: [
{ date: "2026-04-23", dayWeather: "晴", tempHigh: 28, tempLow: 14 },
{ date: "2026-04-24", dayWeather: "多云", tempHigh: 25, tempLow: 13 }
]
}
};
}
};
}
3. 小程序监听 ft.onAgentHandoff 获取 handoff 数据
小程序通过 ft.onAgentHandoff 获取原子接口传递的 handoff 数据,将页面同步至对应的流程状态;必要时,还需将业务流程对应的页面栈同步成合适的状态。
| API | 说明 |
|---|---|
| ft.onAgentHandoff(callback) | 点击小程序卡片进入时触发 |
| ft.offAgentHandoff(callback) | 取消监听 |
回调参数:
{
pageId: number // 目标页实例 ID,用于将 payload 精确投递到关联页面
path: string // 当前打开页面的 path(不含 query)
query: string // 页面 query 字符串,与原子接口返回的 handoff.query 相同
payload: unknown // 原子接口返回的 handoff.payload
}
代码示例:
App({
onLaunch() {
ft.onAgentHandoff(({ pageId, path, query, payload }) => {
this.globalData.agentHandoffs = this.globalData.agentHandoffs || {};
this.globalData.agentHandoffs[pageId] = { path, query, payload };
});
}
});
Page({
onLoad(query) {
const handoffs = getApp().globalData.agentHandoffs || {};
const handoff = handoffs[this.getPageId()];
delete handoffs[this.getPageId()];
// 使用原子接口返回的数据更新页面状态
this.setData({ forecasts: handoff.payload.forecasts });
// 使用 query 参数拉取数据;若 handoff 提交的 query 做过 encode,这里需自行 decode
const parsedPoi = decodeURIComponent(query.poi);
this.loadPoiDetail(parsedPoi).then((forecasts) => this.setData({ forecasts }));
}
});
# 3.5 原子组件实现
请注意
原子组件当前暂不支持调试。
# 3.5.1 原子组件定义
原子组件用于承接原子接口返回的结构化数据的展示。在编码上,它与小程序的自定义组件一致,但需要注意的是,原子组件不可声明为虚拟组件。
通过 ft.modelContext.getContext / getViewContext 可以获取原子组件渲染时需要的尺寸、数据等信息:
Component({
lifetimes: {
created() {
const modelCtx = ft.modelContext.getContext(this);
const { NotificationType } = ft.modelContext;
modelCtx.on(NotificationType.Input, (data) => {
// 原子接口的入参数据
});
modelCtx.on(NotificationType.Result, (data) => {
// 原子接口的出参数据
});
const viewCtx = ft.modelContext.getViewContext(this);
const { minHeight, maxHeight, width } = viewCtx.getDimensions();
viewCtx.on(NotificationType.Overflow, (data) => {
// data.contentHeight: 内容总高
// data.overflowHeight: 溢出高度
// data.maxHeight: 当前卡片容器的硬性阈值
// 注意:若给组件根节点设置 maxHeight 和 overflow: hidden,则无法触发
});
}
}
});
# 3.5.2 关联小程序页面(必须)
原子组件渲染出的 GUI 卡片上方有标题栏,其右上方提供进入小程序的入口,该入口必须配置与原子组件关联的小程序页面。
实现上分为两步:
1. 在 mcp.json 中声明原子组件所对应小程序页面的完整 path(固定 path):
{
"apis": [],
"components": [
{
"path": "path/to/comp",
"relatedPage": "/path/to/related-page"
}
]
}
2. 在原子组件渲染时,动态设置页面的 query 参数:
Component({
lifetimes: {
created() {
const modelCtx = ft.modelContext.getContext(this);
this._viewCtx = ft.modelContext.getViewContext(this);
modelCtx.on('result', (data) => {
const { orderId } = data.result.structuredContent;
this.setData({ orderId });
// 若只传 query,路径由 mcp.json 中的 components[].relatedPage 决定
this._viewCtx.setRelatedPage({ query: `orderId=${orderId}` });
// 若原子组件可能与多个小程序页面关联,也可传入 path 参数
// this._viewCtx.setRelatedPage({ path: '/path/to/page', query: `orderId=${orderId}` })
});
}
},
methods: {
onSpecChange(e) {
const spec = e.detail.value;
this.setData({ selectedSpec: spec });
// 状态变化后更新 query 参数
this._viewCtx.setRelatedPage({
query: `orderId=${this.data.orderId}&spec=${spec}`
});
}
}
});
# 3.5.3 原子组件的约束
原子组件的运行环境与原子接口相互隔离,处于不同的上下文中,其可调用的接口能力也有所不同。原子组件存在以下特性与限制:
- 渲染区域有限:宽度随屏幕宽度变化,最小高度为宽高比 4:1,最大高度为宽高比 1:1,未超出最小/最大高度时随内容自动撑高;
- 初始化时决定卡片高度,后续不可再改变高度;
- 仅支持 tap 点击、image load、image error 事件,不支持其他交互事件;
- 默认不支持网络请求和云开发接口,需声明为「实时动态组件」;
- 默认不支持定时器接口(如 setTimeout、setInterval),需声明为「实时动态组件」;
- 不支持打开小程序的接口;
- 不支持动画;
- 禁止上下滚动(即禁止使用 overflow-y);
- 支持点击后代用户上行一条文本消息(
ModelContext.sendFollowUpMessage),效果等同于用户以文本消息发送; - 支持点击后打开半屏页面(见「半屏页面」)。
# 3.5.4 实时动态组件
对于需要展示实时动态内容的合理场景,可在 mcp.json 中声明实时动态能力(支持 ft.request、定时器等接口)。
{
"apis": [],
"components": [
{
"path": "path/to/comp",
"permissions": {
"scope.dynamic": {
"desc": "声明使用场景"
}
}
}
]
}
# 3.5.5 原子组件过期态
支持通过接口将已经渲染的原子组件置为过期态,防止用户再次点击。
1. 组件过期声明
在 mcp.json 的 components 字段下声明:
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
| path | string | 是 | 组件路径(相对于 SKILL 目录) |
| expirable | boolean | 否 | 声明该组件渲染的卡片是否可被置为过期,默认 false |
| expiredText | string | 否 | 过期后显示的文案,默认"服务已过期" |
{
"apis": [
{
"name": "searchRides",
"description": "搜索打车方案",
"_meta": { "ui": { "componentPath": "components/ride-card/index" } },
"inputSchema": {}
}
],
"components": [
{
"path": "components/ride-card/index",
"expirable": true,
"expiredText": "店铺已关闭"
}
]
}
2. 组件过期接口
提供两种粒度的过期 API:
方式一:ft.modelContext.expireAllCards()
ft.modelContext.expireAllCards(): Promise<{ errMsg: string }>
可在原子接口或原子组件中调用。所有声明了 expirable: true 的组件(包括自身)都会被标记为过期并渲染蒙层。同时支持按 componentPath 过滤,使所有相同 componentPath 的原子组件、或最近一个特定 componentPath 的原子组件过期:
// 过期特定组件的卡片(绝对路径)
ft.modelContext.expireAllCards({
componentPaths: ['pkgA/weatherSkill/components/weather-card/index']
});
// 只过期最近一张匹配的卡片
ft.modelContext.expireAllCards({
componentPaths: ['pkgA/weatherSkill/components/weather-card/index'],
match: 'latest'
});
方式二:ft.modelContext.getViewContext(this).expirePreviousCards()
const viewCtx = ft.modelContext.getViewContext(this);
viewCtx.expirePreviousCards(): Promise<{ errMsg: string }>
只能在原子组件内调用,之前渲染过且声明了 expirable: true 的原子组件会被标记为过期并渲染蒙层,同样支持按 componentPath 过滤。
3. 组件过期事件
原子组件被置为过期时会收到过期事件,组件内部可在此时做一些必要的清理:
Component({
lifetimes: {
created() {
const { NotificationType } = ft.modelContext;
const viewCtx = ft.modelContext.getViewContext(this);
viewCtx.on(NotificationType.Expire, (event) => {
console.log('卡片已过期', event.expiredText);
// 停止轮询、禁用按钮等清理逻辑
});
}
}
});
# 3.5.6 同步交互状态给模型
用户在原子组件卡片上进行交互操作(如点击按钮、选择选项等)修改卡片状态时,可以通过 updateModelContext 接口将状态变更同步给模型,以便模型感知用户的最新选择并作出后续响应。
Component({
methods: {
onOptionSelect(e) {
const { option } = e.currentTarget.dataset;
// 将用户选择同步给模型
const viewCtx = ft.modelContext.getViewContext(this);
viewCtx.updateModelContext({
content: [{ type: 'text', text: `用户选择了${option}` }]
});
}
}
});
参数说明:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| content | Array<{ type: 'text', text: string }> | 是 | 内容块数组,当前仅支持 text 类型 |