[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79GN4MF18XA7AT4FC0T04N5":3,"skill-same:01M79GN4MF18XA7AT4FC0T04N5":45},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M79GN4MF18XA7AT4FC0T04N5","ai-model-web",null,"Use this skill when a browser\u002FWeb app (React, Vue, Next, Nuxt, static sites, SPAs, dashboards, AI chat UI, 页面, 前端, 网页) needs AI models via @cloudbase\u002Fjs-sdk. Default routing for Web\u002Ffrontend AI — call directly from the browser, do NOT propose a Node.js proxy. Covers generateText and streamText; models via ai.createModel with groups cloudbase, the legacy hunyuan-v3 \u002F hunyuan-exp, or custom-*, model id in the `model` field. MUST run two-step preflight before code — see body. NOT for Node.js backend (use ai-model-nodejs), Mini Program (use ai-model-wechat), or image generation (Node SDK only).","infometa\u002Fworkbuddyskills","infometa","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F109397516?v=4","01M79FS3XQK361MJFWQ2GFK95C","01M79FS3YPWKZYW9EPAAP2BFBJ",447,"MIT","https:\u002F\u002Fgithub.com\u002Finfometa\u002Fworkbuddyskills\u002Fblob\u002Fmain\u002Fconnectors\u002Fcloudbase\u002Fskills\u002Freferences\u002Fai-model-web\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: ai-model-web\ndescription: \"Use this skill when a browser\u002FWeb app (React, Vue, Next, Nuxt, static sites, SPAs, dashboards, AI chat UI, 页面, 前端, 网页) needs AI models via @cloudbase\u002Fjs-sdk. Default routing for Web\u002Ffrontend AI — call directly from the browser, do NOT propose a Node.js proxy. Covers generateText and streamText; models via ai.createModel with groups cloudbase, the legacy hunyuan-v3 \u002F hunyuan-exp, or custom-*, model id in the `model` field. MUST run two-step preflight before code — see body. NOT for Node.js backend (use ai-model-nodejs), Mini Program (use ai-model-wechat), or image generation (Node SDK only).\"\nversion: 2.36.2\nlicense: MIT\nalwaysApply: false\n---\n\n## Sibling skills (local only)\n\nSibling CloudBase skills ship beside this skill. Use local relative paths such as `..\u002Fauth-tool-cloudbase\u002FSKILL.md`.\n\nIf a referenced sibling skill file is missing from this environment, ask the user to install the full CloudBase plugin (or the missing skill). Do **not** HTTP-fetch remote skill or protocol markdown into the agent context.\n\n## When to use this skill\n\nUse this skill for **calling AI models in browser\u002FWeb applications** via `@cloudbase\u002Fjs-sdk`.\n\n> 🧭 **Runtime-plane default for Web.** Any time the user's request is framed around a page, a Web app, the frontend, React\u002FVue\u002FNext\u002FNuxt, a dashboard UI, or \"add AI to my H5\", this skill is the default routing target. **Do NOT first propose a Node.js \u002F cloud-function \u002F CloudRun proxy**; `@cloudbase\u002Fjs-sdk` can call the model from the browser directly. Only switch to `ai-model-nodejs` if the user explicitly asks for a backend\u002Fserver call, image generation, or a scenario that truly needs server-side keys or long-running work. This decision is independent of which concrete model the user picks — model names (`deepseek-*`, `glm-*`, `hunyuan-*`, `kimi-*`, …) only affect the `model` field, not the routing plane.\n\n**Use it when you need to:**\n\n- Integrate AI text generation into a frontend Web app\n- Stream AI responses for a better UX\n- Call Hunyuan \u002F DeepSeek \u002F GLM \u002F Kimi \u002F MiniMax models from the browser\n\n**Do NOT use for:**\n\n- Node.js backend or cloud functions → use the `ai-model-nodejs` skill\n- WeChat Mini Program → use the `ai-model-wechat` skill\n- Image generation → use the `ai-model-nodejs` skill (Node SDK only)\n- Runtimes without a CloudBase SDK (native apps, Python, Go, etc.) → use the `http-api-cloudbase` skill (it now includes the `ai_model` OpenAPI spec for direct HTTP calls; do NOT build a custom 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. The single most common mistake when agents generate code for this SDK is hallucinating the argument. There are **exactly four** 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 new 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-v3\"` | **Legacy plan group, being retired.** Only `hy3` is available and the platform adds no new models to it. Existing code keeps working — new code should use `cloudbase` + `{ model: \"hy3\" }`. |\n| `\"hunyuan-exp\"` | Only if `DescribeAIModels` explicitly returns this older legacy builtin group for the current env. Its original default model `hunyuan-2.0-instruct-20251111` is **offline** (2026-05-31) — never target that id. |\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### ❌ 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 — that's a model name, goes in the `model` field\nai.createModel(\"hunyuan\")                  \u002F\u002F wrong — vendor family, not a GroupName\nai.createModel(\"hunyuan-2.0-instruct-20251111\")  \u002F\u002F wrong — model name\nai.createModel(\"glm\") \u002F ai.createModel(\"kimi\") \u002F ai.createModel(\"minimax\")  \u002F\u002F wrong — vendor names\nai.createModel(\"openai\") \u002F ai.createModel(\"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: \"hy3\" }`, `{ model: \"kimi-k2.6\" }`, `{ model: \"glm-5\" }`, …\n4. **Never assume the model is already enabled.** Before writing the SDK call, 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), then enable it via `UpdateAIModel` with `Status: 1` (remember `Models` is a full replacement, so resend everything already enabled + the new one).\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 four legal values above.\n\n---\n\n## Mandatory Two-Step Preflight (before any SDK code)\n\nBefore generating any AI-related SDK code, **run the two-step preflight**: ① eligibility, ② group readiness. Emitting `createModel(...)` straight away and letting the user debug runtime errors is significantly more costly.\n\n### Step 0: obtain the environment ID\n\nCall the MCP tool `queryEnv` with `action=info` and read `EnvId` from the response. Every subsequent check and purchase link uses this `EnvId`.\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` \u002F `envPostpayPackageInfoList`) and trust the live response. For the Mini Program scenario there is an additional growth-plan branch — switch to the `ai-model-wechat` skill.\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[]`, where each `AIModelGroup` includes `GroupName`, `Type` (`builtin` \u002F `custom`), `Models: [{ Model, EnableMCP, Tags }]`, `Status` (1 = on \u002F 2 = off), `BaseUrl`, `Secret`, `Remark`. The main managed `GroupName` is `cloudbase`.\n\n2. **Never assume a model is already enabled.** Inspect `AIModelGroups[?].Models[].Model` for the `cloudbase` group. If the target model (or, when the user did not specify one, the model you intend to default to such as `deepseek-v4-flash`) is missing, jump to step 4 and enable it — do not call `createModel(\"cloudbase\")` yet. If the `cloudbase` group itself is missing or has `Status=2`, also jump to step 4.\n\n3. **User asked for a model that belongs to the managed catalog** (e.g. `deepseek-v3.2`, `hy3`, `glm-5`, `kimi-k2.6`, …): 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** — verify the canonical spelling in `DescribeManagedAIModelList` first (step 4 covers this).\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[]`, where each group lists `GroupName` (e.g. `cloudbase`), `Remark`, and `Models: [{ Model, EnableMCP, ModelSpec{ContextLength, MaxInputToken, MaxOutputToken}, ModelChargingInfo[{Type, InputPrice, OutputPrice, InputOutputUnit, CachePrice}] }]`. **This is the single source of truth for supported model names and pricing — do not infer them from memory. Use the exact `Model` string returned here when calling `UpdateAIModel`.** Also 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, e.g. deepseek-v4-flash>\" },\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 (`EnvId` \u002F `GroupName` \u002F `Models` \u002F `Status`). Fall back to camelCase only if the call returns `InvalidParameter`.\n\n---\n\n## Available Providers and Models\n\n`ai.createModel(\u003CGroupName>)` accepts exactly four kinds of legal values:\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** in application code; 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-v3\"` — legacy plan group (being retired)\n\n- Only `hy3`; the group gets no new models and is on its way out. Migration target is `cloudbase` + `{ model: \"hy3\" }`\n- Still legal for existing code — do **not** \"fix\" `createModel(\"hunyuan-v3\")` into `createModel(\"hy3\")`; `hy3` is a model id, not a GroupName\n- Mainly matters for Mini Program Growth Plan environments (see `ai-model-wechat`)\n\n### 3. `\"hunyuan-exp\"` — older legacy builtin group (kept for compatibility)\n\n- Do not use it from Web unless the env explicitly still returns it (switch to the `ai-model-wechat` skill for that flow)\n- Its original default `hunyuan-2.0-instruct-20251111` went **offline on 2026-05-31** — never target that model id. Whatever models the group still exposes must be read from `DescribeAIModels({ GroupName: \"hunyuan-exp\" }).Models[]`\n\n### 4. 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 (`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> **Never** write guesses like `createModel(\"deepseek\")` or `createModel(\"custom\")` unless `DescribeAIModels` explicitly returned that exact `GroupName` (old envs may still carry historical `deepseek` \u002F `hunyuan-exp` builtin groups — that stays legal for compatibility, but new projects should always go through `cloudbase`).\n\n---\n\n## Custom onboarding (models outside the managed catalog)\n\nWhen the user wants to call a **non-managed** 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\u002Fjs-sdk\n```\n\n## Initialization\n\n> ⚠️ **Do not use anonymous sign-in as the default.** Anonymous login is **disabled by default** for new environments, and inactive existing environments have also been automatically disabled. Even when anonymous login is manually enabled, **anonymous users are denied AI model invocation permissions by default**. The AI-model skill does **not** prescribe a specific login UI — delegate that concern:\n>\n> - **Enabling \u002F configuring login providers** (phone SMS, email, WeChat Open Platform, username+password, OAuth, …) → follow the **`auth-tool-cloudbase`** skill (backend config via `callCloudApi`).\n> - **Building the actual sign-in flow in the browser** (login form, callbacks, session guarding) → follow the **`auth-web-cloudbase`** skill (`@cloudbase\u002Fjs-sdk` auth API, e.g. `signInWithPassword`, `signInWithPhone`, `getSession`).\n>\n> Do **not** fall back to `signInAnonymously()` for AI features — anonymous users cannot call AI models. Only use anonymous login for non-AI read-only demos where the user explicitly requests it and accepts the trade-off.\n\n```js\nimport cloudbase from \"@cloudbase\u002Fjs-sdk\";\n\nconst app = cloudbase.init({\n  env: \"\u003CYOUR_ENV_ID>\",\n  accessKey: import.meta.env.VITE_PUBLISHABLE_KEY  \u002F\u002F auto-provision via queryAppAuth \u002F manageAppAuth, write to .env.local (see auth-web-cloudbase prerequisites)\n});\n\nconst auth = app.auth;\n\n\u002F\u002F CRITICAL: Use auth.getSession() to check login — NOT the deprecated getLoginState().\n\u002F\u002F getLoginState() returns uid even without real login (just accessKey), causing false positives.\n\u002F\u002F getSession() returns data.session === undefined when no real login exists.\n\u002F\u002F Anonymous users are DENIED AI model permissions — calling AI without real login will fail.\nconst { data: sessionData } = await auth.getSession();\nif (!sessionData?.session || sessionData.session.user?.is_anonymous) {\n  \u002F\u002F No real login or anonymous session — route to sign-in page\n  window.location.href = \"\u002Flogin\";\n  return;\n}\n\nconst ai = app.ai();\n```\n\n**Important notes:**\n\n- Use synchronous initialization with a top-level import\n- **`accessKey` causes `getLoginState()` to return misleading auth data** — the deprecated `getLoginState()` returns an object with `uid` even without real login, which breaks naive `!!loginState` checks. Use `auth.getSession()` instead: it returns `data.session === undefined` when no real login exists, so `!!data.session` is a reliable auth gate.\n- The user MUST be authenticated with a verified login (phone, email, WeChat, username+password, custom) before using AI features. Anonymous users are denied AI model permissions. The exact flow is the responsibility of the `auth-web-cloudbase` skill.\n- Get `accessKey` from the CloudBase console\n\n---\n\n## generateText() — non-streaming\n\n> **Prerequisite:** the two-step preflight (eligibility + group readiness) has passed, and the target model has been confirmed present in `DescribeAIModels({ GroupName: \"cloudbase\" }).Models[]` — if it was not, it should already have been enabled via `UpdateAIModel`. The example below uses `deepseek-v4-flash` only for illustration; substitute the actual model the user asked for.\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## 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## 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: \"Generate a concise onboarding checklist.\" }],\n  });\n\n  console.log(result.text);\n} catch (error) {\n  console.error(\"Failed to call CloudBase AI from Web\", error);\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 first** — ① eligibility (Token Credits resource pack via `DescribeEnvPostpayPackage`) + ② group readiness (`DescribeAIModels` to inspect what is enabled, `DescribeManagedAIModelList` for the authoritative supported-model catalog, `UpdateAIModel` with a full-replacement `Models[]` and `Status: 1` when the target model is missing). Skipping preflight leads straight to \"model not found\" \u002F \"model not enabled\" errors at runtime.\n2. **Never assume any model is already enabled** — not `deepseek-v4-flash`, not `hunyuan-*`, 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 or invent vendor prefixes) and then `UpdateAIModel` to enable it.\n3. **`createModel` accepts exactly four kinds of values** — `\"cloudbase\"` (the main managed group), `\"hunyuan-v3\"` (legacy plan group, only `hy3`, being retired), `\"hunyuan-exp\"` (older 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\")`.\n4. **Do not invent SDK method names or parameters.** This SKILL.md is the authoritative reference for `@cloudbase\u002Fjs-sdk`'s AI surface — look up the method signature here (or in the Type Definitions section below) 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). Surface the prices to the user before calling `UpdateAIModel`.\n6. **Use streaming for long responses** — better perceived latency and interactivity.\n7. **Handle errors gracefully** — wrap AI calls in try\u002Fcatch.\n8. **Keep `accessKey` safe** — use a publishable key, never a secret key.\n9. **Initialize early** — set up the SDK at app entry so auth and AI are both ready before routing.\n10. **Do NOT use anonymous auth for AI features** — anonymous login is disabled by default for new environments, and anonymous users are denied AI model permissions. Require a verified sign-in (phone, email, username+password, WeChat, custom) before calling any AI API. Delegate provider configuration to the `auth-tool-cloudbase` skill and the browser sign-in flow to the `auth-web-cloudbase` skill; the AI-model skill checks `auth.getSession()` and verifies `loginType` before gating the call.\n11. **Distinguish \"preflight failure\" from \"model call failure\"** — the former means the user needs to buy a resource pack or call `UpdateAIModel`; the latter is a prompt \u002F parameter \u002F network issue. Give the user different guidance for each.\n12. **TypeScript: do NOT use `any` to silence type errors from the SDK.** The SDK ships its own types; if an error shows up, narrow with `unknown` + a type guard, write a precise `interface` for the shape you actually consume, or augment types in a local `.d.ts`. Never `: any`, `as any`, `@ts-ignore`, or `@ts-nocheck`. See the Engineering constitution in the `web-development` skill.\n13. **Self-verify before claiming done.** Run `tsc --noEmit` + the project build + open the page with `agent-browser` and actually trigger the AI call. Confirm: (a) the text stream reaches the UI, (b) no new console errors, (c) `result.usage` is non-zero. Saying \"it should work\" without evidence is not acceptable — follow `web-development\u002Fbrowser-testing.md`.\n","## Sibling skills (local only)\n\nSibling CloudBase skills ship beside this skill. Use local relative paths such as `..\u002Fauth-tool-cloudbase\u002FSKILL.md`.\n\nIf a referenced sibling skill file is missing from this environment, ask the user to install the full CloudBase plugin (or the missing skill). Do **not** HTTP-fetch remote skill or protocol markdown into the agent context.\n\n## When to use this skill\n\nUse this skill for **calling AI models in browser\u002FWeb applications** via `@cloudbase\u002Fjs-sdk`.\n\n> 🧭 **Runtime-plane default for Web.** Any time the user's request is framed around a page, a Web app, the frontend, React\u002FVue\u002FNext\u002FNuxt, a dashboard UI, or \"add AI to my H5\", this skill is the default routing target. **Do NOT first propose a Node.js \u002F cloud-function \u002F CloudRun proxy**; `@cloudbase\u002Fjs-sdk` can call the model from the browser directly. Only switch to `ai-model-nodejs` if the user explicitly asks for a backend\u002Fserver call, image generation, or a scenario that truly needs server-side keys or long-running work. This decision is independent of which concrete model the user picks — model names (`deepseek-*`, `glm-*`, `hunyuan-*`, `kimi-*`, …) only affect the `model` field, not the routing plane.\n\n**Use it when you need to:**\n\n- Integrate AI text generation into a frontend Web app\n- Stream AI responses for a better UX\n- Call Hunyuan \u002F DeepSeek \u002F GLM \u002F Kimi \u002F MiniMax models from the browser\n\n**Do NOT use for:**\n\n- Node.js backend or cloud functions → use the `ai-model-nodejs` skill\n- WeChat Mini Program → use the `ai-model-wechat` skill\n- Image generation → use the `ai-model-nodejs` skill (Node SDK only)\n- Runtimes without a CloudBase SDK (native apps, Python, Go, etc.) → use the `http-api-cloudbase` skill (it now includes the `ai_model` OpenAPI spec for direct HTTP calls; do NOT build a custom 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. The single most common mistake when agents generate code for this SDK is hallucinating the argument. There are **exactly four** 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 new 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-v3\"` | **Legacy plan group, being retired.** Only `hy3` is available and the platform adds no new models to it. Existing code keeps working — new code should use `cloudbase` + `{ model: \"hy3\" }`. |\n| `\"hunyuan-exp\"` | Only if `DescribeAIModels` explicitly returns this older legacy builtin group for the current env. Its original default model `hunyuan-2.0-instruct-20251111` is **offline** (2026-05-31) — never target that id. |\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### ❌ 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 — that's a model name, goes in the `model` field\nai.createModel(\"hunyuan\")                  \u002F\u002F wrong — vendor family, not a GroupName\nai.createModel(\"hunyuan-2.0-instruct-20251111\")  \u002F\u002F wrong — model name\nai.createModel(\"glm\") \u002F ai.createModel(\"kimi\") \u002F ai.createModel(\"minimax\")  \u002F\u002F wrong — vendor names\nai.createModel(\"openai\") \u002F ai.createModel(\"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: \"hy3\" }`, `{ model: \"kimi-k2.6\" }`, `{ model: \"glm-5\" }`, …\n4. **Never assume the model is already enabled.** Before writing the SDK call, 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), then enable it via `UpdateAIModel` with `Status: 1` (remember `Models` is a full replacement, so resend everything already enabled + the new one).\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 four legal values above.\n\n---\n\n## Mandatory Two-Step Preflight (before any SDK code)\n\nBefore generating any AI-related SDK code, **run the two-step preflight**: ① eligibility, ② group readiness. Emitting `createModel(...)` straight away and letting the user debug runtime errors is significantly more costly.\n\n### Step 0: obtain the environment ID\n\nCall the MCP tool `queryEnv` with `action=info` and read `EnvId` from the response. Every subsequent check and purchase link uses this `EnvId`.\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` \u002F `envPostpayPackageInfoList`) and trust the live response. For the Mini Program scenario there is an additional growth-plan branch — switch to the `ai-model-wechat` skill.\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[]`, where each `AIModelGroup` includes `GroupName`, `Type` (`builtin` \u002F `custom`), `Models: [{ Model, EnableMCP, Tags }]`, `Status` (1 = on \u002F 2 = off), `BaseUrl`, `Secret`, `Remark`. The main managed `GroupName` is `cloudbase`.\n\n2. **Never assume a model is already enabled.** Inspect `AIModelGroups[?].Models[].Model` for the `cloudbase` group. If the target model (or, when the user did not specify one, the model you intend to default to such as `deepseek-v4-flash`) is missing, jump to step 4 and enable it — do not call `createModel(\"cloudbase\")` yet. If the `cloudbase` group itself is missing or has `Status=2`, also jump to step 4.\n\n3. **User asked for a model that belongs to the managed catalog** (e.g. `deepseek-v3.2`, `hy3`, `glm-5`, `kimi-k2.6`, …): 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** — verify the canonical spelling in `DescribeManagedAIModelList` first (step 4 covers this).\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[]`, where each group lists `GroupName` (e.g. `cloudbase`), `Remark`, and `Models: [{ Model, EnableMCP, ModelSpec{ContextLength, MaxInputToken, MaxOutputToken}, ModelChargingInfo[{Type, InputPrice, OutputPrice, InputOutputUnit, CachePrice}] }]`. **This is the single source of truth for supported model names and pricing — do not infer them from memory. Use the exact `Model` string returned here when calling `UpdateAIModel`.** Also 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, e.g. deepseek-v4-flash>\" },\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 (`EnvId` \u002F `GroupName` \u002F `Models` \u002F `Status`). Fall back to camelCase only if the call returns `InvalidParameter`.\n\n---\n\n## Available Providers and Models\n\n`ai.createModel(\u003CGroupName>)` accepts exactly four kinds of legal values:\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** in application code; 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-v3\"` — legacy plan group (being retired)\n\n- Only `hy3`; the group gets no new models and is on its way out. Migration target is `cloudbase` + `{ model: \"hy3\" }`\n- Still legal for existing code — do **not** \"fix\" `createModel(\"hunyuan-v3\")` into `createModel(\"hy3\")`; `hy3` is a model id, not a GroupName\n- Mainly matters for Mini Program Growth Plan environments (see `ai-model-wechat`)\n\n### 3. `\"hunyuan-exp\"` — older legacy builtin group (kept for compatibility)\n\n- Do not use it from Web unless the env explicitly still returns it (switch to the `ai-model-wechat` skill for that flow)\n- Its original default `hunyuan-2.0-instruct-20251111` went **offline on 2026-05-31** — never target that model id. Whatever models the group still exposes must be read from `DescribeAIModels({ GroupName: \"hunyuan-exp\" }).Models[]`\n\n### 4. 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 (`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> **Never** write guesses like `createModel(\"deepseek\")` or `createModel(\"custom\")` unless `DescribeAIModels` explicitly returned that exact `GroupName` (old envs may still carry historical `deepseek` \u002F `hunyuan-exp` builtin groups — that stays legal for compatibility, but new projects should always go through `cloudbase`).\n\n---\n\n## Custom onboarding (models outside the managed catalog)\n\nWhen the user wants to call a **non-managed** 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\u002Fjs-sdk\n```\n\n## Initialization\n\n> ⚠️ **Do not use anonymous sign-in as the default.** Anonymous login is **disabled by default** for new environments, and inactive existing environments have also been automatically disabled. Even when anonymous login is manually enabled, **anonymous users are denied AI model invocation permissions by default**. The AI-model skill does **not** prescribe a specific login UI — delegate that concern:\n>\n> - **Enabling \u002F configuring login providers** (phone SMS, email, WeChat Open Platform, username+password, OAuth, …) → follow the **`auth-tool-cloudbase`** skill (backend config via `callCloudApi`).\n> - **Building the actual sign-in flow in the browser** (login form, callbacks, session guarding) → follow the **`auth-web-cloudbase`** skill (`@cloudbase\u002Fjs-sdk` auth API, e.g. `signInWithPassword`, `signInWithPhone`, `getSession`).\n>\n> Do **not** fall back to `signInAnonymously()` for AI features — anonymous users cannot call AI models. Only use anonymous login for non-AI read-only demos where the user explicitly requests it and accepts the trade-off.\n\n```js\nimport cloudbase from \"@cloudbase\u002Fjs-sdk\";\n\nconst app = cloudbase.init({\n  env: \"\u003CYOUR_ENV_ID>\",\n  accessKey: import.meta.env.VITE_PUBLISHABLE_KEY  \u002F\u002F auto-provision via queryAppAuth \u002F manageAppAuth, write to .env.local (see auth-web-cloudbase prerequisites)\n});\n\nconst auth = app.auth;\n\n\u002F\u002F CRITICAL: Use auth.getSession() to check login — NOT the deprecated getLoginState().\n\u002F\u002F getLoginState() returns uid even without real login (just accessKey), causing false positives.\n\u002F\u002F getSession() returns data.session === undefined when no real login exists.\n\u002F\u002F Anonymous users are DENIED AI model permissions — calling AI without real login will fail.\nconst { data: sessionData } = await auth.getSession();\nif (!sessionData?.session || sessionData.session.user?.is_anonymous) {\n  \u002F\u002F No real login or anonymous session — route to sign-in page\n  window.location.href = \"\u002Flogin\";\n  return;\n}\n\nconst ai = app.ai();\n```\n\n**Important notes:**\n\n- Use synchronous initialization with a top-level import\n- **`accessKey` causes `getLoginState()` to return misleading auth data** — the deprecated `getLoginState()` returns an object with `uid` even without real login, which breaks naive `!!loginState` checks. Use `auth.getSession()` instead: it returns `data.session === undefined` when no real login exists, so `!!data.session` is a reliable auth gate.\n- The user MUST be authenticated with a verified login (phone, email, WeChat, username+password, custom) before using AI features. Anonymous users are denied AI model permissions. The exact flow is the responsibility of the `auth-web-cloudbase` skill.\n- Get `accessKey` from the CloudBase console\n\n---\n\n## generateText() — non-streaming\n\n> **Prerequisite:** the two-step preflight (eligibility + group readiness) has passed, and the target model has been confirmed present in `DescribeAIModels({ GroupName: \"cloudbase\" }).Models[]` — if it was not, it should already have been enabled via `UpdateAIModel`. The example below uses `deepseek-v4-flash` only for illustration; substitute the actual model the user asked for.\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## 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## 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: \"Generate a concise onboarding checklist.\" }],\n  });\n\n  console.log(result.text);\n} catch (error) {\n  console.error(\"Failed to call CloudBase AI from Web\", error);\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 first** — ① eligibility (Token Credits resource pack via `DescribeEnvPostpayPackage`) + ② group readiness (`DescribeAIModels` to inspect what is enabled, `DescribeManagedAIModelList` for the authoritative supported-model catalog, `UpdateAIModel` with a full-replacement `Models[]` and `Status: 1` when the target model is missing). Skipping preflight leads straight to \"model not found\" \u002F \"model not enabled\" errors at runtime.\n2. **Never assume any model is already enabled** — not `deepseek-v4-flash`, not `hunyuan-*`, 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 or invent vendor prefixes) and then `UpdateAIModel` to enable it.\n3. **`createModel` accepts exactly four kinds of values** — `\"cloudbase\"` (the main managed group), `\"hunyuan-v3\"` (legacy plan group, only `hy3`, being retired), `\"hunyuan-exp\"` (older 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\")`.\n4. **Do not invent SDK method names or parameters.** This SKILL.md is the authoritative reference for `@cloudbase\u002Fjs-sdk`'s AI surface — look up the method signature here (or in the Type Definitions section below) 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). Surface the prices to the user before calling `UpdateAIModel`.\n6. **Use streaming for long responses** — better perceived latency and interactivity.\n7. **Handle errors gracefully** — wrap AI calls in try\u002Fcatch.\n8. **Keep `accessKey` safe** — use a publishable key, never a secret key.\n9. **Initialize early** — set up the SDK at app entry so auth and AI are both ready before routing.\n10. **Do NOT use anonymous auth for AI features** — anonymous login is disabled by default for new environments, and anonymous users are denied AI model permissions. Require a verified sign-in (phone, email, username+password, WeChat, custom) before calling any AI API. Delegate provider configuration to the `auth-tool-cloudbase` skill and the browser sign-in flow to the `auth-web-cloudbase` skill; the AI-model skill checks `auth.getSession()` and verifies `loginType` before gating the call.\n11. **Distinguish \"preflight failure\" from \"model call failure\"** — the former means the user needs to buy a resource pack or call `UpdateAIModel`; the latter is a prompt \u002F parameter \u002F network issue. Give the user different guidance for each.\n12. **TypeScript: do NOT use `any` to silence type errors from the SDK.** The SDK ships its own types; if an error shows up, narrow with `unknown` + a type guard, write a precise `interface` for the shape you actually consume, or augment types in a local `.d.ts`. Never `: any`, `as any`, `@ts-ignore`, or `@ts-nocheck`. See the Engineering constitution in the `web-development` skill.\n13. **Self-verify before claiming done.** Run `tsc --noEmit` + the project build + open the page with `agent-browser` and actually trigger the AI call. Confirm: (a) the text stream reaches the UI, (b) no new console errors, (c) `result.usage` is non-zero. Saying \"it should work\" without evidence is not acceptable — follow `web-development\u002Fbrowser-testing.md`.\n",{"name":5,"license":14,"version":23,"alwaysApply":19,"description":7},"2.36.2","main","33b6151ccee9aa0816c6f32d021be77d82772755","connectors\u002Fcloudbase\u002Fskills\u002Freferences\u002Fai-model-web",138,"https:\u002F\u002Fgithub.com\u002Finfometa\u002Fworkbuddyskills","https:\u002F\u002Fgithub.com\u002Finfometa","2026-11-11 03:15:35",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add infometa\u002Fworkbuddyskills --skill ai-model-web",{"tool":37,"command":38},"bunx","bunx skills add infometa\u002Fworkbuddyskills --skill ai-model-web",{"tool":40,"command":41},"pnpm","pnpm dlx skills add infometa\u002Fworkbuddyskills --skill ai-model-web","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Finfometa\u002Fworkbuddyskills\u002Fblob\u002Fmain\u002Fconnectors\u002Fcloudbase\u002Fskills\u002Freferences\u002Fai-model-web\u002FSKILL.md",true,[],[46,53,60,67,74,83],{"skillNo":47,"name":48,"nameZh":6,"description":49,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":50,"categories":51,"keywords":52,"publishedAt":18},"01M7A1EC013S1PBBTSH2PA2S7D","yingmi-skill","当用户需要查询基金、策略、公告、财经资讯，做资产配置、组合诊断、风险回测、现金流分析，或生成图表、PDF 时，优先使用本 Skill 获取真实数据与可执行能力。","https:\u002F\u002Fgithub.com\u002Finfometa\u002Fworkbuddyskills\u002Fblob\u002Fmain\u002Fskills\u002Fyingmi-skill\u002FSKILL.md",[],[],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":18},"01M7A194T67P6NRVYK8KCTH3CH","web-access","所有联网操作必须通过此 skill 处理，包括：搜索、网页抓取、登录后操作、网络交互等。","https:\u002F\u002Fgithub.com\u002Finfometa\u002Fworkbuddyskills\u002Fblob\u002Fmain\u002Fskills\u002Fweb-access\u002FSKILL.md",[],[],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":18},"01M7A14FATMDD6FK8QAGXY5GVR","tencentmap-map-assistant","腾讯位置服务·地图助手 Skill，一句自然语言调用腾讯地图全套能力，无需开发者账号、开箱即用。提供 AI 旅游攻略、地点搜索（含评分\u002F人均\u002F营业时间）、关键词提示、路线规划（驾车\u002F步行\u002F公交\u002F骑行）、地址解析与逆解析、行政区划、IP 定位、距离计算、天气查询，并可将行程或多 POI 渲染成网页地图。涉及找地点、规划路线、旅游行程、查天气、坐标转换等出行场景时使用。","https:\u002F\u002Fgithub.com\u002Finfometa\u002Fworkbuddyskills\u002Fblob\u002Fmain\u002Fskills\u002Ftencentmap-map-assistant\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M7A0SX4XW5053MZ2S921EDH2","skill-scanner","Scan any agent skill for security risks before you install or use it. Powered by Tencent Zhuque Lab A.I.G (AI-Infra-Guard). 100% local static analysis — no file contents or credentials leave your device. Compatible with CodeBuddy, Cursor, Windsurf, Claude Code, OpenClaw and more. Triggers on: 这个 skill 安全吗, skill 安全扫描, 检查 skill 安全, audit skill, scan skill, check skill safety, analyze skill, inspect skill, verify skill, skill security, skill supply chain. Do NOT trigger for general agent usage, full system health checks, project debugging, or normal development.","https:\u002F\u002Fgithub.com\u002Finfometa\u002Fworkbuddyskills\u002Fblob\u002Fmain\u002Fskills\u002Fskill-scanner\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":78,"licenseFileUrl":79,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":18},"01M7A0SQC2CZB3450G8471673M","skill-creator","Guide for creating effective skills. This skill should be used when users want to create a new skill (or update an existing skill) that extends agent capabilities with specialized knowledge, workflows, or tool integrations.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Finfometa\u002Fworkbuddyskills\u002Fblob\u002Fmain\u002Fskills\u002Fskill-creator\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Finfometa\u002Fworkbuddyskills\u002Fblob\u002Fmain\u002Fskills\u002Fskill-creator\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":18},"01M7A0RHV7BKS7DFQF9X9QCCNN","shader-dev","Comprehensive GLSL shader techniques for creating stunning visual effects — ray marching, SDF modeling, fluid simulation, particle systems, procedural generation, lighting, post-processing, and more.","https:\u002F\u002Fgithub.com\u002Finfometa\u002Fworkbuddyskills\u002Fblob\u002Fmain\u002Fskills\u002Fshader-dev\u002FSKILL.md",[],[]]