### Example Code
Source: https://miniapp.xiaohongshu.com/doc/DC559349
Provides a complete example of how to implement the App constructor with various lifecycle callbacks and global data.
```APIDOC
## Example Code
```javascript
App({
onLaunch (options) {
// Do something initial when launch.
},
onShow (options) {
// Do something when show.
},
onHide () {
// Do something when hide.
},
onError (msg) {
console.log(msg)
},
globalData: 'I am global data'
})
```
```
--------------------------------
### Complete ext.json Configuration Example
Source: https://miniapp.xiaohongshu.com/doc/DC641730
This is a comprehensive example of an ext.json file, showcasing all available configuration options for customizing authorized mini programs.
```json
{
"extEnable": true,
"extAppid": "EXT_APPID",
"directCommit": false,
"ext": {
"extAppid": "EXT_APPID"
},
"pages": ["pages/index/index", "pages/logs/logs"],
"extPages": {
"pages/logs/logs": {
"navigationBarTitleText": "logs"
}
},
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "Demo",
"navigationBarTextStyle": "black"
},
"tabBar": {
"list": [{
"pagePath": "pages/index/index",
"text": "首页"
}, {
"pagePath": "pages/logs/logs",
"text": "日志"
}]
},
"networkTimeout": {
"request": 10000,
"downloadFile": 10000
}
}
```
--------------------------------
### Basic Query Task Example
Source: https://miniapp.xiaohongshu.com/doc/DC878656
Demonstrates how to get an agent instance and retrieve task information using the queryTasks API. Ensure the agent is initialized before use.
```typescript
const agent = this.getAgent();
if (!agent) return;
const taskInfo = await agent.taskInfo();
console.log("res", agentInfo);
```
--------------------------------
### wan2.5-i2i-preview Basic Agent Call Example
Source: https://miniapp.xiaohongshu.com/doc/DC638640
This example demonstrates how to integrate the wan2.5-i2i-preview model through a custom Agent to achieve image-to-image / style transfer capabilities.
```javascript
async sendMessage(message) {
try {
const images = Array.isArray(message?.files) ? message.files.filter(f => f?.type === 'image' && f?.url) : [];
// At least 1 input image is required
if (!images.length) {
return {
code: -1,
msg: 'Please upload the image to be converted'
};
}
const contentParts = images.map(img => ({
type: 'image_url',
image_url: { url: img.url }
}));
contentParts.push({
type: 'text',
text: message?.msg || 'Please convert the image style according to the description'
});
// Create wan2.5-i2i-preview model
const model = this.createModel('wan2.5-i2i-preview');
const modelResponse = await model.streamText({
messages: [
{
role: 'user',
content: contentParts,
},
],
parameters: {
size: '1280*1280',
n: 1,
prompt_extend: false,
watermark: false,
seed: 12345
},
// negative_prompt is passed at the top level
negative_prompt: 'blurry, low quality, distorted, artifact, extra fingers, bad proportions'
});
// Stream back the generated image results
for await (const chunk of modelResponse) {
this.sseSender.send({ data: chunk });
}
this.sseSender.end();
} catch (error) {
console.error('wan2.5-i2i-preview stream error:', error);
this.sseSender.end();
}
}
```
--------------------------------
### Input Component Example
Source: https://miniapp.xiaohongshu.com/doc/DC222390
A basic example demonstrating the usage of the input component with common properties.
```xhsml
```
--------------------------------
### Basic Agent Call for Qwen-Image Text-to-Image Generation
Source: https://miniapp.xiaohongshu.com/doc/DC257487
This JavaScript example demonstrates how to integrate the qwen-image model using a custom Agent to generate images from text descriptions. It handles streaming responses, returning image URLs or base64 data. Ensure you have the necessary model creation and SSE sender setup.
```javascript
async sendMessage(message) {
try {
if (!message?.msg) {
return {
code: -1,
msg: '请输入图片描述'
};
}
// 创建 qwen-image 模型
const model = this.createModel('qwen-image');
const modelResponse = await model.streamText({
messages: [
{
role: 'user',
content: [
{ type: 'text', text: message.msg }
],
},
],
parameters: {
negative_prompt: '',
prompt_extend: true,
watermark: true,
size: '1328*1328'
}
});
// 流式返回图片 URL / base64
for await (const chunk of modelResponse) {
this.sseSender.send({ data: chunk });
}
this.sseSender.end();
} catch (error) {
console.error('qwen-image stream error:', error);
this.sseSender.end();
}
}
```
--------------------------------
### Basic Textarea Example
Source: https://miniapp.xiaohongshu.com/doc/DC507900
A simple example demonstrating the basic usage of the textarea component.
```xhsml
```
--------------------------------
### Getting Scroll Offset and Displaying in Modal
Source: https://miniapp.xiaohongshu.com/doc/DC661656
Retrieves the scroll offset of a scrollable element and displays the information in a modal dialog. This example also includes an IntersectionObserver setup.
```javascript
Page({
data: {
appear: false
},
onReady() {
this.intersectionObserver = xhs.createIntersectionObserver();
this.intersectionObserver
.relativeTo('.scroll-view')
.observe('.ball', res => {
console.log('observe', res);
this.setData('appear', res.intersectionRatio > 0);
});
},
getNodeRef() {
xhs.createSelectorQuery()
.select('.scroll-view')
.scrollOffset(res => {
console.log('scrollOffset:', res);
xhs.showModal({
title: 'scrollOffset',
content: JSON.stringify(res)
});
}).exec();
}
});
```
--------------------------------
### Get After-Sales Order Details Request Example
Source: https://miniapp.xiaohongshu.com/doc/DC492057
This is an example of a JSON request body to get the details of an after-sales order. Ensure all required parameters are included.
```json
{
"out_order_id":"string",
"out_after_sales_order_id":"string",
"open_id":"string"
}
```
--------------------------------
### Complete Example: Select and Upload File
Source: https://miniapp.xiaohongshu.com/doc/DC286553
A comprehensive example showing the process of selecting a file using `xhs.chooseSystemFile` and then uploading it via `agent.uploadOpenAiFile`. It includes success and error handling, updating the UI with toast messages and results, and storing uploaded file information. This example is suitable for integrating file uploads into your application.
```typescript
// 选择并上传文件
onUploadFile() {
const that = this;
xhs.chooseSystemFile({
type: 'all',
success: async (result) => {
try {
console.log('选择成功:', result);
const files = (result && result.tempFiles) || [];
const first = files[0] || {};
const filePath = first.path || first.tempFilePath;
if (!filePath) {
xhs.showToast({ title: '未获取到文件路径', icon: 'none' });
return;
}
const agent = that.getAgent();
const resp = await agent.uploadOpenAiFile({
filePath: filePath,
purpose: 'file-extract'
});
xhs.showToast({ title: '上传成功', icon: 'success' });
// 保存上传成功的文件信息
const data = (resp && resp.data) || resp || {};
const fileItem = {
id: data.id,
filename: data.filename,
purpose: data.purpose,
bytes: data.bytes,
fileSource: 'openai',
created_at: data.created_at
};
const uploadedFiles = [...that.data.uploadedFiles, fileItem];
that.setData({ uploadedFiles: uploadedFiles });
// 同步在结果面板展示上传结果
that.setData({
result: typeof resp === 'string' ? resp : JSON.stringify(resp, null, 2)
});
} catch (error) {
console.error('上传失败:', error);
const errMsg = (error && (error.errMsg || error.message)) || error;
that.setData({ result: '错误: ' + errMsg });
xhs.showToast({ title: errMsg || '上传失败', icon: 'none' });
}
},
fail: (error) => {
console.error('选择文件失败:', error);
const errMsg = (error && (error.errMsg || error.message)) || error;
that.setData({ result: '错误: ' + errMsg });
xhs.showToast({ title: errMsg || '选择文件失败', icon: 'none' });
}
});
}
```
--------------------------------
### Get Order Information Response Example
Source: https://miniapp.xiaohongshu.com/doc/DC723771
This is an example of a successful response from the 'Get Order Information' API. It details the order information, product details, pricing, and status.
```json
{
"data":{
"out_order_id":"string",
"open_id":"string",
"path":"string",
"biz_create_time":0,
"biz_update_time":0,
"order_expired_time":0,
"product_infos":[
{
"out_product_id":"string",
"out_sku_id":"string",
"num":0,
"sale_price":0,
"real_price":0,
"discount_infos":[
{
"name":"string",
"price":0,
"num":0
}
],
"image":"string"
}
],
"price_info":{
"order_price":0,
"freight_price":0,
"extra_price_infos":[
{
"name":"string",
"price":0,
"num":0
}
]
},
"status":0,
"open_pay_type":"string"
},
"success":true,
"msg":"string",
"code":0
}
```
--------------------------------
### Draw Points and Quadratic Curve with Guides
Source: https://miniapp.xiaohongshu.com/doc/DC445555
This example illustrates drawing various points, guide lines, and a quadratic Bezier curve on a canvas. It uses `xhs.createCanvasContext` and `quadraticCurveTo`, setting different colors for points, guides, and the curve.
```js
Page({
onReady: function () {
const ctx = xhs.createCanvasContext('myCanvas')
// Draw points
ctx.beginPath()
ctx.arc(20, 20, 2, 0, 2 * Math.PI)
ctx.setFillStyle('red')
ctx.fill()
ctx.beginPath()
ctx.arc(200, 20, 2, 0, 2 * Math.PI)
ctx.setFillStyle('lightgreen')
ctx.fill()
ctx.beginPath()
ctx.arc(20, 100, 2, 0, 2 * Math.PI)
ctx.setFillStyle('blue')
ctx.fill()
ctx.setFillStyle('black')
ctx.setFontSize(12)
// Draw guides
ctx.beginPath()
ctx.moveTo(20, 20)
ctx.lineTo(20, 100)
ctx.lineTo(200, 20)
ctx.setStrokeStyle('#AAAAAA')
ctx.stroke()
// Draw quadratic curve
ctx.beginPath()
ctx.moveTo(20, 20)
ctx.quadraticCurveTo(20, 100, 200, 20)
ctx.setStrokeStyle('black')
ctx.stroke()
ctx.draw()
}
});
```
--------------------------------
### Choose System File Example
Source: https://miniapp.xiaohongshu.com/doc/DC457198
This snippet demonstrates how to use the xhs.chooseSystemFile API to allow users to select all types of files. It includes success and fail callbacks to handle the results and display feedback to the user.
```javascript
xhs.chooseSystemFile({
type: "all",
success: (result) => {
console.log('选择成功:', result);
this.setData({
resultInfo: JSON.stringify(result, null, 2)
});
xhs.showToast({
title: `成功选择${result.tempFiles?.length || 0}个文件`,
icon: 'success'
});
},
fail: (error) => {
console.error('选择文件失败:', error);
this.setData({
resultInfo: `错误: ${error.errMsg || error.message || error}`
});
xhs.showToast({
title: error.errMsg || error.message || '选择文件失败',
icon: 'none'
});
}
}
);
```
--------------------------------
### Draw Cubic Bezier Curve with Guides
Source: https://miniapp.xiaohongshu.com/doc/DC221438
Illustrates drawing a cubic Bezier curve along with guide lines and control points for visualization. This example requires a canvas context and demonstrates drawing arcs for points and lines for guides.
```javascript
Page({
onLoad() {
const ctx = xhs.createCanvasContext('myCanvas')
// Draw points
ctx.beginPath()
ctx.arc(20, 20, 2, 0, 2 * Math.PI)
ctx.setFillStyle('red')
ctx.fill()
ctx.beginPath()
ctx.arc(200, 20, 2, 0, 2 * Math.PI)
ctx.setFillStyle('lightgreen')
ctx.fill()
ctx.beginPath()
ctx.arc(20, 100, 2, 0, 2 * Math.PI)
ctx.arc(200, 100, 2, 0, 2 * Math.PI)
ctx.setFillStyle('blue')
ctx.fill()
ctx.setFillStyle('black')
ctx.setFontSize(12)
// Draw guides
ctx.beginPath()
ctx.moveTo(20, 20)
ctx.lineTo(20, 100)
ctx.lineTo(150, 75)
ctx.moveTo(200, 20)
ctx.lineTo(200, 100)
ctx.lineTo(70, 75)
ctx.setStrokeStyle('#AAAAAA')
ctx.stroke()
// Draw quadratic curve
ctx.beginPath()
ctx.moveTo(20, 20)
ctx.bezierCurveTo(20, 100, 200, 100, 200, 20)
ctx.setStrokeStyle('black')
ctx.stroke()
ctx.draw()
}
});
```
--------------------------------
### Get Chat Records Example
Source: https://miniapp.xiaohongshu.com/doc/DC569737
This example demonstrates how to fetch conversations and then retrieve historical messages for the first conversation using the agent. It includes error handling for API calls.
```typescript
// 获取历史记录
async getChatRecords() {
const agent = this.getAgent();
if (!agent) return;
const response = await agent.getConversations();
console.log("=== conversations", response);
if (response.code !== 0) {
xhs.showToast({
title: "获取历史记录失败",
icon: "none",
});
return;
}
const conversations = response.data.conversations;
if (conversations && conversations.length > 0) {
const res = await agent.getHistoryMessages({
conversation_id: conversations[0].id,
cursor: 1,
count: 10,
sort: "desc",
});
console.log("=== getHistoryMessages", res);
}
}
```
--------------------------------
### Page Configuration Example
Source: https://miniapp.xiaohongshu.com/doc/DC785655
This JSON snippet demonstrates how to configure the navigation bar, background color, and text style for a specific mini-program page. These settings override global configurations.
```json
{
"navigationBarBackgroundColor": "#ffffff",
"navigationBarTextStyle": "black",
"navigationBarTitleText": "小红书接口功能演示",
"backgroundColor": "#eeeeee",
"backgroundTextStyle": "light"
}
```
--------------------------------
### Get After-Sales Order Details Response Example
Source: https://miniapp.xiaohongshu.com/doc/DC492057
This is an example of a successful JSON response when retrieving after-sales order details. It includes order status, pricing, product information, and more.
```json
{
"data":{
"status":0,
"out_order_id":"string",
"out_after_sales_order_id":"string",
"open_id":"string",
"type":0,
"reason":"string",
"biz_create_time":0,
"price_info":{
"refund_price":0,
"freight_price":0,
"extra_price_infos":[
{
"name":"string",
"price":0,
"num":0
}
]
},
"product_infos":[
{
"out_product_id":"string",
"out_sku_id":"string",
"num":0,
"price":0
}
],
"refund_voucher_detail":[
{
"voucher_code":"string",
"refund_price":0
}
],
"refund_book_detail":[
{
"book_id":"string",
"refund_price":0
}
],
"product_type":0,
"auto_confirm":true
},
"success":true,
"msg":"string",
"code":0
}
```
--------------------------------
### Qwen3-Doc-Turbo Basic Agent Call Example
Source: https://miniapp.xiaohongshu.com/doc/DC165982
Example demonstrating how to integrate the Qwen3-Doc-Turbo model using a custom Agent for document parsing and Q&A capabilities.
```APIDOC
## Usage Example
### Qwen3-Doc-Turbo Basic Agent Call Example
This example shows how to use the `qwen3-doc-turbo` model with a custom Agent to achieve document analysis and Q&A capabilities.
```javascript
async sendMessage(message) {
try {
// Simple parameter validation
if (!message?.files?.[0]?.url) {
return {
code: -1,
msg: 'Please upload the document to be analyzed'
};
}
// Create qwen3-doc-turbo model
const model = this.createModel('qwen3-doc-turbo');
const modelResponse = await model.generateText({
messages: [
{
role: 'system',
content: 'You are a document analysis assistant. Please analyze the document content according to the user\'s needs.'
},
{
role: 'user',
content: [
{ type: 'text', text: message?.msg || 'Please help me analyze this document' },
{
type: 'doc_url',
doc_url: [message.files[0].url],
file_parsing_strategy: 'auto'
}
]
}
]
});
// Non-streaming: Directly return model output
return modelResponse;
} catch (error) {
console.error('qwen3-doc-turbo error:', error);
return {
code: -1,
msg: 'Document analysis failed, please try again later'
};
}
}
```
```
--------------------------------
### Get Conversations Example
Source: https://miniapp.xiaohongshu.com/doc/DC599507
This snippet demonstrates how to call the getConversations API to retrieve a list of conversations. Ensure you have an agent instance before calling this method.
```typescript
const agent = this.getAgent();
if (!agent) return;
const agentInfo = await agent.getConversations();
console.log("res", agentInfo);
```
--------------------------------
### Example Usage of chooseVideo
Source: https://miniapp.xiaohongshu.com/doc/DC281730
Demonstrates how to call the chooseVideo function with specific options and handle the returned video data. This example shows how to set source type, compression, camera, and maximum duration, and then logs the results or errors.
```javascript
// 调用示例
chooseVideo({
sourceType: ['album', 'camera'], // 指定来源
compressed: true, // 是否压缩
camera: 'back', // 默认后置摄像头
maxDuration: 30, // 最大时长 30 秒
})
.then((res) => {
console.log('视频选择成功:', res);
// 处理返回结果
console.log('临时文件路径:', res.tempFilePath);
console.log('视频时长:', res.duration);
console.log('视频大小:', res.size);
console.log('视频宽度:', res.width);
console.log('视频高度:', res.height);
})
.catch((err) => {
console.error('视频选择失败:', err);
});
```
--------------------------------
### Get Gpay Order Info Response Example
Source: https://miniapp.xiaohongshu.com/doc/DC510914
This JSON object illustrates a successful response from the 'get gpay order info' API. It includes order details, payment information, voucher details, booking information, product details, and discount information.
```json
{
"data":{
"order_id":"string",
"pay_amount":0,
"order_status":0,
"voucher_infos":[
{
"voucher_code":"string",
"voucher_status":0,
"pay_amount":0,
"biz_id":"string"
}
],
"book_details":[
{
"book_id":"string",
"voucher_code":"string",
"book_status":0
}
],
"product_infos":[
{
"out_product_id":"string",
"out_sku_id":"string",
"num":0,
"sale_price":0,
"real_price":0,
"image":"string",
"discount_infos":[
{
"name":"string",
"price":0,
"num":0
}
]
}
],
"third_trade_no":"string",
"pay_channel":0
},
"success":true,
"msg":"string",
"code":0
}
```
--------------------------------
### Qwen-Image-2.0 Basic Agent Call Example
Source: https://miniapp.xiaohongshu.com/doc/DC577944
Provides a JavaScript example demonstrating how to use the Qwen-Image-2.0 model with the SDK for basic agent calls. It shows how to create a model instance, send a streaming text request with specified parameters, and handle the streamed response.
```javascript
async sendMessage(message) {
try {
if (!message?.msg) {
return { code: -1, msg: "Please enter an image description" };
}
const model = this.createModel("qwen-image-2.0");
const modelResponse = await model.streamText({
messages: [
{
role: "user",
content: [{ type: "text", text: message.msg }],
},
],
parameters: {
size: "2048*2048",
n: 1,
prompt_extend: true,
watermark: false,
},
negative_prompt: "blurry, low quality, deformed, distorted",
});
for await (const chunk of modelResponse) {
this.sseSender.send({ data: chunk });
}
this.sseSender.end();
} catch (error) {
console.error("qwen-image-2.0 stream error:", error);
this.sseSender.end();
}
}
```
--------------------------------
### xhs.followOfficialAccount
Source: https://miniapp.xiaohongshu.com/doc/DC437650
Guides users to follow a Xiaohongshu shop. This method is supported starting from basic library version 3.28.0 and can only be used within a bindtap event.
```APIDOC
## xhs.followOfficialAccount
### Description
This API is used to guide users to follow a Xiaohongshu shop. It requires a basic library version of 3.28.0 or higher and is intended to be called within a `bindtap` event.
### Method
`xhs.followOfficialAccount(options)`
### Parameters
#### Options Object
- **success** (Function) - Optional - Callback function executed when the API call is successful. Minimum supported version: 3.28.0.
- **fail** (Function) - Optional - Callback function executed when the API call fails. Minimum supported version: 3.28.0.
- **complete** (Function) - Optional - Callback function executed when the API call finishes, regardless of success or failure. Minimum supported version: 3.28.0.
### Callbacks
#### Success Response
- **errMsg** (string) - Indicates success, typically "followOfficialAccount:ok". Minimum supported version: 3.28.0.
- **status** (number) - The status code of the operation. Minimum supported version: 3.28.0.
##### Status Code Meanings:
- **0**: Follow successful.
- **1**: Already following.
- **2**: Follow failed.
- **3**: Error obtaining follow status.
#### Failure Response
- **errMsg** (string) - Indicates failure, formatted as "followOfficialAccount:fail + error message". Minimum supported version: 3.28.0.
### Code Example
```javascript
xhs.followOfficialAccount({
success(res) {
if (res.status === 0) {
console.log("关注成功");
} else {
console.log(res.errMsg);
}
},
});
```
### Notes
- **Tip**: This API can only be used within a `bindtap` event.
- Xiaohongshu does not currently provide a way to query user follow status directly.
```
--------------------------------
### Qwen-Image Basic Agent Call Example
Source: https://miniapp.xiaohongshu.com/doc/DC257487
Example demonstrating how to integrate the Qwen-Image model using a custom Agent to achieve text-to-image generation capabilities.
```javascript
async sendMessage(message) {
try {
if (!message?.msg) {
return {
code: -1,
msg: '请输入图片描述'
};
}
// Create qwen-image model
const model = this.createModel('qwen-image');
const modelResponse = await model.streamText({
messages: [
{
role: 'user',
content: [
{ type: 'text', text: message.msg },
],
},
],
parameters: {
negative_prompt: '',
prompt_extend: true,
watermark: true,
size: '1328*1328'
}
});
// Stream image URL / base64
for await (const chunk of modelResponse) {
this.sseSender.send({ data: chunk });
}
this.sseSender.end();
} catch (error) {
console.error('qwen-image stream error:', error);
this.sseSender.end();
}
}
```
--------------------------------
### Start Location Update with Promise
Source: https://miniapp.xiaohongshu.com/doc/DC291240
This example demonstrates how to use the xhs.startLocationUpdate API with a Promise-style interface. It resolves with success data or rejects with error information.
```javascript
function startLocationUpdate() {
return new Promise((resolve, reject) => {
xhs.startLocationUpdate({
success: (res) => resolve(res),
fail: (err) => reject(err),
});
});
}
startLocationUpdate()
.then((res) => {
console.log('位置更新开启成功:', res.errMsg);
})
.catch((err) => {
console.error('位置更新开启失败:', err);
});
```
--------------------------------
### Create a Simple Agent Class (Server-side)
Source: https://miniapp.xiaohongshu.com/doc/DC254985
Implement a basic Agent class extending AgentRuntime for handling messages and interacting with models. This example shows how to process files, construct messages, and stream responses from the qwen-doc-turbo model.
```typescript
const { AgentRuntime, AgentDriver } = require("@vectorx/agent-runtime");
/**
* @typedef {import('@vectorx/agent-runtime').IAgent} IAgent
*
* @class
* @implements {IAgent}
*/
class MyAgent extends AgentRuntime {
async sendMessage(message) {
try {
// 创建 qwen-doc-turbo 模型
const model = this.createModel("qwen-doc-turbo");
// 组装消息数组
const messages = [];
// 1. 处理文件:根据 fileSource 区分处理
if (Array.isArray(message?.files) && message.files.length > 0) {
message.files.forEach((file) => {
if (file.fileSource === "openai") {
// OpenAI 上传的文件:使用 file-id,通过 system role 传入
const fileId = file.id;
if (fileId) {
messages.push({
role: "system",
content: `fileid://${fileId}`,
});
}
} else if (file.fileSource === "standard" || !file.fileSource) {
// 标准上传的文件:使用 URL,通过 user content 中的 doc_url 传入
// 注意:标准上传的文件会在 user message 的 content 中处理
}
});
}
// 2. 添加 user 消息
const userContent = [];
// 2.1 添加标准上传的文件(doc_url)
if (Array.isArray(message?.files) && message.files.length > 0) {
message.files.forEach((file) => {
if ((file.fileSource === "standard" || !file.fileSource) && file.url) {
userContent.push({
"type": "doc_url",
doc_url: [file.url],
});
}
});
}
// 2.2 添加用户文本提示
const userPrompt = message?.msg || "请分析这个文档";
if (userPrompt.trim()) {
userContent.push({
"type": "text",
text: userPrompt.trim(),
});
}
messages.push({
role: "user",
content: userContent,
});
// 3. 调用模型
const modelResponse = await model.streamText({
messages,
parameters: {
temperature: 0.3,
max_tokens: 2000,
},
enable_thinking: true,
});
// 4. 流式返回结果
for await (const chunk of modelResponse) {
this.sseSender.send({ data: chunk });
}
this.sseSender.end();
} catch (error) {
console.error("qwen-doc-turbo stream error:", error);
this.sseSender.end();
}
}
}
exports.main = function (event, context) {
return AgentDriver.run(event, context, new MyAgent(context));
};
```
--------------------------------
### Qwen-Turbo Basic Agent Call Example
Source: https://miniapp.xiaohongshu.com/doc/DC753845
This example demonstrates how to integrate the qwen-turbo model using a custom Agent for text generation and conversational Q&A. It handles basic input validation and uses a streaming response.
```javascript
async sendMessage(message) {
try {
// 简单的参数校验
if (!message?.msg) {
return {
code: -1,
msg: '请输入问题或描述'
};
}
// 创建 qwen-turbo 模型
const model = this.createModel('qwen-turbo');
const modelResponse = await model.streamText({
messages: [
{
role: 'user',
content: [
{
type: 'text',
text: message.msg
}
],
},
]
});
// 流式返回:分片为标准化的 text 类型,content 为模型输出内容
for await (const chunk of modelResponse) {
this.sseSender.send({ data: chunk });
}
this.sseSender.end();
} catch (error) {
console.error('qwen-turbo stream error:', error);
this.sseSender.end();
}
}
```
--------------------------------
### Picker Component - Time Selector Mode
Source: https://miniapp.xiaohongshu.com/doc/DC910522
Example of using the 'picker' component for selecting a time. It allows setting start and end times and displays the selected time.
```xml
当前时间: {{time}}
```
--------------------------------
### Time Picker Example
Source: https://miniapp.xiaohongshu.com/doc/DC281806
Demonstrates the time picker. It allows users to select a specific time. The `start` and `end` attributes can be used to set the selectable time range.
```xml
当前时间: {{time}}
```
--------------------------------
### Qwen Sketch-to-Image Agent Example
Source: https://miniapp.xiaohongshu.com/doc/DC520677
Example of integrating the Qwen Sketch-to-Image model into a custom Agent for sketch-to-image generation. Demonstrates how to send messages with image files and text prompts, and configure model parameters.
```APIDOC
## Qwen Sketch-to-Image Agent Example
### Description
This example demonstrates how to use a custom Agent to integrate the `qwen-sketch-to-image` model for sketch-to-image generation. It shows the process of sending messages containing sketch images and text prompts, and configuring generation parameters like style, number of images, sketch weight, and edge extraction.
### Code Example (JavaScript)
```javascript
async sendMessage(message) {
try {
// Ensure a sketch image is uploaded
if (!message?.files?.[0]?.url) {
return {
code: -1,
msg: 'Please upload a sketch image'
};
}
const contentParts = [
{
type: 'image_url',
image_url: { url: message.files[0].url }
}
];
if (message?.msg) {
contentParts.push({
type: 'text',
text: message.msg
});
}
// Create the qwen-sketch-to-image model instance
const model = this.createModel('qwen-sketch-to-image');
const modelResponse = await model.generateText({
messages: [
{
role: 'user',
content: contentParts,
},
],
parameters: {
style: '', // Example: watercolor style
n: 1, // Generate 1 image
sketch_weight: 9, // Sketch weight
sketch_extraction: true // Enable edge extraction
}
});
// Non-streaming: return the generated image result directly
return modelResponse;
} catch (error) {
console.error('qwen-sketch-to-image error:', error);
return {
code: -1,
msg: 'Sketch-to-image generation failed, please try again later'
};
}
}
```
### Usage Notes
- The `sendMessage` function expects a `message` object that includes a `files` array with the sketch image URL and an optional `msg` property for the text prompt.
- The `createModel` function is assumed to be a method available in the Agent's context for initializing the model.
- The `generateText` method is used to call the model with the prepared messages and parameters.
- The response from `generateText` is directly returned for non-streaming scenarios.
```
--------------------------------
### Multiple Function Configuration Example
Source: https://miniapp.xiaohongshu.com/doc/DC533610
Demonstrates configuring multiple cloud functions, each with its own name, directory, source file, and unique trigger path.
```json
{
"functionsRoot": "./src",
"functions": [
{
"name": "userProfile",
"directory": "./user",
"source": "index.js",
"triggerPath": "/user/profile"
},
{
"name": "booksList",
"directory": "./books",
"source": "index.js",
"triggerPath": "/books/list"
}
]
}
```
--------------------------------
### Picker Component - Date Selector Mode (Year)
Source: https://miniapp.xiaohongshu.com/doc/DC910522
Example of using the 'picker' component for selecting a year. It allows setting start and end years and displays the selected year.
```xml
当前选择日期: {{year}}
```
--------------------------------
### Qwen-Style-Repaint-V1 Basic Agent Call Example
Source: https://miniapp.xiaohongshu.com/doc/DC301756
Provides a JavaScript example demonstrating how to integrate the qwen-style-repaint-v1 model using a custom Agent for image repainting and style transfer capabilities.
```APIDOC
## Usage Example
### Qwen-Style-Repaint-V1 Basic Agent Call Example
The following example shows how to access the `qwen-style-repaint-v1` model through a custom Agent to implement **image repainting / style transfer** capabilities.
```javascript
async sendMessage(message) {
try {
// Image input is required
if (!message?.files?.[0]?.url) {
return {
code: -1,
msg: 'Please upload the image to be repainted'
};
}
// Parse style index from message (optional)
let styleIndex = 3;
if (message?.msg) {
const match = message.msg.match(/style_index:\s*(\d+)/);
if (match && match[1]) {
styleIndex = parseInt(match[1], 10) || 3;
}
}
// Create qwen-style-repaint-v1 model
const model = this.createModel('qwen-style-repaint-v1');
const modelResponse = await model.generateText({
messages: [
{
role: 'user',
content: [
{
type: 'image_url',
image_url: { url: message.files[0].url }
}
],
},
],
parameters: {
style_index: styleIndex
}
});
// Non-streaming: directly return model output (image URL / base64)
return modelResponse;
} catch (error) {
console.error('qwen-style-repaint-v1 error:', error);
return {
code: -1,
msg: 'Image repainting failed, please try again later'
};
}
}
```
```
--------------------------------
### Picker Component - Date Selector Mode (Month)
Source: https://miniapp.xiaohongshu.com/doc/DC910522
Example of using the 'picker' component for selecting a month. It allows setting start and end months and displays the selected month.
```xml
当前选择日期: {{month}}
```
--------------------------------
### Get Gpay Order Info Request Example
Source: https://miniapp.xiaohongshu.com/doc/DC510914
This JSON object demonstrates the structure for requesting order information for a guaranteed payment. Ensure all required fields are populated correctly.
```json
{
"out_order_id":"string",
"open_id":"string",
"order_type":0,
"ext_info":"string"
}
```
--------------------------------
### qwen-turbo Basic Agent Call Example
Source: https://miniapp.xiaohongshu.com/doc/DC753845
Demonstrates how to integrate the qwen-turbo model through a custom Agent to achieve text generation and conversational Q&A capabilities.
```javascript
async sendMessage(message) {
try {
// Simple parameter validation
if (!message?.msg) {
return {
code: -1,
msg: 'Please enter a question or description'
};
}
// Create qwen-turbo model
const model = this.createModel('qwen-turbo');
const modelResponse = await model.streamText({
messages: [
{
role: 'user',
content: [
{
type: 'text',
text: message.msg
}
],
},
]
});
// Streamed return: chunks are standardized text types, content is model output
for await (const chunk of modelResponse) {
this.sseSender.send({ data: chunk });
}
this.sseSender.end();
} catch (error) {
console.error('qwen-turbo stream error:', error);
this.sseSender.end();
}
}
```
--------------------------------
### wan2.5-i2i-preview Basic Agent Call Example
Source: https://miniapp.xiaohongshu.com/doc/DC638640
This JavaScript snippet demonstrates how to integrate the wan2.5-i2i-preview model using a custom Agent for image-to-image transformations and style transfer. It requires at least one input image and a text prompt. The response is streamed back.
```javascript
async sendMessage(message) {
try {
const images =
Array.isArray(message?.files)
? message.files.filter(f => f?.type === 'image' && f?.url)
: [];
// 至少需要 1 张输入图片
if (!images.length) {
return {
code: -1,
msg: '请上传待转换的图片'
};
}
const contentParts = images.map(img => ({
type: 'image_url',
image_url: { url: img.url }
}));
contentParts.push({
type: 'text',
text: message?.msg || '请根据描述对图片进行风格转换'
});
// 创建 wan2.5-i2i-preview 模型
const model = this.createModel('wan2.5-i2i-preview');
const modelResponse = await model.streamText({
messages: [
{
role: 'user',
content: contentParts,
},
],
parameters: {
size: '1280*1280',
n: 1,
prompt_extend: false,
watermark: false,
seed: 12345
},
// negative_prompt 在顶层传入
negative_prompt: '模糊, 低质量, 变形, 失真, 多余的手指, 比例不良'
});
// 流式返回生成的图片结果
for await (const chunk of modelResponse) {
this.sseSender.send({ data: chunk });
}
this.sseSender.end();
} catch (error) {
console.error('wan2.5-i2i-preview stream error:', error);
this.sseSender.end();
}
}
```
--------------------------------
### Get Agent Info in Simulator
Source: https://miniapp.xiaohongshu.com/doc/DC202641
Example of how to fetch agent information using the apiService in the agent simulator's frontend code. Handles potential errors during the fetch operation.
```javascript
// 在智能体模拟器的前端代码中使用
import { apiService } from './services/agent-service';
// 获取智能体信息
async function fetchAgentInfo() {
try {
const agentInfo = await apiService.getAgentInfo();
console.log('智能体名称:', agentInfo.name);
console.log('智能体ID:', agentInfo.agentId);
console.log('服务器地址:', agentInfo.agentServerUrl);
return agentInfo;
} catch (error) {
console.error('获取智能体信息失败:', error);
throw error;
}
}
```
--------------------------------
### Picker Component - Date Selector Mode (Day)
Source: https://miniapp.xiaohongshu.com/doc/DC910522
Example of using the 'picker' component for selecting a specific day. It allows setting start and end dates and displays the selected date.
```xml
当前选择日期: {{date}}
```
--------------------------------
### qwen-image-2.0-pro Basic Agent Call Example
Source: https://miniapp.xiaohongshu.com/doc/DC252789
Example of how to use the qwen-image-2.0-pro model for basic agent calls, demonstrating asynchronous message sending with streaming responses.
```javascript
async sendMessage(message) {
try {
if (!message?.msg) {
return { code: -1, msg: "请输入图片描述" };
}
const model = this.createModel("qwen-image-2.0-pro");
const modelResponse = await model.streamText({
messages: [
{
role: "user",
content: [{ type: "text", text: message.msg }],
},
],
parameters: {
size: "2048*2048",
n: 1,
prompt_extend: true,
watermark: false,
},
negative_prompt: "模糊, 低质量, 变形, 失真",
});
for await (const chunk of modelResponse) {
this.sseSender.send({ data: chunk });
}
this.sseSender.end();
} catch (error) {
console.error("qwen-image-2.0-pro stream error:", error);
this.sseSender.end();
}
}
```
--------------------------------
### Calling xhs.chooseMedia with Options
Source: https://miniapp.xiaohongshu.com/doc/DC548119
Example demonstrating how to invoke the Promise-wrapped chooseMedia function with various configuration options. It shows how to handle the resolved success data and rejected error.
```javascript
// 调用示例
chooseMedia({
count: 5, // 最多选择 5 个文件
mediaType: ['image', 'video'], // 支持图片和视频
sourceType: ['album', 'camera'], // 来源为相册和相机
maxDuration: 15, // 拍摄视频最长 15 秒
sizeType: ['original', 'compressed'], // 支持原图和压缩图
camera: 'back', // 使用后置摄像头
})
.then((res) => {
console.log('选择成功:', res);
res.tempFiles.forEach((file) => {
console.log('文件路径:', file.tempFilePath);
console.log('文件大小:', file.size);
});
console.log('文件类型:', res.type); // image 或 video
})
.catch((err) => {
console.error('选择失败:', err);
});
```
--------------------------------
### Qwen-Image-2.0-Pro Basic Agent Call Example
Source: https://miniapp.xiaohongshu.com/doc/DC252789
This JavaScript snippet demonstrates how to use the Qwen-Image-2.0-Pro model for image generation via a streaming API. Ensure you have the necessary model creation and SSE sender setup.
```javascript
async sendMessage(message) {
try {
if (!message?.msg) {
return { code: -1, msg: "请输入图片描述" };
}
const model = this.createModel("qwen-image-2.0-pro");
const modelResponse = await model.streamText({
messages: [
{
role: "user",
content: [{ type: "text", text: message.msg }],
},
],
parameters: {
size: "2048*2048",
n: 1,
prompt_extend: true,
watermark: false,
},
negative_prompt: "模糊, 低质量, 变形, 失真",
});
for await (const chunk of modelResponse) {
this.sseSender.send({ data: chunk });
}
this.sseSender.end();
} catch (error) {
console.error("qwen-image-2.0-pro stream error:", error);
this.sseSender.end();
}
}
```
--------------------------------
### Date Picker Examples (Day, Month, Year)
Source: https://miniapp.xiaohongshu.com/doc/DC281806
Illustrates the date picker with options to select by day, month, or year. The `start` and `end` attributes define the valid date range. The `fields` attribute controls the granularity of selection.
```xml
当前选择日期: {{date}}当前选择日期: {{month}}当前选择日期: {{year}}
```