[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M784HF22B9B8CWSF8271PPQR":3,"skill-same:01M784HF22B9B8CWSF8271PPQR":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":30,"ownerHtmlUrl":31,"ownerBlogUrl":6,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M784HF22B9B8CWSF8271PPQR","ai-model-nodejs",null,"Use this skill for Node.js backend AI via @cloudbase\u002Fnode-sdk (>=3.16.0) — cloud functions, CloudRun, Express, Koa, NestJS, serverless APIs, scheduled jobs, LLM proxies. Only SDK supporting image generation (ai.createImageModel + generateImage). Text models via ai.createModel with groups cloudbase, hunyuan-exp, or custom-*. Model IDs (deepseek-v4-flash, deepseek-v3.2, hunyuan-2.0-instruct-20251111, glm-5, kimi-k2.6) go in the model field of generateText\u002FstreamText. MUST run two-step preflight before code — see body. Keywords: backend, 云函数, 云托管, serverless, LLM proxy, agent orchestration, generateText, streamText, generateImage, createModel, hunyuan-image, Token Credits, TokenHub, Hunyuan, DeepSeek, GLM, Kimi, MiniMax. NOT for browser\u002FWeb (use ai-model-web) or Mini Program (use ai-model-wechat).","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fskills_sh\u002Fs\u002Fskills-sh_tencentcloudbase_skills_ai-model-nodejs\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: ai-model-nodejs\ndescription: \"Use this skill for Node.js backend AI via @cloudbase\u002Fnode-sdk (>=3.16.0) — cloud functions, CloudRun, Express, Koa, NestJS, serverless APIs, scheduled jobs, LLM proxies. Only SDK supporting image generation (ai.createImageModel + generateImage). Text models via ai.createModel with groups cloudbase, hunyuan-exp, or custom-*. Model IDs (deepseek-v4-flash, deepseek-v3.2, hunyuan-2.0-instruct-20251111, glm-5, kimi-k2.6) go in the model field of generateText\u002FstreamText. MUST run two-step preflight before code — see body. Keywords: backend, 云函数, 云托管, serverless, LLM proxy, agent orchestration, generateText, streamText, generateImage, createModel, hunyuan-image, Token Credits, TokenHub, Hunyuan, DeepSeek, GLM, Kimi, MiniMax. NOT for browser\u002FWeb (use ai-model-web) or Mini Program (use ai-model-wechat).\"\nversion: 2.21.1\nalwaysApply: false\n---\n\n## Standalone Install Note\n\nIf this environment only installed the current skill, start from the CloudBase main entry and use the published `cloudbase\u002Freferences\u002F...` paths for sibling skills.\n\n- CloudBase main entry: `https:\u002F\u002Fcnb.cool\u002Ftencent\u002Fcloud\u002Fcloudbase\u002Fcloudbase-skills\u002F-\u002Fgit\u002Fraw\u002Fmain\u002Fskills\u002Fcloudbase\u002FSKILL.md`\n- Current skill raw source: `https:\u002F\u002Fcnb.cool\u002Ftencent\u002Fcloud\u002Fcloudbase\u002Fcloudbase-skills\u002F-\u002Fgit\u002Fraw\u002Fmain\u002Fskills\u002Fcloudbase\u002Freferences\u002Fai-model-nodejs\u002FSKILL.md`\n\nKeep local `references\u002F...` paths for files that ship with the current skill directory. When this file points to a sibling skill such as `auth-tool` or `web-development`, use the standalone fallback URL shown next to that reference.\n\n## When to use this skill\n\nUse this skill for **calling AI models from Node.js backends, cloud functions, or CloudRun services** via `@cloudbase\u002Fnode-sdk`.\n\n> 🧭 **Runtime-plane fit.** This is the right skill when the AI call truly belongs on the server: image generation (the only SDK that supports it), long-running agent jobs, orchestration across multiple tools, scheduled tasks, or flows that must keep secrets server-side. **If the user is building a Web page \u002F frontend AI chat UI, do NOT wrap this SDK behind a backend proxy** — route to `ai-model-web` and call the model directly from the browser. For WeChat Mini Programs use `ai-model-wechat`. Routing is decided by runtime plane first; the concrete model (`deepseek-*`, `glm-*`, `hunyuan-*`, `kimi-*`, …) only affects the `model` field.\n\n**Use it when you need to:**\n\n- Integrate AI text generation into a backend service\n- Generate images with the Hunyuan Image model\n- Call AI models from CloudBase cloud functions or CloudRun\n- Do server-side AI processing (agent orchestration, batch jobs, scheduled tasks)\n\n**Do NOT use for:**\n\n- Browser\u002FWeb apps → use the `ai-model-web` skill\n- WeChat Mini Program → use the `ai-model-wechat` skill\n- Runtimes without a CloudBase SDK (Python, Go, PHP, curl, etc.) → use the `http-api` skill (it now includes the `ai_model` OpenAPI spec for direct HTTP calls to the AI model endpoint; do NOT wrap this SDK behind an HTTP proxy)\n\n---\n\n## ⛔ STOP — `ai.createModel(...)` argument is **not** a vendor \u002F model name\n\nRead this before writing any `createModel(...)` line. Agents frequently hallucinate this argument. There are **exactly three** legal shapes. Anything else is a bug.\n\n| ✅ Legal `ai.createModel(...)` argument | When to use it |\n|----------------------------------------|----------------|\n| `\"cloudbase\"` | **The main managed group for server-side projects** (TokenHub-backed, multi-vendor pool). Vendor + concrete model go into the **`model` field** of `generateText` \u002F `streamText`, e.g. `{ model: \"deepseek-v4-flash\" }`. **No model is enabled by default — always check `DescribeAIModels` first and, if the target model is missing, enable it with `UpdateAIModel` before calling the SDK.** |\n| `\"hunyuan-exp\"` | Only if `DescribeAIModels` explicitly returns this legacy builtin group for the current env. |\n| `\"custom-\u003Cyour-name>\"` | A user-defined GroupName you onboarded via `CreateAIModel`. **Must** start with `custom-` (e.g. `custom-kimi`, `custom-openai-compat`). |\n\n> Image generation is a separate entry point: `ai.createImageModel(\"hunyuan-image\")`. Do not mix it with `createModel(...)`.\n\n### ❌ Do NOT write any of these — they are all wrong\n\n```js\nai.createModel(\"deepseek\")                 \u002F\u002F wrong — that's a vendor, not a GroupName\nai.createModel(\"deepseek-v4-flash\")        \u002F\u002F wrong — model id goes in the `model` field\nai.createModel(\"hunyuan\") \u002F \"hunyuan-2.0-instruct-20251111\"  \u002F\u002F wrong — vendor \u002F model name\nai.createModel(\"glm\") \u002F \"kimi\" \u002F \"minimax\"  \u002F\u002F wrong — vendor names\nai.createModel(\"openai\") \u002F \"moonshot\"       \u002F\u002F wrong — vendor names\nai.createModel(\"custom\")                   \u002F\u002F wrong — placeholder; use your real custom-\u003Cname>\nai.createModel(modelName)                  \u002F\u002F wrong — do not reuse the variable that holds the model id\n```\n\n### ✅ Correct pattern — GroupName vs Model are two different fields\n\n```js\nconst model = ai.createModel(\"cloudbase\");          \u002F\u002F ← GroupName\nawait model.generateText({\n  model: \"deepseek-v4-flash\",                       \u002F\u002F ← concrete model id\n  messages: [...]\n});\n```\n\n### Decision procedure (when the user names a specific model)\n\n1. The user says \"use DeepSeek v3.2\" \u002F \"use hunyuan instruct\" \u002F \"use Kimi k2.6\" \u002F \"use GLM-5\" \u002F …\n2. `createModel(\"cloudbase\")` stays the same.\n3. Put the model id into the **`model` field**: `{ model: \"deepseek-v3.2\" }`, `{ model: \"hunyuan-2.0-instruct-20251111\" }`, `{ model: \"kimi-k2.6\" }`, `{ model: \"glm-5\" }`, …\n4. **Never assume the model is already enabled.** Before calling the SDK, verify it is present in `DescribeAIModels({ GroupName: \"cloudbase\" }).Models[]`. If missing, call `DescribeManagedAIModelList` to confirm the exact `Model` name the platform supports (case-sensitive — do **not** guess the spelling) and then enable it via `UpdateAIModel` with `Status: 1` (remember `Models` is a full replacement).\n\n> If you are about to type `ai.createModel(` and the thing inside the parentheses is a vendor name, a model name, or a guess — **stop**. It is almost certainly one of the three legal values above.\n\n---\n\n## Mandatory Two-Step Preflight (before any SDK code)\n\nBefore calling any AI API on the server, **run the two-step preflight**: ① eligibility, ② group readiness. **Text generation and image generation draw from the same Token Credits resource pack**, and both must complete the preflight before code is emitted.\n\n### Step 0: obtain the environment ID\n\nCall the MCP tool `envQuery` with `action=info` and read `EnvId` from the response.\n\n---\n\n### Preflight ① — Eligibility (Token Credits resource pack)\n\nCall the MCP tool:\n\n```\ncallCloudApi(service=\"tcb\", action=\"DescribeEnvPostpayPackage\", params={ EnvId })\n```\n\n**Pass conditions (all required):**\n- `envPostpayPackageInfoList` contains at least one entry\n- That entry's `postpayPackageId` starts with `pkg_tcb_tokencredits_`\n- That entry's `status` is NOT in `[3, 4]` (3 \u002F 4 typically mean expired \u002F disabled; trust the live response)\n\n- ❌ **Not satisfied** → **stop writing code** and surface this to the user (replacing `{envId}` with the real id):\n  > The current environment has no active Token Credits resource pack. Please purchase one before calling any AI API:\n  > https:\u002F\u002Fbuy.cloud.tencent.com\u002Flowcode?buyType=resPack&envId={envId}&resourceType=token\n  >\n  > Let me know once it's done and I'll re-check the resource pack status.\n\n- ✅ **Satisfied** → proceed to preflight ②.\n\n> Parameter casing is PascalCase by contract. If the call returns `InvalidParameter`, fall back to camelCase (`envId`) and trust the live response.\n\n---\n\n### Preflight ② — Group readiness (`DescribeAIModels` → `UpdateAIModel` if needed)\n\nEligibility alone is not enough. **Do not write `createModel(\"cloudbase\")` yet.** First confirm that the target `GroupName` exists in the env with `Status=1`, and that the target `Model` is present in its `Models[]`.\n\n1. **List groups configured in the current env:**\n\n   ```\n   callCloudApi(service=\"tcb\", action=\"DescribeAIModels\", params={ EnvId })\n   ```\n\n   Returns `AIModelGroups: AIModelGroup[]` with `GroupName`, `Type` (`builtin` \u002F `custom`), `Models: [{ Model, EnableMCP, Tags }]`, `Status` (1 \u002F 2), `BaseUrl`, `Secret`, `Remark`. The main managed `GroupName` is `cloudbase`.\n\n2. **Never assume a model is already enabled.** Inspect `AIModelGroups[?].Models[].Model` for the target group. If the text model you plan to use (e.g. `deepseek-v4-flash`, or whatever the user asked for) is missing from the `cloudbase` group's `Models[]`, jump to step 4 and enable it — do not call `createModel(\"cloudbase\")` yet. Image generation uses `createImageModel(\"hunyuan-image\")` + `model: \"hunyuan-image\"`; verify it is likewise enabled before the call.\n\n3. **User asked for a model from the managed catalog** (e.g. `deepseek-v3.2`, `hunyuan-2.0-instruct-20251111`): check whether that `Model` is already in the `cloudbase` group's `Models[]`. If not, jump to step 4. **Do not guess the exact model id** — confirm the canonical spelling in `DescribeManagedAIModelList` first.\n\n4. **Enable \u002F add a managed model** (always inspect the authoritative catalog + pricing first):\n\n   ```\n   callCloudApi(service=\"tcb\", action=\"DescribeManagedAIModelList\", params={ EnvId })\n   ```\n\n   Returns `ManagedAIModelGroup[]` with `GroupName`, `Remark`, and `Models: [{ Model, EnableMCP, ModelSpec, ModelChargingInfo }]`. **This is the single source of truth for supported model names and pricing — do not infer them from memory. Use the exact `Model` string from here when calling `UpdateAIModel`.** `ModelChargingInfo` includes input \u002F output prices and billing unit. Surface the prices to the user before enabling.\n\n   Then enable (note: `Models` is a **full replacement** — always resend the already-enabled models together with the new one):\n\n   ```\n   callCloudApi(service=\"tcb\", action=\"UpdateAIModel\", params={\n     EnvId,\n     GroupName: \"cloudbase\",\n     Models: [\n       \u002F\u002F resend every model that DescribeAIModels already showed as enabled\n       { Model: \"\u003Calready-enabled model>\" },\n       \u002F\u002F append the newly-requested one, using the exact spelling from DescribeManagedAIModelList\n       { Model: \"\u003Ctarget model>\" }\n     ],\n     Status: 1\n   })\n   ```\n\n5. **The requested model is not in the managed catalog** (not found by `DescribeManagedAIModelList`) → jump to the next section, **Custom onboarding (models outside the managed catalog)**.\n\n> All Actions use `service=tcb`, `Version=2018-06-08`. Parameters are PascalCase; fall back to camelCase only on `InvalidParameter`.\n\n---\n\n## Available Providers and Models\n\n`ai.createModel(\u003CGroupName>)` accepts exactly three kinds of legal values; `ai.createImageModel(\"hunyuan-image\")` is the dedicated image-generation entry point.\n\n### 1. `\"cloudbase\"` — the main managed group (recommended)\n\n- `GroupName: \"cloudbase\"`, `Type: \"builtin\"`, `Remark: \"腾讯云开发\"` (Tencent CloudBase)\n- Backed by **Tencent Cloud TokenHub**, a unified managed pool covering multiple vendors — **Hunyuan** (HY 2.0 Instruct, HY 2.0 Think, Hunyuan-role, Hy3 preview, …), **DeepSeek** (DeepSeek-V4-Pro, DeepSeek-V4-Flash, Deepseek-v3.2, Deepseek-v3.1, Deepseek-r1-0528, Deepseek-v3-0324, …), **Zhipu GLM** (GLM-5, GLM-5-Turbo, GLM-5.1, GLM-5V-Turbo), **Kimi** (K2.5, K2.6), **MiniMax** (M2.5, M2.7), and more. The roster evolves — **do not hard-code specific SKUs**; discover at runtime\n- **No model is enabled by default.** Always call `DescribeAIModels` first to see what the env has actually enabled; if your target model is missing, call `DescribeManagedAIModelList` for the authoritative catalog + pricing and then `UpdateAIModel` (`Status: 1`, `Models` full-replacement) to enable it before making the SDK call.\n- Authoritative catalog + pricing: `DescribeManagedAIModelList`\n- Env-enabled set: `DescribeAIModels`\n\n### 2. `\"hunyuan-exp\"` — legacy builtin group (kept for compatibility)\n\n- Default model: `hunyuan-2.0-instruct-20251111`; additional hunyuan SKUs must be discovered at runtime via `DescribeAIModels({ GroupName: \"hunyuan-exp\" }).Models[]` — do not hard-code other IDs\n- Use it directly only if `DescribeAIModels` actually returns this group with `Status=1`. New projects should prefer `cloudbase`\n\n### 3. User-defined GroupName\n\n- Onboarded via `CreateAIModel` (see the next section). The custom `GroupName` **MUST start with `custom-`** (e.g. `custom-kimi`, `custom-moonshot`, `custom-openai-compat`). This naming convention prevents future collisions with built-in \u002F vendor GroupNames (like `cloudbase`, `hunyuan-exp`, `deepseek`, `glm`, `kimi`, `minimax`) that the platform may introduce over time\n- Examples: `createModel(\"custom-kimi\")`, `createModel(\"custom-openai-compat\")`\n\n### Image generation (independent API)\n\n- `ai.createImageModel(\"hunyuan-image\")` + `model: \"hunyuan-image\"`. Only supported in the Node SDK\n\n> **Never** write guesses like `createModel(\"deepseek\")` or `createModel(\"custom\")` unless `DescribeAIModels` explicitly returned that exact `GroupName`.\n\n---\n\n## Custom onboarding (models outside the managed catalog)\n\nWhen the user wants a **non-managed** text model (self-hosted, enterprise-internal, third-party OpenAI-compatible endpoint, …), **do not block**. Guide them through onboarding:\n\n### Option 1: console flow (recommended, user handles it)\n\n`https:\u002F\u002Ftcb.cloud.tencent.com\u002Fdev?envId={envId}#\u002Fai`\n\n### Option 2: programmatic onboarding (`CreateAIModel`)\n\n```\ncallCloudApi(service=\"tcb\", action=\"CreateAIModel\", params={\n  EnvId: \"\u003CenvId>\",\n  GroupName: \"custom-\u003Cyour-name>\",  \u002F\u002F MUST start with \"custom-\" (e.g. custom-kimi, custom-openai-compat); never start with \"cloudbase\"\n  BaseUrl: \"\u003COpenAI-compatible endpoint, e.g. https:\u002F\u002Fapi.moonshot.cn\u002Fv1>\",\n  Models: [\n    { Model: \"\u003Cmodel name, e.g. kimi-k2.5>\", EnableMCP: true }\n  ],\n  Remark: \"\u003Coptional remark>\",\n  Status: 1,\n  Secret: { ApiKey: \"\u003Cvendor api key supplied by the user>\" }\n})\n```\n\nOnce onboarded, confirm with `DescribeAIModels` that the group is ready, then call `ai.createModel(\"\u003Cthe GroupName you just registered>\")` from your code. Use `UpdateAIModel` to add\u002Fremove models, rotate keys, or change `BaseUrl` (remember `Models` is a **full replacement**). Use `DeleteAIModel` to remove a custom group (builtin groups cannot be deleted).\n\n> Custom-model billing is covered by the third-party provider and does not draw from the Token Credits resource pack. Field casing follows the live contract — fall back to camelCase on `InvalidParameter`.\n\n---\n\n## Installation\n\n```bash\nnpm install @cloudbase\u002Fnode-sdk\n```\n\n⚠️ **The AI feature requires version 3.16.0 or above.** Check with `npm list @cloudbase\u002Fnode-sdk`.\n\n---\n\n## Initialization\n\n### Inside a CloudBase cloud function\n\n```js\nconst tcb = require('@cloudbase\u002Fnode-sdk');\nconst app = tcb.init({ env: '\u003CYOUR_ENV_ID>' });\n\nexports.main = async (event, context) => {\n  const ai = app.ai();\n  \u002F\u002F Use AI features\n};\n```\n\n### Cloud function configuration for AI models\n\n⚠️ **Important:** when creating cloud functions that use AI models (especially `generateImage()` and large text generation), set a longer timeout — these operations can be slow.\n\n**Using the MCP tool `manageFunctions(action=\"createFunction\")`:**\n\nLegacy compatibility: if an older prompt still says `createFunction`, keep the same payload shape but execute it through `manageFunctions(action=\"createFunction\")`.\n\nSet `timeout` inside the `func` object:\n\n- **Parameter**: `func.timeout` (number)\n- **Unit**: seconds\n- **Range**: 1 – 900\n- **Default**: 20 seconds (usually too short for AI operations)\n\n**Recommended timeouts:**\n- **Text generation (`generateText`)**: 60 – 120 s\n- **Streaming (`streamText`)**: 60 – 120 s\n- **Image generation (`generateImage`)**: 300 – 900 s (recommended: 900 s)\n- **Combined operations**: 900 s (maximum allowed)\n\n### In a regular Node.js server\n\n```js\nconst tcb = require('@cloudbase\u002Fnode-sdk');\nconst app = tcb.init({\n  env: '\u003CYOUR_ENV_ID>',\n  secretId: '\u003CYOUR_SECRET_ID>',\n  secretKey: '\u003CYOUR_SECRET_KEY>'\n});\n\nconst ai = app.ai();\n```\n\n---\n\n## generateText() — non-streaming\n\n> **Prerequisite:** the two-step preflight (eligibility + group readiness) has passed. The example below assumes the user did not specify a model, so it uses the `cloudbase` managed group + `deepseek-v4-flash`.\n\n```js\nconst model = ai.createModel(\"cloudbase\");\n\nconst result = await model.generateText({\n  model: \"deepseek-v4-flash\",  \u002F\u002F must already be enabled in this env (DescribeAIModels → UpdateAIModel)\n  messages: [{ role: \"user\", content: \"Give me a one-paragraph intro to Li Bai.\" }],\n});\n\nconsole.log(result.text);           \u002F\u002F generated text string\nconsole.log(result.usage);          \u002F\u002F { prompt_tokens, completion_tokens, total_tokens }\nconsole.log(result.messages);       \u002F\u002F full message history\nconsole.log(result.rawResponses);   \u002F\u002F raw model responses\n```\n\n---\n\n## Error Handling Pattern\n\n```js\nconst model = ai.createModel(\"cloudbase\");\n\ntry {\n  const result = await model.generateText({\n    model: \"deepseek-v4-flash\",\n    messages: [{ role: \"user\", content: \"Summarize today's deployment logs.\" }],\n  });\n\n  console.log(result.text);\n} catch (error) {\n  console.error(\"AI request failed\", error);\n}\n```\n\n---\n\n## streamText() — streaming\n\n> **Prerequisite:** the two-step preflight has passed.\n\n```js\nconst model = ai.createModel(\"cloudbase\");\n\nconst res = await model.streamText({\n  model: \"deepseek-v4-flash\",\n  messages: [{ role: \"user\", content: \"Give me a one-paragraph intro to Li Bai.\" }],\n});\n\n\u002F\u002F Option 1: iterate the text stream (recommended)\nfor await (let text of res.textStream) {\n  console.log(text);  \u002F\u002F incremental text chunks\n}\n\n\u002F\u002F Option 2: iterate the data stream for full response chunks\nfor await (let data of res.dataStream) {\n  console.log(data);  \u002F\u002F full response chunk with metadata\n}\n\n\u002F\u002F Option 3: access final results\nconst messages = await res.messages;  \u002F\u002F full message history\nconst usage = await res.usage;        \u002F\u002F token usage\n```\n\n---\n\n## generateImage() — image generation\n\n⚠️ **Image generation is only available in the Node SDK**, not in the JS SDK (Web) or WeChat Mini Program.\n\n⚠️ **Image generation also consumes the Token Credits resource pack**, so the two-step preflight must pass before calling it. Per-call cost is higher than text and calls take longer (set cloud function timeout to 900 s).\n\n```js\nconst imageModel = ai.createImageModel(\"hunyuan-image\");\n\nconst res = await imageModel.generateImage({\n  model: \"hunyuan-image\",\n  prompt: \"A cute kitten playing on the grass\",\n  size: \"1024x1024\",\n  version: \"v1.9\",\n});\n\nconsole.log(res.data[0].url);           \u002F\u002F image URL (valid for 24 hours)\nconsole.log(res.data[0].revised_prompt);\u002F\u002F revised prompt when revise=true\n```\n\n### Image Generation Parameters\n\n```ts\ninterface HunyuanGenerateImageInput {\n  model: \"hunyuan-image\";      \u002F\u002F required\n  prompt: string;                       \u002F\u002F required: image description\n  version?: \"v1.8.1\" | \"v1.9\";         \u002F\u002F default: \"v1.8.1\"\n  size?: string;                        \u002F\u002F default: \"1024x1024\"\n  negative_prompt?: string;             \u002F\u002F v1.9 only\n  style?: string;                       \u002F\u002F v1.9 only\n  revise?: boolean;                     \u002F\u002F default: true\n  n?: number;                           \u002F\u002F default: 1\n  footnote?: string;                    \u002F\u002F watermark, max 16 chars\n  seed?: number;                        \u002F\u002F range: [1, 4294967295]\n}\n\ninterface HunyuanGenerateImageOutput {\n  id: string;\n  created: number;\n  data: Array\u003C{\n    url: string;                        \u002F\u002F image URL (24h valid)\n    revised_prompt?: string;\n  }>;\n}\n```\n\n---\n\n## Type Definitions\n\n```ts\ninterface BaseChatModelInput {\n  model: string;                        \u002F\u002F required: model name\n  messages: Array\u003CChatModelMessage>;    \u002F\u002F required: message array\n  temperature?: number;                 \u002F\u002F optional: sampling temperature\n  topP?: number;                        \u002F\u002F optional: nucleus sampling\n}\n\ntype ChatModelMessage =\n  | { role: \"user\"; content: string }\n  | { role: \"system\"; content: string }\n  | { role: \"assistant\"; content: string };\n\ninterface GenerateTextResult {\n  text: string;                         \u002F\u002F generated text\n  messages: Array\u003CChatModelMessage>;    \u002F\u002F full message history\n  usage: Usage;                         \u002F\u002F token usage\n  rawResponses: Array\u003Cunknown>;         \u002F\u002F raw model responses\n  error?: unknown;                      \u002F\u002F error if any\n}\n\ninterface StreamTextResult {\n  textStream: AsyncIterable\u003Cstring>;    \u002F\u002F incremental text stream\n  dataStream: AsyncIterable\u003CDataChunk>; \u002F\u002F full data stream\n  messages: Promise\u003CChatModelMessage[]>;\u002F\u002F final message history\n  usage: Promise\u003CUsage>;                \u002F\u002F final token usage\n  error?: unknown;                      \u002F\u002F error if any\n}\n\ninterface Usage {\n  prompt_tokens: number;\n  completion_tokens: number;\n  total_tokens: number;\n}\n```\n\n---\n\n## Best Practices\n\n1. **Run the two-step preflight before writing business code** — ① eligibility: `envQuery` → `callCloudApi(tcb, DescribeEnvPostpayPackage)` to confirm the Token Credits resource pack (text + image share the same pack); ② group readiness: `DescribeAIModels` for the `cloudbase` group and its `Models[]`, `DescribeManagedAIModelList` for the authoritative supported-model catalog, `UpdateAIModel` with a full-replacement `Models[]` + `Status: 1` when the target model is missing. If the pack is missing, return the purchase link `https:\u002F\u002Fbuy.cloud.tencent.com\u002Flowcode?buyType=resPack&envId={envId}&resourceType=token` instead of emitting SDK code and letting the user debug runtime errors.\n2. **Never assume any model is already enabled** — not `deepseek-v4-flash`, not `hunyuan-image`, not anything. Always verify with `DescribeAIModels` first; if the target is missing, look up the exact `Model` string in `DescribeManagedAIModelList` (do **not** guess the spelling) and then `UpdateAIModel` to enable it.\n3. **`createModel` accepts exactly three kinds of values** — `\"cloudbase\"` (the main managed group), `\"hunyuan-exp\"` (legacy builtin), or a user-defined GroupName registered via `CreateAIModel` (**MUST start with `custom-`**, e.g. `custom-kimi`, `custom-openai-compat`). **Never** guess with `createModel(\"deepseek\")` \u002F `createModel(\"kimi\")` \u002F `createModel(\"custom\")` — the first two are vendor\u002Fmodel names, the last is a placeholder. `createImageModel(\"hunyuan-image\")` is a separate image API — keep it as-is.\n4. **Do not invent SDK method names or parameters.** This SKILL.md is the authoritative reference for `@cloudbase\u002Fnode-sdk`'s AI surface — look up the method signature here (or in the Type Definitions section) before writing code. If a method or field is not documented here, stop and ask, or check the live contract via the MCP tools. No guessing.\n5. **Show pricing before enabling a new managed model** — `DescribeManagedAIModelList` returns `ModelSpec` (context length, max input\u002Foutput tokens) + `ModelChargingInfo` (input \u002F output \u002F cache prices, billing unit). Show the prices to the user before calling `UpdateAIModel`.\n6. **Plan timeout and quota separately for image generation** — `generateImage` costs more per call than text and takes longer. For cloud functions, set `timeout` to `900s`. HTTP-function gateways cap at 60s, so use an async-task + polling pattern. Throttle per-user concurrency and frequency to avoid burning an entire Token pack on one failure.\n7. **Prefer streaming for long-form interactions** — in HTTP-function or cloud-function SSE scenarios, use `streamText` + `for await (const chunk of result.textStream)` to flush chunks back to the client incrementally. Handle stream interruption in `catch` and close the underlying response.\n8. **Pin `@cloudbase\u002Fnode-sdk` >= 3.16.0** on the server — image generation is only available from this version. Verify with `npm ls @cloudbase\u002Fnode-sdk` to confirm the version actually loaded by the cloud function \u002F cloud run runtime — local and production can drift.\n9. **Centralize model names in config, not scattered literals.** Keep the chosen text \u002F image model in a single constant and source from `DescribeAIModels` \u002F `DescribeManagedAIModelList`. The managed catalog evolves; a single source of truth makes upgrades cheap. For models outside the managed catalog, follow the Custom Onboarding section — never hard-code third-party API keys in business code (let `CreateAIModel.Secret.ApiKey` hold them via CloudBase).\n10. **Distinguish \"preflight failure\" from \"model call failure\"** — the former means the resource pack is not active or the target model has not been enabled via `UpdateAIModel` (guide the user to purchase \u002F enable). The latter is a parameter issue or upstream error. Do not wrap both in one generic toast.\n11. **Do not log full prompts or generated text in production** — log only `usage.total_tokens` and a short prefix. Prompts can leak sensitive content; token counts can leak cost signals.\n12. **TypeScript: do NOT use `any` to silence SDK type errors.** The Node SDK ships its own types; narrow with `unknown` + a type guard, write a precise `interface` for the shape you consume, or augment types in a local `.d.ts`. Never `: any`, `as any`, `@ts-ignore`, `@ts-nocheck`. See the Engineering constitution in the `web-development` skill — it applies to backend TS too.\n13. **Self-verify before claiming done.** `tsc --noEmit` + project build + actually invoke the function (local invoke \u002F `manageFunctions(action=\"invokeFunction\")` \u002F direct HTTP hit) and confirm `usage.total_tokens > 0` and the returned text is not an error envelope. \"It should work\" without a real round-trip is not acceptable evidence.\n","## Standalone Install Note\n\nIf this environment only installed the current skill, start from the CloudBase main entry and use the published `cloudbase\u002Freferences\u002F...` paths for sibling skills.\n\n- CloudBase main entry: `https:\u002F\u002Fcnb.cool\u002Ftencent\u002Fcloud\u002Fcloudbase\u002Fcloudbase-skills\u002F-\u002Fgit\u002Fraw\u002Fmain\u002Fskills\u002Fcloudbase\u002FSKILL.md`\n- Current skill raw source: `https:\u002F\u002Fcnb.cool\u002Ftencent\u002Fcloud\u002Fcloudbase\u002Fcloudbase-skills\u002F-\u002Fgit\u002Fraw\u002Fmain\u002Fskills\u002Fcloudbase\u002Freferences\u002Fai-model-nodejs\u002FSKILL.md`\n\nKeep local `references\u002F...` paths for files that ship with the current skill directory. When this file points to a sibling skill such as `auth-tool` or `web-development`, use the standalone fallback URL shown next to that reference.\n\n## When to use this skill\n\nUse this skill for **calling AI models from Node.js backends, cloud functions, or CloudRun services** via `@cloudbase\u002Fnode-sdk`.\n\n> 🧭 **Runtime-plane fit.** This is the right skill when the AI call truly belongs on the server: image generation (the only SDK that supports it), long-running agent jobs, orchestration across multiple tools, scheduled tasks, or flows that must keep secrets server-side. **If the user is building a Web page \u002F frontend AI chat UI, do NOT wrap this SDK behind a backend proxy** — route to `ai-model-web` and call the model directly from the browser. For WeChat Mini Programs use `ai-model-wechat`. Routing is decided by runtime plane first; the concrete model (`deepseek-*`, `glm-*`, `hunyuan-*`, `kimi-*`, …) only affects the `model` field.\n\n**Use it when you need to:**\n\n- Integrate AI text generation into a backend service\n- Generate images with the Hunyuan Image model\n- Call AI models from CloudBase cloud functions or CloudRun\n- Do server-side AI processing (agent orchestration, batch jobs, scheduled tasks)\n\n**Do NOT use for:**\n\n- Browser\u002FWeb apps → use the `ai-model-web` skill\n- WeChat Mini Program → use the `ai-model-wechat` skill\n- Runtimes without a CloudBase SDK (Python, Go, PHP, curl, etc.) → use the `http-api` skill (it now includes the `ai_model` OpenAPI spec for direct HTTP calls to the AI model endpoint; do NOT wrap this SDK behind an HTTP proxy)\n\n---\n\n## ⛔ STOP — `ai.createModel(...)` argument is **not** a vendor \u002F model name\n\nRead this before writing any `createModel(...)` line. Agents frequently hallucinate this argument. There are **exactly three** legal shapes. Anything else is a bug.\n\n| ✅ Legal `ai.createModel(...)` argument | When to use it |\n|----------------------------------------|----------------|\n| `\"cloudbase\"` | **The main managed group for server-side projects** (TokenHub-backed, multi-vendor pool). Vendor + concrete model go into the **`model` field** of `generateText` \u002F `streamText`, e.g. `{ model: \"deepseek-v4-flash\" }`. **No model is enabled by default — always check `DescribeAIModels` first and, if the target model is missing, enable it with `UpdateAIModel` before calling the SDK.** |\n| `\"hunyuan-exp\"` | Only if `DescribeAIModels` explicitly returns this legacy builtin group for the current env. |\n| `\"custom-\u003Cyour-name>\"` | A user-defined GroupName you onboarded via `CreateAIModel`. **Must** start with `custom-` (e.g. `custom-kimi`, `custom-openai-compat`). |\n\n> Image generation is a separate entry point: `ai.createImageModel(\"hunyuan-image\")`. Do not mix it with `createModel(...)`.\n\n### ❌ Do NOT write any of these — they are all wrong\n\n```js\nai.createModel(\"deepseek\")                 \u002F\u002F wrong — that's a vendor, not a GroupName\nai.createModel(\"deepseek-v4-flash\")        \u002F\u002F wrong — model id goes in the `model` field\nai.createModel(\"hunyuan\") \u002F \"hunyuan-2.0-instruct-20251111\"  \u002F\u002F wrong — vendor \u002F model name\nai.createModel(\"glm\") \u002F \"kimi\" \u002F \"minimax\"  \u002F\u002F wrong — vendor names\nai.createModel(\"openai\") \u002F \"moonshot\"       \u002F\u002F wrong — vendor names\nai.createModel(\"custom\")                   \u002F\u002F wrong — placeholder; use your real custom-\u003Cname>\nai.createModel(modelName)                  \u002F\u002F wrong — do not reuse the variable that holds the model id\n```\n\n### ✅ Correct pattern — GroupName vs Model are two different fields\n\n```js\nconst model = ai.createModel(\"cloudbase\");          \u002F\u002F ← GroupName\nawait model.generateText({\n  model: \"deepseek-v4-flash\",                       \u002F\u002F ← concrete model id\n  messages: [...]\n});\n```\n\n### Decision procedure (when the user names a specific model)\n\n1. The user says \"use DeepSeek v3.2\" \u002F \"use hunyuan instruct\" \u002F \"use Kimi k2.6\" \u002F \"use GLM-5\" \u002F …\n2. `createModel(\"cloudbase\")` stays the same.\n3. Put the model id into the **`model` field**: `{ model: \"deepseek-v3.2\" }`, `{ model: \"hunyuan-2.0-instruct-20251111\" }`, `{ model: \"kimi-k2.6\" }`, `{ model: \"glm-5\" }`, …\n4. **Never assume the model is already enabled.** Before calling the SDK, verify it is present in `DescribeAIModels({ GroupName: \"cloudbase\" }).Models[]`. If missing, call `DescribeManagedAIModelList` to confirm the exact `Model` name the platform supports (case-sensitive — do **not** guess the spelling) and then enable it via `UpdateAIModel` with `Status: 1` (remember `Models` is a full replacement).\n\n> If you are about to type `ai.createModel(` and the thing inside the parentheses is a vendor name, a model name, or a guess — **stop**. It is almost certainly one of the three legal values above.\n\n---\n\n## Mandatory Two-Step Preflight (before any SDK code)\n\nBefore calling any AI API on the server, **run the two-step preflight**: ① eligibility, ② group readiness. **Text generation and image generation draw from the same Token Credits resource pack**, and both must complete the preflight before code is emitted.\n\n### Step 0: obtain the environment ID\n\nCall the MCP tool `envQuery` with `action=info` and read `EnvId` from the response.\n\n---\n\n### Preflight ① — Eligibility (Token Credits resource pack)\n\nCall the MCP tool:\n\n```\ncallCloudApi(service=\"tcb\", action=\"DescribeEnvPostpayPackage\", params={ EnvId })\n```\n\n**Pass conditions (all required):**\n- `envPostpayPackageInfoList` contains at least one entry\n- That entry's `postpayPackageId` starts with `pkg_tcb_tokencredits_`\n- That entry's `status` is NOT in `[3, 4]` (3 \u002F 4 typically mean expired \u002F disabled; trust the live response)\n\n- ❌ **Not satisfied** → **stop writing code** and surface this to the user (replacing `{envId}` with the real id):\n  > The current environment has no active Token Credits resource pack. Please purchase one before calling any AI API:\n  > https:\u002F\u002Fbuy.cloud.tencent.com\u002Flowcode?buyType=resPack&envId={envId}&resourceType=token\n  >\n  > Let me know once it's done and I'll re-check the resource pack status.\n\n- ✅ **Satisfied** → proceed to preflight ②.\n\n> Parameter casing is PascalCase by contract. If the call returns `InvalidParameter`, fall back to camelCase (`envId`) and trust the live response.\n\n---\n\n### Preflight ② — Group readiness (`DescribeAIModels` → `UpdateAIModel` if needed)\n\nEligibility alone is not enough. **Do not write `createModel(\"cloudbase\")` yet.** First confirm that the target `GroupName` exists in the env with `Status=1`, and that the target `Model` is present in its `Models[]`.\n\n1. **List groups configured in the current env:**\n\n   ```\n   callCloudApi(service=\"tcb\", action=\"DescribeAIModels\", params={ EnvId })\n   ```\n\n   Returns `AIModelGroups: AIModelGroup[]` with `GroupName`, `Type` (`builtin` \u002F `custom`), `Models: [{ Model, EnableMCP, Tags }]`, `Status` (1 \u002F 2), `BaseUrl`, `Secret`, `Remark`. The main managed `GroupName` is `cloudbase`.\n\n2. **Never assume a model is already enabled.** Inspect `AIModelGroups[?].Models[].Model` for the target group. If the text model you plan to use (e.g. `deepseek-v4-flash`, or whatever the user asked for) is missing from the `cloudbase` group's `Models[]`, jump to step 4 and enable it — do not call `createModel(\"cloudbase\")` yet. Image generation uses `createImageModel(\"hunyuan-image\")` + `model: \"hunyuan-image\"`; verify it is likewise enabled before the call.\n\n3. **User asked for a model from the managed catalog** (e.g. `deepseek-v3.2`, `hunyuan-2.0-instruct-20251111`): check whether that `Model` is already in the `cloudbase` group's `Models[]`. If not, jump to step 4. **Do not guess the exact model id** — confirm the canonical spelling in `DescribeManagedAIModelList` first.\n\n4. **Enable \u002F add a managed model** (always inspect the authoritative catalog + pricing first):\n\n   ```\n   callCloudApi(service=\"tcb\", action=\"DescribeManagedAIModelList\", params={ EnvId })\n   ```\n\n   Returns `ManagedAIModelGroup[]` with `GroupName`, `Remark`, and `Models: [{ Model, EnableMCP, ModelSpec, ModelChargingInfo }]`. **This is the single source of truth for supported model names and pricing — do not infer them from memory. Use the exact `Model` string from here when calling `UpdateAIModel`.** `ModelChargingInfo` includes input \u002F output prices and billing unit. Surface the prices to the user before enabling.\n\n   Then enable (note: `Models` is a **full replacement** — always resend the already-enabled models together with the new one):\n\n   ```\n   callCloudApi(service=\"tcb\", action=\"UpdateAIModel\", params={\n     EnvId,\n     GroupName: \"cloudbase\",\n     Models: [\n       \u002F\u002F resend every model that DescribeAIModels already showed as enabled\n       { Model: \"\u003Calready-enabled model>\" },\n       \u002F\u002F append the newly-requested one, using the exact spelling from DescribeManagedAIModelList\n       { Model: \"\u003Ctarget model>\" }\n     ],\n     Status: 1\n   })\n   ```\n\n5. **The requested model is not in the managed catalog** (not found by `DescribeManagedAIModelList`) → jump to the next section, **Custom onboarding (models outside the managed catalog)**.\n\n> All Actions use `service=tcb`, `Version=2018-06-08`. Parameters are PascalCase; fall back to camelCase only on `InvalidParameter`.\n\n---\n\n## Available Providers and Models\n\n`ai.createModel(\u003CGroupName>)` accepts exactly three kinds of legal values; `ai.createImageModel(\"hunyuan-image\")` is the dedicated image-generation entry point.\n\n### 1. `\"cloudbase\"` — the main managed group (recommended)\n\n- `GroupName: \"cloudbase\"`, `Type: \"builtin\"`, `Remark: \"腾讯云开发\"` (Tencent CloudBase)\n- Backed by **Tencent Cloud TokenHub**, a unified managed pool covering multiple vendors — **Hunyuan** (HY 2.0 Instruct, HY 2.0 Think, Hunyuan-role, Hy3 preview, …), **DeepSeek** (DeepSeek-V4-Pro, DeepSeek-V4-Flash, Deepseek-v3.2, Deepseek-v3.1, Deepseek-r1-0528, Deepseek-v3-0324, …), **Zhipu GLM** (GLM-5, GLM-5-Turbo, GLM-5.1, GLM-5V-Turbo), **Kimi** (K2.5, K2.6), **MiniMax** (M2.5, M2.7), and more. The roster evolves — **do not hard-code specific SKUs**; discover at runtime\n- **No model is enabled by default.** Always call `DescribeAIModels` first to see what the env has actually enabled; if your target model is missing, call `DescribeManagedAIModelList` for the authoritative catalog + pricing and then `UpdateAIModel` (`Status: 1`, `Models` full-replacement) to enable it before making the SDK call.\n- Authoritative catalog + pricing: `DescribeManagedAIModelList`\n- Env-enabled set: `DescribeAIModels`\n\n### 2. `\"hunyuan-exp\"` — legacy builtin group (kept for compatibility)\n\n- Default model: `hunyuan-2.0-instruct-20251111`; additional hunyuan SKUs must be discovered at runtime via `DescribeAIModels({ GroupName: \"hunyuan-exp\" }).Models[]` — do not hard-code other IDs\n- Use it directly only if `DescribeAIModels` actually returns this group with `Status=1`. New projects should prefer `cloudbase`\n\n### 3. User-defined GroupName\n\n- Onboarded via `CreateAIModel` (see the next section). The custom `GroupName` **MUST start with `custom-`** (e.g. `custom-kimi`, `custom-moonshot`, `custom-openai-compat`). This naming convention prevents future collisions with built-in \u002F vendor GroupNames (like `cloudbase`, `hunyuan-exp`, `deepseek`, `glm`, `kimi`, `minimax`) that the platform may introduce over time\n- Examples: `createModel(\"custom-kimi\")`, `createModel(\"custom-openai-compat\")`\n\n### Image generation (independent API)\n\n- `ai.createImageModel(\"hunyuan-image\")` + `model: \"hunyuan-image\"`. Only supported in the Node SDK\n\n> **Never** write guesses like `createModel(\"deepseek\")` or `createModel(\"custom\")` unless `DescribeAIModels` explicitly returned that exact `GroupName`.\n\n---\n\n## Custom onboarding (models outside the managed catalog)\n\nWhen the user wants a **non-managed** text model (self-hosted, enterprise-internal, third-party OpenAI-compatible endpoint, …), **do not block**. Guide them through onboarding:\n\n### Option 1: console flow (recommended, user handles it)\n\n`https:\u002F\u002Ftcb.cloud.tencent.com\u002Fdev?envId={envId}#\u002Fai`\n\n### Option 2: programmatic onboarding (`CreateAIModel`)\n\n```\ncallCloudApi(service=\"tcb\", action=\"CreateAIModel\", params={\n  EnvId: \"\u003CenvId>\",\n  GroupName: \"custom-\u003Cyour-name>\",  \u002F\u002F MUST start with \"custom-\" (e.g. custom-kimi, custom-openai-compat); never start with \"cloudbase\"\n  BaseUrl: \"\u003COpenAI-compatible endpoint, e.g. https:\u002F\u002Fapi.moonshot.cn\u002Fv1>\",\n  Models: [\n    { Model: \"\u003Cmodel name, e.g. kimi-k2.5>\", EnableMCP: true }\n  ],\n  Remark: \"\u003Coptional remark>\",\n  Status: 1,\n  Secret: { ApiKey: \"\u003Cvendor api key supplied by the user>\" }\n})\n```\n\nOnce onboarded, confirm with `DescribeAIModels` that the group is ready, then call `ai.createModel(\"\u003Cthe GroupName you just registered>\")` from your code. Use `UpdateAIModel` to add\u002Fremove models, rotate keys, or change `BaseUrl` (remember `Models` is a **full replacement**). Use `DeleteAIModel` to remove a custom group (builtin groups cannot be deleted).\n\n> Custom-model billing is covered by the third-party provider and does not draw from the Token Credits resource pack. Field casing follows the live contract — fall back to camelCase on `InvalidParameter`.\n\n---\n\n## Installation\n\n```bash\nnpm install @cloudbase\u002Fnode-sdk\n```\n\n⚠️ **The AI feature requires version 3.16.0 or above.** Check with `npm list @cloudbase\u002Fnode-sdk`.\n\n---\n\n## Initialization\n\n### Inside a CloudBase cloud function\n\n```js\nconst tcb = require('@cloudbase\u002Fnode-sdk');\nconst app = tcb.init({ env: '\u003CYOUR_ENV_ID>' });\n\nexports.main = async (event, context) => {\n  const ai = app.ai();\n  \u002F\u002F Use AI features\n};\n```\n\n### Cloud function configuration for AI models\n\n⚠️ **Important:** when creating cloud functions that use AI models (especially `generateImage()` and large text generation), set a longer timeout — these operations can be slow.\n\n**Using the MCP tool `manageFunctions(action=\"createFunction\")`:**\n\nLegacy compatibility: if an older prompt still says `createFunction`, keep the same payload shape but execute it through `manageFunctions(action=\"createFunction\")`.\n\nSet `timeout` inside the `func` object:\n\n- **Parameter**: `func.timeout` (number)\n- **Unit**: seconds\n- **Range**: 1 – 900\n- **Default**: 20 seconds (usually too short for AI operations)\n\n**Recommended timeouts:**\n- **Text generation (`generateText`)**: 60 – 120 s\n- **Streaming (`streamText`)**: 60 – 120 s\n- **Image generation (`generateImage`)**: 300 – 900 s (recommended: 900 s)\n- **Combined operations**: 900 s (maximum allowed)\n\n### In a regular Node.js server\n\n```js\nconst tcb = require('@cloudbase\u002Fnode-sdk');\nconst app = tcb.init({\n  env: '\u003CYOUR_ENV_ID>',\n  secretId: '\u003CYOUR_SECRET_ID>',\n  secretKey: '\u003CYOUR_SECRET_KEY>'\n});\n\nconst ai = app.ai();\n```\n\n---\n\n## generateText() — non-streaming\n\n> **Prerequisite:** the two-step preflight (eligibility + group readiness) has passed. The example below assumes the user did not specify a model, so it uses the `cloudbase` managed group + `deepseek-v4-flash`.\n\n```js\nconst model = ai.createModel(\"cloudbase\");\n\nconst result = await model.generateText({\n  model: \"deepseek-v4-flash\",  \u002F\u002F must already be enabled in this env (DescribeAIModels → UpdateAIModel)\n  messages: [{ role: \"user\", content: \"Give me a one-paragraph intro to Li Bai.\" }],\n});\n\nconsole.log(result.text);           \u002F\u002F generated text string\nconsole.log(result.usage);          \u002F\u002F { prompt_tokens, completion_tokens, total_tokens }\nconsole.log(result.messages);       \u002F\u002F full message history\nconsole.log(result.rawResponses);   \u002F\u002F raw model responses\n```\n\n---\n\n## Error Handling Pattern\n\n```js\nconst model = ai.createModel(\"cloudbase\");\n\ntry {\n  const result = await model.generateText({\n    model: \"deepseek-v4-flash\",\n    messages: [{ role: \"user\", content: \"Summarize today's deployment logs.\" }],\n  });\n\n  console.log(result.text);\n} catch (error) {\n  console.error(\"AI request failed\", error);\n}\n```\n\n---\n\n## streamText() — streaming\n\n> **Prerequisite:** the two-step preflight has passed.\n\n```js\nconst model = ai.createModel(\"cloudbase\");\n\nconst res = await model.streamText({\n  model: \"deepseek-v4-flash\",\n  messages: [{ role: \"user\", content: \"Give me a one-paragraph intro to Li Bai.\" }],\n});\n\n\u002F\u002F Option 1: iterate the text stream (recommended)\nfor await (let text of res.textStream) {\n  console.log(text);  \u002F\u002F incremental text chunks\n}\n\n\u002F\u002F Option 2: iterate the data stream for full response chunks\nfor await (let data of res.dataStream) {\n  console.log(data);  \u002F\u002F full response chunk with metadata\n}\n\n\u002F\u002F Option 3: access final results\nconst messages = await res.messages;  \u002F\u002F full message history\nconst usage = await res.usage;        \u002F\u002F token usage\n```\n\n---\n\n## generateImage() — image generation\n\n⚠️ **Image generation is only available in the Node SDK**, not in the JS SDK (Web) or WeChat Mini Program.\n\n⚠️ **Image generation also consumes the Token Credits resource pack**, so the two-step preflight must pass before calling it. Per-call cost is higher than text and calls take longer (set cloud function timeout to 900 s).\n\n```js\nconst imageModel = ai.createImageModel(\"hunyuan-image\");\n\nconst res = await imageModel.generateImage({\n  model: \"hunyuan-image\",\n  prompt: \"A cute kitten playing on the grass\",\n  size: \"1024x1024\",\n  version: \"v1.9\",\n});\n\nconsole.log(res.data[0].url);           \u002F\u002F image URL (valid for 24 hours)\nconsole.log(res.data[0].revised_prompt);\u002F\u002F revised prompt when revise=true\n```\n\n### Image Generation Parameters\n\n```ts\ninterface HunyuanGenerateImageInput {\n  model: \"hunyuan-image\";      \u002F\u002F required\n  prompt: string;                       \u002F\u002F required: image description\n  version?: \"v1.8.1\" | \"v1.9\";         \u002F\u002F default: \"v1.8.1\"\n  size?: string;                        \u002F\u002F default: \"1024x1024\"\n  negative_prompt?: string;             \u002F\u002F v1.9 only\n  style?: string;                       \u002F\u002F v1.9 only\n  revise?: boolean;                     \u002F\u002F default: true\n  n?: number;                           \u002F\u002F default: 1\n  footnote?: string;                    \u002F\u002F watermark, max 16 chars\n  seed?: number;                        \u002F\u002F range: [1, 4294967295]\n}\n\ninterface HunyuanGenerateImageOutput {\n  id: string;\n  created: number;\n  data: Array\u003C{\n    url: string;                        \u002F\u002F image URL (24h valid)\n    revised_prompt?: string;\n  }>;\n}\n```\n\n---\n\n## Type Definitions\n\n```ts\ninterface BaseChatModelInput {\n  model: string;                        \u002F\u002F required: model name\n  messages: Array\u003CChatModelMessage>;    \u002F\u002F required: message array\n  temperature?: number;                 \u002F\u002F optional: sampling temperature\n  topP?: number;                        \u002F\u002F optional: nucleus sampling\n}\n\ntype ChatModelMessage =\n  | { role: \"user\"; content: string }\n  | { role: \"system\"; content: string }\n  | { role: \"assistant\"; content: string };\n\ninterface GenerateTextResult {\n  text: string;                         \u002F\u002F generated text\n  messages: Array\u003CChatModelMessage>;    \u002F\u002F full message history\n  usage: Usage;                         \u002F\u002F token usage\n  rawResponses: Array\u003Cunknown>;         \u002F\u002F raw model responses\n  error?: unknown;                      \u002F\u002F error if any\n}\n\ninterface StreamTextResult {\n  textStream: AsyncIterable\u003Cstring>;    \u002F\u002F incremental text stream\n  dataStream: AsyncIterable\u003CDataChunk>; \u002F\u002F full data stream\n  messages: Promise\u003CChatModelMessage[]>;\u002F\u002F final message history\n  usage: Promise\u003CUsage>;                \u002F\u002F final token usage\n  error?: unknown;                      \u002F\u002F error if any\n}\n\ninterface Usage {\n  prompt_tokens: number;\n  completion_tokens: number;\n  total_tokens: number;\n}\n```\n\n---\n\n## Best Practices\n\n1. **Run the two-step preflight before writing business code** — ① eligibility: `envQuery` → `callCloudApi(tcb, DescribeEnvPostpayPackage)` to confirm the Token Credits resource pack (text + image share the same pack); ② group readiness: `DescribeAIModels` for the `cloudbase` group and its `Models[]`, `DescribeManagedAIModelList` for the authoritative supported-model catalog, `UpdateAIModel` with a full-replacement `Models[]` + `Status: 1` when the target model is missing. If the pack is missing, return the purchase link `https:\u002F\u002Fbuy.cloud.tencent.com\u002Flowcode?buyType=resPack&envId={envId}&resourceType=token` instead of emitting SDK code and letting the user debug runtime errors.\n2. **Never assume any model is already enabled** — not `deepseek-v4-flash`, not `hunyuan-image`, not anything. Always verify with `DescribeAIModels` first; if the target is missing, look up the exact `Model` string in `DescribeManagedAIModelList` (do **not** guess the spelling) and then `UpdateAIModel` to enable it.\n3. **`createModel` accepts exactly three kinds of values** — `\"cloudbase\"` (the main managed group), `\"hunyuan-exp\"` (legacy builtin), or a user-defined GroupName registered via `CreateAIModel` (**MUST start with `custom-`**, e.g. `custom-kimi`, `custom-openai-compat`). **Never** guess with `createModel(\"deepseek\")` \u002F `createModel(\"kimi\")` \u002F `createModel(\"custom\")` — the first two are vendor\u002Fmodel names, the last is a placeholder. `createImageModel(\"hunyuan-image\")` is a separate image API — keep it as-is.\n4. **Do not invent SDK method names or parameters.** This SKILL.md is the authoritative reference for `@cloudbase\u002Fnode-sdk`'s AI surface — look up the method signature here (or in the Type Definitions section) before writing code. If a method or field is not documented here, stop and ask, or check the live contract via the MCP tools. No guessing.\n5. **Show pricing before enabling a new managed model** — `DescribeManagedAIModelList` returns `ModelSpec` (context length, max input\u002Foutput tokens) + `ModelChargingInfo` (input \u002F output \u002F cache prices, billing unit). Show the prices to the user before calling `UpdateAIModel`.\n6. **Plan timeout and quota separately for image generation** — `generateImage` costs more per call than text and takes longer. For cloud functions, set `timeout` to `900s`. HTTP-function gateways cap at 60s, so use an async-task + polling pattern. Throttle per-user concurrency and frequency to avoid burning an entire Token pack on one failure.\n7. **Prefer streaming for long-form interactions** — in HTTP-function or cloud-function SSE scenarios, use `streamText` + `for await (const chunk of result.textStream)` to flush chunks back to the client incrementally. Handle stream interruption in `catch` and close the underlying response.\n8. **Pin `@cloudbase\u002Fnode-sdk` >= 3.16.0** on the server — image generation is only available from this version. Verify with `npm ls @cloudbase\u002Fnode-sdk` to confirm the version actually loaded by the cloud function \u002F cloud run runtime — local and production can drift.\n9. **Centralize model names in config, not scattered literals.** Keep the chosen text \u002F image model in a single constant and source from `DescribeAIModels` \u002F `DescribeManagedAIModelList`. The managed catalog evolves; a single source of truth makes upgrades cheap. For models outside the managed catalog, follow the Custom Onboarding section — never hard-code third-party API keys in business code (let `CreateAIModel.Secret.ApiKey` hold them via CloudBase).\n10. **Distinguish \"preflight failure\" from \"model call failure\"** — the former means the resource pack is not active or the target model has not been enabled via `UpdateAIModel` (guide the user to purchase \u002F enable). The latter is a parameter issue or upstream error. Do not wrap both in one generic toast.\n11. **Do not log full prompts or generated text in production** — log only `usage.total_tokens` and a short prefix. Prompts can leak sensitive content; token counts can leak cost signals.\n12. **TypeScript: do NOT use `any` to silence SDK type errors.** The Node SDK ships its own types; narrow with `unknown` + a type guard, write a precise `interface` for the shape you consume, or augment types in a local `.d.ts`. Never `: any`, `as any`, `@ts-ignore`, `@ts-nocheck`. See the Engineering constitution in the `web-development` skill — it applies to backend TS too.\n13. **Self-verify before claiming done.** `tsc --noEmit` + project build + actually invoke the function (local invoke \u002F `manageFunctions(action=\"invokeFunction\")` \u002F direct HTTP hit) and confirm `usage.total_tokens > 0` and the returned text is not an error envelope. \"It should work\" without a real round-trip is not acceptable evidence.\n",{"name":5,"version":24,"alwaysApply":20,"description":7},"2.21.1","master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fskills_sh\u002Fs\u002Fskills-sh_tencentcloudbase_skills_ai-model-nodejs",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill ai-model-nodejs",{"tool":40,"command":41},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill ai-model-nodejs",{"tool":43,"command":44},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill ai-model-nodejs","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fskills_sh\u002Fs\u002Fskills-sh_tencentcloudbase_skills_ai-model-nodejs\u002FSKILL.md",true,[],[49,56,63,70,77,84],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]