home / skills / tencentcloudbase / cloudbase-mcp / ai-model-wechat

This skill enables WeChat Mini Programs to generate and stream AI text using wx.cloud.extend.AI for real-time, interactive responses.

npx playbooks add skill tencentcloudbase/cloudbase-mcp --skill ai-model-wechat

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
5.7 KB
---
name: ai-model-wechat
description: Use this skill when developing WeChat Mini Programs (小程序, 企业微信小程序, wx.cloud-based apps) that need AI capabilities. Features text generation (generateText) and streaming (streamText) with callback support (onText, onEvent, onFinish) via wx.cloud.extend.AI. Built-in models include Hunyuan (hunyuan-2.0-instruct-20251111 recommended) and DeepSeek (deepseek-v3.2 recommended). API differs from JS/Node SDK - streamText requires data wrapper, generateText returns raw response. NOT for browser/Web apps (use ai-model-web), Node.js backend (use ai-model-nodejs), or image generation (not supported).
alwaysApply: false
---

## When to use this skill

Use this skill for **calling AI models in WeChat Mini Program** using `wx.cloud.extend.AI`.

**Use it when you need to:**

- Integrate AI text generation in a Mini Program
- Stream AI responses with callback support
- Call Hunyuan models from WeChat environment

**Do NOT use for:**

- Browser/Web apps → use `ai-model-web` skill
- Node.js backend or cloud functions → use `ai-model-nodejs` skill
- Image generation → use `ai-model-nodejs` skill (not available in Mini Program)
- HTTP API integration → use `http-api` skill

---

## Available Providers and Models

CloudBase provides these built-in providers and models:

| Provider | Models | Recommended |
|----------|--------|-------------|
| `hunyuan-exp` | `hunyuan-turbos-latest`, `hunyuan-t1-latest`, `hunyuan-2.0-thinking-20251109`, `hunyuan-2.0-instruct-20251111` | ✅ `hunyuan-2.0-instruct-20251111` |
| `deepseek` | `deepseek-r1-0528`, `deepseek-v3-0324`, `deepseek-v3.2` | ✅ `deepseek-v3.2` |

---

## Prerequisites

- WeChat base library **3.7.1+**
- No extra SDK installation needed

---

## Initialization

```js
// app.js
App({
  onLaunch: function() {
    wx.cloud.init({ env: "<YOUR_ENV_ID>" });
  }
})
```

---

## generateText() - Non-streaming

⚠️ **Different from JS/Node SDK:** Return value is raw model response.

```js
const model = wx.cloud.extend.AI.createModel("hunyuan-exp");

const res = await model.generateText({
  model: "hunyuan-2.0-instruct-20251111",  // Recommended model
  messages: [{ role: "user", content: "你好" }],
});

// ⚠️ Return value is RAW model response, NOT wrapped like JS/Node SDK
console.log(res.choices[0].message.content);  // Access via choices array
console.log(res.usage);                        // Token usage
```

---

## streamText() - Streaming

⚠️ **Different from JS/Node SDK:** Must wrap parameters in `data` object, supports callbacks.

```js
const model = wx.cloud.extend.AI.createModel("hunyuan-exp");

// ⚠️ Parameters MUST be wrapped in `data` object
const res = await model.streamText({
  data: {                              // ⚠️ Required wrapper
    model: "hunyuan-2.0-instruct-20251111",  // Recommended model
    messages: [{ role: "user", content: "hi" }]
  },
  onText: (text) => {                  // Optional: incremental text callback
    console.log("New text:", text);
  },
  onEvent: ({ data }) => {             // Optional: raw event callback
    console.log("Event:", data);
  },
  onFinish: (fullText) => {            // Optional: completion callback
    console.log("Done:", fullText);
  }
});

// Async iteration also available
for await (let str of res.textStream) {
  console.log(str);
}

// Check for completion with eventStream
for await (let event of res.eventStream) {
  console.log(event);
  if (event.data === "[DONE]") {       // ⚠️ Check for [DONE] to stop
    break;
  }
}
```

---

## API Comparison: JS/Node SDK vs WeChat Mini Program

| Feature | JS/Node SDK | WeChat Mini Program |
|---------|-------------|---------------------|
| **Namespace** | `app.ai()` | `wx.cloud.extend.AI` |
| **generateText params** | Direct object | Direct object |
| **generateText return** | `{ text, usage, messages }` | Raw: `{ choices, usage }` |
| **streamText params** | Direct object | ⚠️ Wrapped in `data: {...}` |
| **streamText return** | `{ textStream, dataStream }` | `{ textStream, eventStream }` |
| **Callbacks** | Not supported | `onText`, `onEvent`, `onFinish` |
| **Image generation** | Node SDK only | Not available |

---

## Type Definitions

### streamText() Input

```ts
interface WxStreamTextInput {
  data: {                              // ⚠️ Required wrapper object
    model: string;
    messages: Array<{
      role: "user" | "system" | "assistant";
      content: string;
    }>;
  };
  onText?: (text: string) => void;     // Incremental text callback
  onEvent?: (prop: { data: string }) => void;  // Raw event callback
  onFinish?: (text: string) => void;   // Completion callback
}
```

### streamText() Return

```ts
interface WxStreamTextResult {
  textStream: AsyncIterable<string>;   // Incremental text stream
  eventStream: AsyncIterable<{         // Raw event stream
    event?: unknown;
    id?: unknown;
    data: string;                      // "[DONE]" when complete
  }>;
}
```

### generateText() Return

```ts
// Raw model response (OpenAI-compatible format)
interface WxGenerateTextResponse {
  id: string;
  object: "chat.completion";
  created: number;
  model: string;
  choices: Array<{
    index: number;
    message: {
      role: "assistant";
      content: string;
    };
    finish_reason: string;
  }>;
  usage: {
    prompt_tokens: number;
    completion_tokens: number;
    total_tokens: number;
  };
}
```

---

## Best Practices

1. **Check base library version** - Ensure 3.7.1+ for AI support
2. **Use callbacks for UI updates** - `onText` is great for real-time display
3. **Check for [DONE]** - When using `eventStream`, check `event.data === "[DONE]"` to stop
4. **Handle errors gracefully** - Wrap AI calls in try/catch
5. **Remember the `data` wrapper** - streamText params must be wrapped in `data: {...}`

Overview

This skill provides a lightweight TypeScript interface for calling AI models from WeChat Mini Programs using wx.cloud.extend.AI. It exposes text generation (generateText) and streaming (streamText) with callback hooks (onText, onEvent, onFinish) and supports built-in CloudBase models like Hunyuan and DeepSeek. Use it to add conversational or generative text features directly inside Mini Program clients without extra SDK installs.

How this skill works

Initialize wx.cloud in your App and create a model via wx.cloud.extend.AI.createModel(provider). generateText returns the raw model response (choices + usage) similar to OpenAI chat completions. streamText requires parameters wrapped in a data object, provides textStream and eventStream async iterables, and supports onText/onEvent/onFinish callbacks for incremental updates. Recommended models include hunyuan-2.0-instruct-20251111 and deepseek-v3.2.

When to use it

  • Add chat or assistant text generation inside a WeChat Mini Program (wx or enterprise wx).
  • Stream partial model outputs to update UI in real time (typing, progress, partial answers).
  • Call Hunyuan or DeepSeek models from client-side Mini Program logic via wx.cloud.
  • Prototype in-app AI features without a separate Node backend or browser SDK.
  • Embed serverless AI behavior where Mini Program can directly access CloudBase AI providers.

Best practices

  • Ensure WeChat base library version 3.7.1+ before using AI features.
  • Wrap streamText parameters in a data object — missing wrapper will fail.
  • Use onText to update UI incrementally and onFinish to finalize content.
  • Monitor eventStream and stop when event.data === "[DONE]" to avoid hangs.
  • Always wrap calls in try/catch and surface user-friendly errors and retries.

Example use cases

  • In-app chatbot that streams replies as the model composes them for better UX.
  • Smart reply composer that generates multiple candidate messages using generateText.
  • Customer support assistant integrated in an enterprise WeChat Mini Program.
  • Content suggestion tool that previews partial drafts via streamText on input.
  • Interactive tutorials that use Hunyuan models to generate step-by-step instructions.

FAQ

Do I need an extra SDK to use this in a Mini Program?

No. wx.cloud.extend.AI is available in WeChat base library 3.7.1+ and requires no additional SDK installation.

How does generateText differ from the Node/JS SDK?

generateText in Mini Program returns the raw model response (choices and usage) rather than the wrapped {text, usage} shape used by the Node/JS SDK.