[
  {
    "category": "Framework Integration,Web Frameworks,UniApp",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 5,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/api-reference/webv2/adapter/uniapp-adapter",
    "content": [
      {
        "markdown": "`@cloudbase/js-sdk` Combine with `@cloudbase/adapter-uni-app` allows you toin uni-app project",
        "index": 1,
        "title": "Install SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```bash\nnpm i @cloudbase/js-sdk @cloudbase/adapter-uni-app\n```",
            "index": 1,
            "title": "npm",
            "content": []
          },
          {
            "markdown": "```bash\nyarn add @cloudbase/js-sdk @cloudbase/adapter-uni-app\n```",
            "index": 2,
            "title": "yarn",
            "content": []
          },
          {
            "markdown": "```bash\npnpm add @cloudbase/js-sdk @cloudbase/adapter-uni-app\n```",
            "index": 3,
            "title": "pnpm",
            "content": []
          }
        ]
      },
      {
        "markdown": "Add the following code to your uni-app project",
        "index": 2,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nimport cloudbaseSDK from \"@cloudbase/js-sdk\";\nimport adapter from \"@cloudbase/adapter-uni-app\";\n\n// passed inConfigurationoption\nconst options = {\n  uni: uni // passed in uni object，for imageVerification codeFunction\n};\n\ncloudbaseSDK.useAdapters(adapter, options);\n\nconst cloudbase = cloudbaseSDK.init({\n  // Environment ID\n  env: \"{%ENV_ID%}\",\n  // region\n  region: \"{%REGION%}\",\n  // Anonymous access token\n  accessKey: \"{%PUBLISHABLE_KEY%}\"\n});\n\nexport default cloudbase;\n```",
            "index": 1,
            "title": "./utils/cloudbase.js",
            "content": []
          }
        ]
      },
      {
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table first 10 records\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\nconsole.log(res.data);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"getData\">Query Data</button>\n    <view v-if=\"dataList.length > 0\">\n      <view v-for=\"(item, index) in dataList\" :key=\"index\" class=\"data-item\">\n        <text>{{ JSON.stringify(item) }}</text>\n      </view>\n    </view>\n    <text v-else>temporarilyNoneData</text>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataList: []\n    };\n  },\n  methods: {\n    // Query Data\n    async getData() {\n      try {\n        const { data, error } = await cloudbase\n          .database()\n          .from(\"{%TABLE_NAME%}\")\n          .select(\"*\")\n          .limit(10);\n\n        if (!error) {\n          this.dataList = data;\n          uni.showToast({\n            title: \"Querysuccessful\",\n            icon: \"success\"\n          });\n        } else {\n          uni.showToast({\n            title: \"Queryfailed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        uni.showToast({\n          title: \"Queryfailed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} table data\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({ title: \"Example Title\" });\nconsole.log(`Insert successful! id: ${res.id}`);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Title：</text>\n      <input v-model=\"title\" placeholder=\"Please enterTitle\" />\n    </view>\n    <button :disabled=\"!title\" @click=\"addData\">Insert Data</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      title: \"\"\n    };\n  },\n  methods: {\n    // Insert Data\n    async addData() {\n      try {\n        const { data, error } = await cloudbase\n          .database()\n          .from(\"{%TABLE_NAME%}\")\n          .insert({ title: this.title });\n\n        if (!error) {\n          uni.showToast({\n            title: \"Insert successful\",\n            icon: \"success\"\n          });\n          this.title = \"\";\n        } else {\n          uni.showToast({\n            title: \"Insert failed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        uni.showToast({\n          title: \"Insert failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} table id with specified value\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ title: \"New Title\" })\n  .eq(\"id\", \"<data id>\");\nif (!error) {\n  console.log(\"Update successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>DataID：</text>\n      <input v-model=\"dataId\" placeholder=\"Please enterDataID\" />\n    </view>\n    <view>\n      <text>New Title：</text>\n      <input v-model=\"newTitle\" placeholder=\"Please enterNew Title\" />\n    </view>\n    <button :disabled=\"!dataId || !newTitle\" @click=\"updateData\">\n      Update Data\n    </button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataId: \"\",\n      newTitle: \"\"\n    };\n  },\n  methods: {\n    // Update Data\n    async updateData() {\n      try {\n        const { data, error } = await cloudbase\n          .database()\n          .from(\"{%TABLE_NAME%}\")\n          .update({ title: this.newTitle })\n          .eq(\"id\", this.dataId);\n\n        if (!error) {\n          uni.showToast({\n            title: \"Update successful\",\n            icon: \"success\"\n          });\n          this.dataId = \"\";\n          this.newTitle = \"\";\n        } else {\n          uni.showToast({\n            title: \"Update failed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        uni.showToast({\n          title: \"Update failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Example Title\" });\nif (!error) {\n  console.log(\"Operation successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>ID：</text>\n      <input v-model=\"id\" type=\"number\" placeholder=\"Please enterID\" />\n    </view>\n    <view>\n      <text>Title：</text>\n      <input v-model=\"title\" placeholder=\"Please enterTitle\" />\n    </view>\n    <button :disabled=\"!id || !title\" @click=\"upsertData\">UpdateorCreate</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      id: \"\",\n      title: \"\"\n    };\n  },\n  methods: {\n    // Upsert Data\n    async upsertData() {\n      try {\n        const { data, error } = await cloudbase\n          .database()\n          .from(\"{%TABLE_NAME%}\")\n          .upsert({ id: parseInt(this.id), title: this.title });\n\n        if (!error) {\n          uni.showToast({\n            title: \"Operation successful\",\n            icon: \"success\"\n          });\n          this.id = \"\";\n          this.title = \"\";\n        } else {\n          uni.showToast({\n            title: \"Operation failed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        uni.showToast({\n          title: \"Operation failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} table id with specified value\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", \"<data id>\");\nif (!error) {\n  console.log(\"Delete successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>DataID：</text>\n      <input v-model=\"dataId\" placeholder=\"Please entershouldDeleteDataID\" />\n    </view>\n    <button :disabled=\"!dataId\" @click=\"deleteData\">Delete Data</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataId: \"\"\n    };\n  },\n  methods: {\n    // Delete Data\n    async deleteData() {\n      try {\n        const { data, error } = await cloudbase\n          .database()\n          .from(\"{%TABLE_NAME%}\")\n          .delete()\n          .eq(\"id\", this.dataId);\n\n        if (!error) {\n          uni.showToast({\n            title: \"Delete successful\",\n            icon: \"success\"\n          });\n          this.dataId = \"\";\n        } else {\n          uni.showToast({\n            title: \"Delete failed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        uni.showToast({\n          title: \"Delete failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table first 10 records\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\nconsole.log(res.data);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"getData\">Query Data</button>\n    <view v-if=\"dataList.length > 0\">\n      <view v-for=\"(item, index) in dataList\" :key=\"index\" class=\"data-item\">\n        <text>{{ JSON.stringify(item) }}</text>\n      </view>\n    </view>\n    <text v-else>temporarilyNoneData</text>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataList: []\n    };\n  },\n  methods: {\n    // Query Data\n    async getData() {\n      try {\n        const db = cloudbase.database();\n        const res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n\n        this.dataList = res.data;\n        uni.showToast({\n          title: \"Querysuccessful\",\n          icon: \"success\"\n        });\n      } catch (error) {\n        uni.showToast({\n          title: \"Queryfailed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} table data\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({ title: \"Example Title\" });\nconsole.log(`Insert successful! id: ${res.id}`);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Title：</text>\n      <input v-model=\"title\" placeholder=\"Please enterTitle\" />\n    </view>\n    <button :disabled=\"!title\" @click=\"addData\">Insert Data</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      title: \"\"\n    };\n  },\n  methods: {\n    // Insert Data\n    async addData() {\n      try {\n        const db = cloudbase.database();\n        const res = await db\n          .collection(\"{%TABLE_NAME%}\")\n          .add({ title: this.title });\n\n        uni.showToast({\n          title: `Insert successful! id: ${res.id}`,\n          icon: \"success\"\n        });\n        this.title = \"\";\n      } catch (error) {\n        uni.showToast({\n          title: \"Insert failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} table id with specified value\nconst db = cloudbase.database();\nawait db\n  .collection(\"{%TABLE_NAME%}\")\n  .doc(\"<data id>\")\n  .update({ title: \"New Title\" });\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>DataID：</text>\n      <input v-model=\"dataId\" placeholder=\"Please enterDataID\" />\n    </view>\n    <view>\n      <text>New Title：</text>\n      <input v-model=\"newTitle\" placeholder=\"Please enterNew Title\" />\n    </view>\n    <button :disabled=\"!dataId || !newTitle\" @click=\"updateData\">\n      Update Data\n    </button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataId: \"\",\n      newTitle: \"\"\n    };\n  },\n  methods: {\n    // Update Data\n    async updateData() {\n      try {\n        const db = cloudbase.database();\n        await db\n          .collection(\"{%TABLE_NAME%}\")\n          .doc(this.dataId)\n          .update({ title: this.newTitle });\n\n        uni.showToast({\n          title: \"Update successful\",\n          icon: \"success\"\n        });\n        this.dataId = \"\";\n        this.newTitle = \"\";\n      } catch (error) {\n        uni.showToast({\n          title: \"Update failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} table id with specified value\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").remove();\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>DataID：</text>\n      <input v-model=\"dataId\" placeholder=\"Please entershouldDeleteDataID\" />\n    </view>\n    <button :disabled=\"!dataId\" @click=\"deleteData\">Delete Data</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataId: \"\"\n    };\n  },\n  methods: {\n    // Delete Data\n    async deleteData() {\n      try {\n        const db = cloudbase.database();\n        await db.collection(\"{%TABLE_NAME%}\").doc(this.dataId).remove();\n\n        uni.showToast({\n          title: \"Delete successful\",\n          icon: \"success\"\n        });\n        this.dataId = \"\";\n      } catch (error) {\n        uni.showToast({\n          title: \"Delete failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} Data Modelbefore10recordsData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\nconsole.log(res.data?.records);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"getData\">Query Data</button>\n    <view v-if=\"dataList.length > 0\">\n      <view v-for=\"(item, index) in dataList\" :key=\"index\" class=\"data-item\">\n        <text>{{ JSON.stringify(item) }}</text>\n      </view>\n    </view>\n    <text v-else>temporarilyNoneData</text>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataList: []\n    };\n  },\n  methods: {\n    // Query Data\n    async getData() {\n      try {\n        const res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n          pageNumber: 1,\n          pagesize: 10\n        });\n\n        this.dataList = res.data?.records || [];\n        uni.showToast({\n          title: \"Querysuccessful\",\n          icon: \"success\"\n        });\n      } catch (error) {\n        uni.showToast({\n          title: \"Queryfailed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} Data ModelData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: { title: \"Example Title\" }\n});\nconsole.log(`Insert successful! id: ${res.data.id}`);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Title：</text>\n      <input v-model=\"title\" placeholder=\"Please enterTitle\" />\n    </view>\n    <button :disabled=\"!title\" @click=\"addData\">Insert Data</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      title: \"\"\n    };\n  },\n  methods: {\n    // Insert Data\n    async addData() {\n      try {\n        const res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n          data: { title: this.title }\n        });\n\n        uni.showToast({\n          title: `Insert successful! id: ${res.data.id}`,\n          icon: \"success\"\n        });\n        this.title = \"\";\n      } catch (error) {\n        uni.showToast({\n          title: \"Insert failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} Data Model _id with specified value\nawait cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: { title: \"New Title\" },\n  filter: { where: { _id: { $eq: \"<data id>\" } } }\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>DataID：</text>\n      <input v-model=\"dataId\" placeholder=\"Please enterDataID\" />\n    </view>\n    <view>\n      <text>New Title：</text>\n      <input v-model=\"newTitle\" placeholder=\"Please enterNew Title\" />\n    </view>\n    <button :disabled=\"!dataId || !newTitle\" @click=\"updateData\">\n      Update Data\n    </button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataId: \"\",\n      newTitle: \"\"\n    };\n  },\n  methods: {\n    // Update Data\n    async updateData() {\n      try {\n        await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n          data: { title: this.newTitle },\n          filter: { where: { _id: { $eq: this.dataId } } }\n        });\n\n        uni.showToast({\n          title: \"Update successful\",\n          icon: \"success\"\n        });\n        this.dataId = \"\";\n        this.newTitle = \"\";\n      } catch (error) {\n        uni.showToast({\n          title: \"Update failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} Data Model _id with specified value\nawait cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: { where: { _id: { $eq: \"<data id>\" } } }\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>DataID：</text>\n      <input v-model=\"dataId\" placeholder=\"Please entershouldDeleteDataID\" />\n    </view>\n    <button :disabled=\"!dataId\" @click=\"deleteData\">Delete Data</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataId: \"\"\n    };\n  },\n  methods: {\n    // Delete Data\n    async deleteData() {\n      try {\n        await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n          filter: { where: { _id: { $eq: this.dataId } } }\n        });\n\n        uni.showToast({\n          title: \"Delete successful\",\n          icon: \"success\"\n        });\n        this.dataId = \"\";\n      } catch (error) {\n        uni.showToast({\n          title: \"Delete failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Call {%FUNCTION_NAME%} Cloud Function\nconst res = await cloudbase.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {}\n});\nconsole.log(res.result);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"callFunction\">CallCloud Function</button>\n    <view v-if=\"result\">\n      <text>Return result：</text>\n      <text>{{ JSON.stringify(result) }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      result: null\n    };\n  },\n  methods: {\n    // CallCloud Function\n    async callFunction() {\n      try {\n        const res = await cloudbase.callFunction({\n          name: \"{%FUNCTION_NAME%}\",\n          data: {}\n        });\n\n        this.result = res.result;\n        uni.showToast({\n          title: \"Callsuccessful\",\n          icon: \"success\"\n        });\n      } catch (error) {\n        uni.showToast({\n          title: \"Call failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function",
            "content": []
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call {%SERVICE_NAME%} Cloud Runservice\nconst res = await cloudbase.callContainer({\n  name: \"{%SERVICE_NAME%}\"\n  method: 'POST',\n  path: '/',\n  header:{\n    'Content-Type': 'application/json; charset=utf-8'\n  },\n  data: {},\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"callRun\">CallCloud Run</button>\n    <view v-if=\"result\">\n      <text>Return result：</text>\n      <text>{{ JSON.stringify(result) }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      result: null\n    };\n  },\n  methods: {\n    // CallCloud Run\n    async callRun() {\n      try {\n        // Call {%SERVICE_NAME%} Cloud Runservice\n        const res = await cloudbase.callContainer({\n          name: \"{%SERVICE_NAME%}\"\n          method: 'POST',\n          path: '/',\n          header:{\n            'Content-Type': 'application/json; charset=utf-8'\n          },\n          data: {},\n        });\n\n        this.result = res;\n        uni.showToast({\n          title: \"Callsuccessful\",\n          icon: \"success\"\n        });\n      } catch (error) {\n        uni.showToast({\n          title: \"Call failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run",
            "content": []
          },
          {
            "index": 6,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.uploadFile({\n  cloudPath: `images/${Date.now()}-${file.name}`, // Path to upload in cloud\n  filePath: file\n});\nconsole.log(res.fileID);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"uploadFile\">SelectandUploadImage</button>\n    <view v-if=\"fileId\">\n      <text>Upload successful！</text>\n      <text>fileID: {{ fileId }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      fileId: \"\"\n    };\n  },\n  methods: {\n    // Upload File\n    async uploadFile() {\n      uni.chooseImage({\n        count: 1,\n        success: async chooseImageRes => {\n          try {\n            uni.showLoading({\n              title: \"Upload...\"\n            });\n\n            const tempFilePath = chooseImageRes.tempFilePaths[0];\n            const cloudPath = `images/${Date.now()}-${Math.random()}.png`;\n\n            const res = await cloudbase.uploadFile({\n              cloudPath: cloudPath,\n              filePath: tempFilePath\n            });\n\n            this.fileId = res.fileID;\n            uni.hideLoading();\n            uni.showToast({\n              title: \"Upload successful\",\n              icon: \"success\"\n            });\n          } catch (error) {\n            uni.hideLoading();\n            uni.showToast({\n              title: \"Uploadfailed：\" + error.message,\n              icon: \"none\"\n            });\n          }\n        }\n      });\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "title": "Upload File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.getTempFileURL({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\nconsole.log(res.fileList[0].tempFileURL);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>fileID：</text>\n      <input v-model=\"fileId\" placeholder=\"Please enterfileID (cloud://xxx.png)\" />\n    </view>\n    <button :disabled=\"!fileId\" @click=\"getFileUrl\">Get File URL</button>\n    <view v-if=\"fileUrl\">\n      <text>fileURL：</text>\n      <text>{{ fileUrl }}</text>\n      <image :src=\"fileUrl\" mode=\"aspectFit\"></image>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      fileId: \"\",\n      fileUrl: \"\"\n    };\n  },\n  methods: {\n    // Get File URL\n    async getFileUrl() {\n      try {\n        const res = await cloudbase.getTempFileURL({\n          fileList: [this.fileId]\n        });\n\n        this.fileUrl = res.fileList[0].tempFileURL;\n        uni.showToast({\n          title: \"Getsuccessful\",\n          icon: \"success\"\n        });\n      } catch (error) {\n        uni.showToast({\n          title: \"Getfailed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Get File URL"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nawait cloudbase.downloadFile({\n  fileID: \"cloud://xxx.png\" // File fileID\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>fileID：</text>\n      <input v-model=\"fileId\" placeholder=\"Please enterfileID (cloud://xxx.png)\" />\n    </view>\n    <button :disabled=\"!fileId\" @click=\"downloadFile\">Download File</button>\n    <view v-if=\"localPath\">\n      <text>Downloadsuccessful！</text>\n      <text>localPath: {{ localPath }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      fileId: \"\",\n      localPath: \"\"\n    };\n  },\n  methods: {\n    // Download File\n    async downloadFile() {\n      try {\n        uni.showLoading({\n          title: \"Download...\"\n        });\n\n        const res = await cloudbase.downloadFile({\n          fileID: this.fileId\n        });\n\n        this.localPath = res.tempFilePath;\n        uni.hideLoading();\n        uni.showToast({\n          title: \"Downloadsuccessful\",\n          icon: \"success\"\n        });\n      } catch (error) {\n        uni.hideLoading();\n        uni.showToast({\n          title: \"Downloadfailed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Download File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.deleteFile({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\nif (res.fileList[0].code === \"SUCCESS\") {\n  console.log(\"Delete successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>fileID：</text>\n      <input v-model=\"fileId\" placeholder=\"Please enterfileID (cloud://xxx.png)\" />\n    </view>\n    <button :disabled=\"!fileId\" @click=\"deleteFile\">Delete File</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      fileId: \"\"\n    };\n  },\n  methods: {\n    // Delete File\n    async deleteFile() {\n      try {\n        const res = await cloudbase.deleteFile({\n          fileList: [this.fileId]\n        });\n\n        if (res.fileList[0].code === \"SUCCESS\") {\n          uni.showToast({\n            title: \"Delete successful\",\n            icon: \"success\"\n          });\n          this.fileId = \"\";\n        } else {\n          uni.showToast({\n            title: \"Delete failed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        uni.showToast({\n          title: \"Delete failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Delete File"
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase\n  .ai()\n  .createModel(\"{%AI_MODEL_NAME%}\")\n  .streamText({\n    model: \"{%AI_SUB_MODEL_NAME%}\",\n    messages: [{ role: \"user\", content: \"Hello\" }]\n  });\n\nfor await (let data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data?.choices?.[0]?.delta?.reasoning_content;\n  if (think) console.log(think);\n\n  // Print generated text content\n  const text = data?.choices?.[0]?.delta?.content;\n  if (text) console.log(text);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Inputtopic：</text>\n      <input v-model=\"input\" placeholder=\"Please entertopic，such as：Spring\" />\n    </view>\n    <button :disabled=\"!input || isGenerating\" @click=\"callAIModel\">\n      GenerateContent\n    </button>\n    <view v-if=\"response\">\n      <text>GenerateResult：</text>\n      <text>{{ response }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      input: \"\",\n      response: \"\",\n      isGenerating: false\n    };\n  },\n  methods: {\n    // CallAI Model\n    async callAIModel() {\n      this.isGenerating = true;\n      this.response = \"\";\n\n      try {\n        // EnsurealreadyLogin\n        const loginState = await cloudbase.auth().getLoginState();\n        if (!loginState) {\n          await cloudbase.auth().signInAnonymously();\n        }\n\n        uni.showLoading({\n          title: \"Generating...\"\n        });\n\n        const res = await cloudbase\n          .ai()\n          .createModel(\"<YOUR_AI_MODEL_NAME>\")\n          .streamText({\n            model: \"<YOUR_AI_SUB_MODEL_NAME>\",\n            messages: [{ role: \"user\", content: this.input }]\n          });\n\n        for await (let str of res.textStream) {\n          this.response += str;\n        }\n\n        uni.hideLoading();\n        uni.showToast({\n          title: \"GenerateDone\",\n          icon: \"success\"\n        });\n      } catch (err) {\n        uni.hideLoading();\n        uni.showToast({\n          title: \"Generation failed：\" + err.message,\n          icon: \"none\"\n        });\n      } finally {\n        this.isGenerating = false;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation"
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call image generation cloud function\nconst res = await cloudbase.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: {\n    prompt: \"A cute cat playing in the sunshine\"\n  }\n});\n\nconst result = res.result;\n\nif (result.success) {\n  // Generation successful\n  console.log(\"Generation successful!\");\n  console.log(\"Image URL:\", result.imageUrl);\n  console.log(\"Optimized prompt:\", result.revised_prompt);\n\n  // Use image\n  // Note: Image URL is valid for 24 hours, please save or transfer promptly\n} else {\n  // Generation failed\n  console.error(\"Generation failed:\", result.code, result.message);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>ImageDescription：</text>\n      <input v-model=\"prompt\" placeholder=\"Enter image description\" />\n    </view>\n    <button :disabled=\"!prompt || loading\" @click=\"generateImage\">\n      {{ loading ? \"Generating...\" : \"Generate Image\" }}\n    </button>\n    <view v-if=\"message\">\n      <text :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\">\n        {{ message }}\n      </text>\n    </view>\n    <view v-if=\"imageUrl\">\n      <image :src=\"imageUrl\" mode=\"aspectFit\" style=\"width: 100%\"></image>\n      <text style=\"font-size: 12px; color: #666\">\n        Note: Image URL is valid for 24 hours, please save promptly\n      </text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      prompt: \"\",\n      imageUrl: \"\",\n      message: \"\",\n      loading: false\n    };\n  },\n  methods: {\n    // Generate Image\n    async generateImage() {\n      this.loading = true;\n      this.message = \"\";\n      this.imageUrl = \"\";\n\n      try {\n        uni.showLoading({\n          title: \"Generating...\"\n        });\n\n        // Call image generation cloud function\n        const res = await cloudbase.callFunction({\n          name: \"<YOUR_FUNCTION_NAME>\",\n          data: {\n            prompt: this.prompt\n          }\n        });\n\n        const result = res.result;\n\n        if (result.success) {\n          this.imageUrl = result.imageUrl;\n          this.message = \"Generation successful！\";\n          uni.hideLoading();\n          uni.showToast({\n            title: \"Generation successful\",\n            icon: \"success\"\n          });\n        } else {\n          this.message = `Generation failed：${result.message}`;\n          uni.hideLoading();\n          uni.showToast({\n            title: \"Generation failed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        this.message = \"Call failed：\" + error.message;\n        uni.hideLoading();\n        uni.showToast({\n          title: \"Call failed\",\n          icon: \"none\"\n        });\n      } finally {\n        this.loading = false;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation"
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from './utils/cloudbase';\n\nconst res = await cloudbase.ai().bot.sendMessage({\n  botId: '{%AGENT_ID%}',\n  // Refer to frontend-backend communication protocol for input structure：\n  //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n  threadId: '550e8400-e29b-41d4-a716-446655440000',\n  runId: 'run_001',\n  messages: [\n    {\n      id: 'msg_001',\n      role: 'user',\n      content: 'Hello',\n    },\n  ],\n  tools: [],\n  context: [],\n  state: {},\n  forwardedProps: {},\n});\n\nfor await (const data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data.reasoning_content;\n  if (think) console.log(think);\n\n  // Print output content\n  const content = data.content;\n  if (content) console.log(content);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Inputquestion：</text>\n      <input v-model=\"input\" placeholder=\"Please enterquestion，such as：Who are you\" />\n    </view>\n    <button :disabled=\"!input || isGenerating\" @click=\"callAgent\">\n      SendMessage\n    </button>\n    <view v-if=\"response\">\n      <text>answer：</text>\n      <text>{{ response }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      input: \"\",\n      response: \"\",\n      isGenerating: false\n    };\n  },\n  methods: {\n    // CallAgent\n    async callAgent() {\n      this.isGenerating = true;\n      this.response = \"\";\n\n      try {\n        // EnsurealreadyLogin\n        const loginState = await cloudbase.auth().getLoginState();\n        if (!loginState) {\n          await cloudbase.auth().signInAnonymously();\n        }\n\n        uni.showLoading({\n          title: \"Generating...\"\n        });\n\n        const res = await cloudbase.ai().bot.sendMessage({\n          botId: \"{%AGENT_ID%}\",\n          // Refer to frontend-backend communication protocol for input structure：\n          //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n          threadId: '550e8400-e29b-41d4-a716-446655440000',\n          runId: 'run_001',\n          messages: [\n            {\n              id: 'msg_001',\n              role: 'user',\n              content: 'Hello',\n            },\n          ],\n          tools: [],\n          context: [],\n          state: {},\n          forwardedProps: {},\n        });\n\n        for await (const data of res.dataStream) {\n          // Print reasoning content if available\n          const think = data.reasoning_content;\n          if (think) this.response += think;\n\n          // Print output content\n          const content = data.content;\n          if (content) this.response += content;\n        }\n\n        uni.hideLoading();\n        uni.showToast({\n          title: \"GenerateDone\",\n          icon: \"success\"\n        });\n      } catch (err) {\n        uni.hideLoading();\n        uni.showToast({\n          title: \"Generation failed：\" + err.message,\n          icon: \"none\"\n        });\n      } finally {\n        this.isGenerating = false;\n      }\n    }\n  }\n};\n</script>\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.ai().bot.sendMessage({\n  botId: \"{%AGENT_ID%}\",\n  msg: \"Hello\"\n});\n\nfor await (const data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data.reasoning_content;\n  if (think) console.log(think);\n\n  // Print output content\n  const content = data.content;\n  if (content) console.log(content);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Inputquestion：</text>\n      <input v-model=\"input\" placeholder=\"Please enterquestion，such as：Who are you\" />\n    </view>\n    <button :disabled=\"!input || isGenerating\" @click=\"callAgent\">\n      SendMessage\n    </button>\n    <view v-if=\"response\">\n      <text>answer：</text>\n      <text>{{ response }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      input: \"\",\n      response: \"\",\n      isGenerating: false\n    };\n  },\n  methods: {\n    // CallAgent\n    async callAgent() {\n      this.isGenerating = true;\n      this.response = \"\";\n\n      try {\n        // EnsurealreadyLogin\n        const loginState = await cloudbase.auth().getLoginState();\n        if (!loginState) {\n          await cloudbase.auth().signInAnonymously();\n        }\n\n        uni.showLoading({\n          title: \"Generating...\"\n        });\n\n        const res = await cloudbase.ai().bot.sendMessage({\n          botId: \"{%AGENT_ID%}\",\n          msg: \"Hello\"\n        });\n\n        for await (const data of res.dataStream) {\n          // Print reasoning content if available\n          const think = data.reasoning_content;\n          if (think) this.response += think;\n\n          // Print output content\n          const content = data.content;\n          if (content) this.response += content;\n        }\n\n        uni.hideLoading();\n        uni.showToast({\n          title: \"GenerateDone\",\n          icon: \"success\"\n        });\n      } catch (err) {\n        uni.hideLoading();\n        uni.showToast({\n          title: \"Generation failed：\" + err.message,\n          icon: \"none\"\n        });\n      } finally {\n        this.isGenerating = false;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 9,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "Use **SMS Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMSVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: phone });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  phone_number: `+86 ${phone}`,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${phone.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Phone number：</text>\n      <input v-model=\"phone\" placeholder=\"13800000000\" />\n    </view>\n    <view>\n      <text>Verification code：</text>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button :disabled=\"!phone\" @click=\"sendCode\">Send Code</button>\n    </view>\n    <button :disabled=\"!verificationId || !code\" @click=\"register\">Register</button>\n    <text\n      v-if=\"message\"\n      :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\"\n      >{{ message }}</text\n    >\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      phone: \"\",\n      code: \"\",\n      verificationId: \"\",\n      message: \"\"\n    };\n  },\n  methods: {\n    // Send Code\n    async sendCode() {\n      try {\n        const auth = cloudbase.auth();\n        const res = await auth.getVerification({ phone_number: this.phone });\n        this.verificationId = res.verification_id;\n        this.message = \"Verification code sent！\";\n      } catch (error) {\n        this.message = \"Send failed：\" + error.message;\n      }\n    },\n\n    // Register\n    async register() {\n      try {\n        const auth = cloudbase.auth();\n        // Verify the code\n        const verifyRes = await auth.verify({\n          verification_id: this.verificationId,\n          verification_code: this.code\n        });\n        // Register (auto-login if user exists)\n        await auth.signUp({\n          phone_number: `+86 ${this.phone}`,\n          verification_code: this.code,\n          verification_token: verifyRes.verification_token,\n          name: `user_${this.phone.slice(-4)}`,\n          password: \"admin@123\"\n        });\n        this.message = \"Registration successful！\";\n      } catch (error) {\n        this.message = \"Registration failed：\" + error.message;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "title": "SMS Code Registration"
              },
              {
                "markdown": "Use **Email Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  email,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${email.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Email：</text>\n      <input v-model=\"email\" placeholder=\"example@email.com\" />\n    </view>\n    <view>\n      <text>Verification code：</text>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button :disabled=\"!email\" @click=\"sendCode\">Send Code</button>\n    </view>\n    <button :disabled=\"!verificationId || !code\" @click=\"register\">Register</button>\n    <text\n      v-if=\"message\"\n      :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\"\n      >{{ message }}</text\n    >\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      email: \"\",\n      code: \"\",\n      verificationId: \"\",\n      message: \"\"\n    };\n  },\n  methods: {\n    // Send Code\n    async sendCode() {\n      try {\n        const auth = cloudbase.auth();\n        const res = await auth.getVerification({ email: this.email });\n        this.verificationId = res.verification_id;\n        this.message = \"Verification code sent！\";\n      } catch (error) {\n        this.message = \"Send failed：\" + error.message;\n      }\n    },\n\n    // Register\n    async register() {\n      try {\n        const auth = cloudbase.auth();\n        // Verify the code\n        const verifyRes = await auth.verify({\n          verification_id: this.verificationId,\n          verification_code: this.code\n        });\n        // Register (auto-login if user exists)\n        await auth.signUp({\n          email: this.email,\n          verification_code: this.code,\n          verification_token: verifyRes.verification_token,\n          name: `user_${this.email.slice(-4)}`,\n          password: \"admin@123\"\n        });\n        this.message = \"Registration successful！\";\n      } catch (error) {\n        this.message = \"Registration failed：\" + error.message;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Email Code Registration"
              },
              {
                "markdown": "Use **Username Password Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **UsernamePasswordLogin**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\nawait auth.signIn({\n  username, // Can be username, phone or email\n  password\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Account：</text>\n      <input v-model=\"username\" placeholder=\"Username/Phone/Email\" />\n      <text>Note: Add country code for phone login +86</text>\n    </view>\n    <view>\n      <text>Password：</text>\n      <input type=\"password\" v-model=\"password\" placeholder=\"Enter password\" />\n    </view>\n    <button :disabled=\"!username || !password\" @click=\"login\">Login</button>\n    <text\n      v-if=\"message\"\n      :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\"\n      >{{ message }}</text\n    >\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      username: \"\",\n      password: \"\",\n      message: \"\"\n    };\n  },\n  methods: {\n    // Login\n    async login() {\n      try {\n        const auth = cloudbase.auth();\n        await auth.signIn({\n          username: this.username, // Can be username, phone or email\n          password: this.password\n        });\n        this.message = \"Login successful！\";\n      } catch (error) {\n        this.message = \"Login failed：\" + error.message;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login"
              },
              {
                "markdown": "Use **SMS Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMS Verification Login**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n\n// Login\nawait auth.signInWithSms({\n  verificationInfo: res,\n  verificationCode: code,\n  phoneNum: `+86 ${phone}`\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Phone number：</text>\n      <input v-model=\"phone\" placeholder=\"13800000000\" />\n    </view>\n    <view>\n      <text>Verification code：</text>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button @click=\"sendCode\" :disabled=\"!phone\">Send Code</button>\n    </view>\n    <button @click=\"login\" :disabled=\"!verificationInfo || !code\">Login</button>\n    <text\n      v-if=\"message\"\n      :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\"\n      >{{ message }}</text\n    >\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      phone: \"\",\n      code: \"\",\n      verificationInfo: null,\n      message: \"\"\n    };\n  },\n  methods: {\n    // Send Code\n    async sendCode() {\n      try {\n        const auth = cloudbase.auth();\n        const res = await auth.getVerification({\n          phone_number: `+86 ${this.phone}`\n        });\n        this.verificationInfo = res;\n        this.message = \"Verification code sent！\";\n      } catch (error) {\n        this.message = \"Send failed：\" + error.message;\n      }\n    },\n\n    // Login\n    async login() {\n      try {\n        const auth = cloudbase.auth();\n        await auth.signInWithSms({\n          verificationInfo: this.verificationInfo,\n          verificationCode: this.code,\n          phoneNum: `+86 ${this.phone}`\n        });\n        this.message = \"Login successful！\";\n      } catch (error) {\n        this.message = \"Login failed：\" + error.message;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login"
              },
              {
                "markdown": "Use **Email Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Login\nawait auth.signInWithEmail({\n  verificationInfo: res,\n  verificationCode: code,\n  email\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Email：</text>\n      <input v-model=\"email\" placeholder=\"example@email.com\" />\n    </view>\n    <view>\n      <text>Verification code：</text>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button @click=\"sendCode\" :disabled=\"!email\">Send Code</button>\n    </view>\n    <button @click=\"login\" :disabled=\"!verificationInfo || !code\">Login</button>\n    <text\n      v-if=\"message\"\n      :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\"\n      >{{ message }}</text\n    >\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      email: \"\",\n      code: \"\",\n      verificationInfo: null,\n      message: \"\"\n    };\n  },\n  methods: {\n    // Send Code\n    async sendCode() {\n      try {\n        const auth = cloudbase.auth();\n        const res = await auth.getVerification({ email: this.email });\n        this.verificationInfo = res;\n        this.message = \"Verification code sent！\";\n      } catch (error) {\n        this.message = \"Send failed：\" + error.message;\n      }\n    },\n\n    // Login\n    async login() {\n      try {\n        const auth = cloudbase.auth();\n        await auth.signInWithEmail({\n          verificationInfo: this.verificationInfo,\n          verificationCode: this.code,\n          email: this.email\n        });\n        this.message = \"Login successful！\";\n      } catch (error) {\n        this.message = \"Login failed：\" + error.message;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Phone numberAuthorizeLogin\nconst loginResult = await auth.signInWithPhoneAuth(code);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button open-type=\"getPhoneNumber\" @getphonenumber=\"handleGetPhoneNumber\">\n      WeChatMini ProgramLogin\n    </button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from './utils/cloudbase';\n\nexport default {\n  data() {\n    return {}\n  },\n  methods: {\n    async handleGetPhoneNumber(event) {\n      if(!event.detail.code) {\n        console.error('GetPhone numberfailed:', event.detail.errMsg);\n        uni.showToast({\n          title: 'GetPhone numberfailed',\n          icon: 'none'\n        });\n        return\n      }\n      console.log('Gettodynamic token(code):', event.detail.code);\n      uni.showLoading({\n        title: 'Login...'\n      });\n      try {\n        // Phone numberAuthorizeLogin\n        const auth = cloudbase.auth();\n        const loginResult = await auth.signInWithPhoneAuth( event.detail.code );\n        console.log('Phone numberAuthorizeLoginResult:', loginResult);\n        uni.hideLoading();\n        uni.showToast({\n          title: 'Login successful',\n          icon: 'success'\n        });\n      } catch (error: any) {\n        // ProcessLogin failed\n        console.error('Phone numberAuthorizeLogin failed:', error);\n        uni.showToast({\n          title: error.message || 'Login failed',\n          icon: 'none'\n        });\n      } finally {\n        uni.hideLoading();\n      }\n    }\n  }\n}\n</script>\n```",
                "index": 6,
                "title": "Mini ProgramPhone numberLogin"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// WeChat OpenID Login\nconst loginResult = await auth.signInWithOpenId();\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"openIdLogin\">WeChatMini ProgramLogin</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from './utils/cloudbase';\n\nexport default {\n  data() {\n    return {}\n  },\n  methods: {\n    async openIdLogin() {\n      uni.showLoading({\n        title: 'currentlyinLogin...'\n      });\n\n      try {\n        const auth = cloudbase.auth();\n        const loginResult = await auth.signInWithOpenId();\n        console.log('WeChat OpenID Login successful:', loginResult);\n        uni.hideLoading();\n\n        uni.showToast({\n          title: 'Login successful',\n          icon: 'success'\n        });\n      } catch (error: any) {\n        uni.hideLoading();\n        console.error('WeChat OpenID Login failed:', error);\n        uni.showToast({\n          title: error.message || 'Login failed，pleaseRetry',\n          icon: 'none'\n        });\n      }\n    }\n  }\n}\n</script>\n```",
                "index": 7,
                "title": "WeChat OpenID Login"
              }
            ]
          }
        ]
      }
    ],
    "_id": "0b175e3169a92871004393494f1c0085",
    "_openid": "anon",
    "createdAt": 1769767045876,
    "updatedAt": 1769767045876
  },
  {
    "category": "Framework Integration,ORMs,Drizzle",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 42,
    "hasTemplate": false,
    "docsUrl": "https://orm.drizzle.team/docs/get-started-mysql",
    "content": [
      {
        "markdown": "Use `Drizzle` operate **MySQL Database**\n```bash\nnpm install drizzle-orm mysql2\n```",
        "title": "Install Dependencies",
        "type": "",
        "content": []
      },
      {
        "markdown": "Add the following code to your **Drizzle** project",
        "title": "Usage Example",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nimport { drizzle } from \"drizzle-orm/mysql2\";\nimport mysql from \"mysql2/promise\";\nimport { todos } from \"./schema.js\";\n\nasync function main() {\n  const connection = await mysql.createConnection(process.env.DATABASE_URL);\n  const db = drizzle(connection);\n\n  const allTodos = await db.select().from(todos);\n  console.log(allTodos);\n\n  await connection.end();\n}\n\nmain().catch(console.error);\n```",
            "title": "index.js"
          },
          {
            "markdown": "```js\nimport { mysqlTable, text } from \"drizzle-orm/mysql-core\";\n\nexport const todos = mysqlTable(\"todos\", {\n  id: text(\"_id\").primaryKey(),\n  title: text(\"title\"),\n});\n```",
            "id": "",
            "title": "schema.js"
          },
          {
            "markdown": "```\nDATABASE_URL=mysql://{%DATABASE_URL%}\n```",
            "id": "mysqlString",
            "title": ".env"
          }
        ]
      }
    ],
    "_id": "14b1f540697c28d3003ad4ab0a073e5b",
    "_openid": "anon",
    "createdAt": 1769744595879,
    "updatedAt": 1769766693678
  },
  {
    "category": "Framework Integration,MiniProgram / MiniGame,MiniProgram",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": -1,
    "hasTemplate": false,
    "docsUrl": "https://developers.weixin.qq.com/miniprogram/dev/wxcloudservice/wxcloud/guide/init.html",
    "content": [
      {
        "markdown": "in `app.js` InitializeCloudBase：",
        "index": 1,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "mostCloudBasecapabilities canUse `Mini ProgramNative API` directlyCall，NoneneedInstall SDK，If `NativeAPI` Not supported pleaseUse `Client SDK` performCall\n\n```js\nApp({\n  onLaunch() {\n    wx.cloud.init({\n      env: \"{%ENV_ID%}\"\n    });\n  }\n});\n```",
            "index": 1,
            "title": "NativeAPI Initialize",
            "content": []
          },
          {
            "markdown": "**Install**\n\nUse Client SDK before please firstInstall SDK\n\ninMini Program `package.json` theinDirectory（usually `miniprogram` Directory）execute：\n\n```bash\nnpm i @cloudbase/wx-cloud-client-sdk --save\n```\n\nInstallDoneafter，inWeChatClick in developer tools **tool → Build npm**。\n\n**Initialize**\n\n```js\nconst { init } = require(\"@cloudbase/wx-cloud-client-sdk\");\n\nApp({\n  onLaunch() {\n    wx.cloud.init({\n      env: \"{%ENV_ID%}\"\n    });\n    this.globalData.cloudbase = init(wx.cloud);\n  },\n  globalData: {}\n});\n```",
            "index": 2,
            "title": "Client SDK Initialize",
            "content": []
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 2,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Query {%TABLE_NAME%} table (limit 10 records)\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n\nconsole.log(\"Query result:\", data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Insert a record into {%TABLE_NAME%} table\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"New Post\", status: \"draft\" })\n  .select();\n\nconsole.log(\"Insert result:\", data);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Update record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ status: \"published\" })\n  .eq(\"id\", 1)\n  .select();\n\nconsole.log(\"Update result:\", data);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Upsert: update on conflict, otherwise insert\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Post Title\", status: \"published\" }, { onConflict: \"id\" })\n  .select();\n\nconsole.log(\"Upsert result:\", data);\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Delete record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", 1);\n\nconsole.log(\"Delete completed:\", error);\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "pleaseUse `Client SDK` performCall",
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Query {%TABLE_NAME%} table first 10 records\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n\nconsole.log(\"QueryResult:\", data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Add {%TABLE_NAME%} table data\nconst { data, error } = await cloudbase.rdb().from(\"{%TABLE_NAME%}\").insert({\n  title: \"Example Title\"\n});\n\nconsole.log(\"AddResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Update {%TABLE_NAME%} table id as <DataID> Data\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({\n    title: \"UpdateafterTitle\"\n  })\n  .eq(\"id\", \"<DataID>\");\n\nconsole.log(\"UpdateResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Example Title\" });\n\nconsole.log(\"AddUpdateResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Delete {%TABLE_NAME%} table id as <DataID> Data\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", \"<DataID>\");\n\nconsole.log(\"DeleteResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Query {%TABLE_NAME%} table first 10 records\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n\nconsole.log(res.data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Add {%TABLE_NAME%} table data\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({\n  data: {\n    title: \"Example Title\",\n    content: \"ExampleContent\"\n  }\n});\n\nconsole.log(res);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Update {%TABLE_NAME%} table id as <DataID> Data\nconst res = await db\n  .collection(\"{%TABLE_NAME%}\")\n  .doc(\"<DataID>\")\n  .update({\n    data: {\n      title: \"UpdateafterTitle\"\n    }\n  });\n\nconsole.log(res.stats.updated);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Delete {%TABLE_NAME%} table id as <DataID> Data\nconst res = await db.collection(\"{%TABLE_NAME%}\").doc(\"<DataID>\").remove();\n\nconsole.log(res.stats.removed);\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "pleaseUse `Client SDK` performCall",
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Query {%TABLE_NAME%} Data Modelbefore10recordsData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\n\nconsole.log(res.data.records);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Add {%TABLE_NAME%} Data ModelData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: {\n    title: \"Example Title\",\n    content: \"ExampleContent\"\n  }\n});\n\nconsole.log(res.data);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Update {%TABLE_NAME%} Data Model _id as <DataID> Data\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: {\n    title: \"UpdateafterTitle\"\n  },\n  filter: {\n    where: {\n      _id: {\n        $eq: \"<DataID>\"\n      }\n    }\n  }\n});\n\nconsole.log(res.data);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Delete {%TABLE_NAME%} Data Model _id as <DataID> Data\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: {\n    where: {\n      _id: {\n        $eq: \"<DataID>\"\n      }\n    }\n  }\n});\n\nconsole.log(res.data);\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "```js\n// Call {%FUNCTION_NAME%} Cloud Function\nconst res = await wx.cloud.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {} // Cloud Functioninput parameters\n});\n\nconsole.log(res.result);\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function",
            "content": []
          },
          {
            "markdown": "```js\n// Call {%SERVICE_NAME%} Cloud Runservice\nconst res = await wx.cloud.callContainer({\n  config: {\n    env: \"{%ENV_ID%}\" // andMini ProgramalreadyAssociationCloudBaseEnvironment ID\n  },\n  path: \"/\", // businessCustomPath，rootDirectoryas /\n  method: \"GET\", // Choose according to business needs\n  header: {\n    \"X-WX-SERVICE\": \"{%SERVICE_NAME%}\" // Cloud RunserviceName\n    // other header\n  }\n  // dataType: 'text' // Defaultas JSON；if neededmanuallyParsecan be set to 'text'\n});\n\nconsole.log(res);\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run",
            "content": []
          },
          {
            "index": 1,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nwx.chooseMedia({\n  count: 1,\n  mediaType: [\"image\", \"video\"],\n  sourceType: [\"album\", \"camera\"],\n  success: async res => {\n    const res = await wx.cloud.uploadFile({\n      cloudPath: \"images/\" + Date.now() + \".png\", // Path to upload in cloud\n      filePath: res.tempFiles[0].tempFilePath // Mini ProgramtemporaryfilePath\n    });\n\n    console.log(res.fileID);\n  }\n});\n```",
                "index": 1,
                "title": "Upload File"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.getTempFileURL({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\n\nconsole.log(res.fileList);\n// fileListExample\n// [{\n//    fileID: \"cloud://xxx.png\", // file ID\n//    tempFileURL: \"https://xxx.png\", // temporaryfilenetworkURL\n//    maxAge: 120 * 60 * 1000, // Validperiod\n// }]\n```",
                "index": 2,
                "title": "Get File URL"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.downloadFile({\n  fileID: \"cloud://xxx.png\" // File fileID\n});\n\nconsole.log(res.tempFilePath); // ReturntemporaryfilePath\n```",
                "index": 3,
                "title": "Download File"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.deleteFile({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\n\nconsole.log(res.fileList);\n```",
                "index": 4,
                "title": "Delete File"
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst res = await wx.cloud.extend.AI.createModel(\n  \"{%AI_MODEL_NAME%}\"\n).streamText({\n  data: {\n    model: \"{%AI_SUB_MODEL_NAME%}\",\n    messages: [\n      {\n        role: \"user\",\n        content: \"Hello\"\n      }\n    ]\n  }\n});\n\nfor await (let event of res.eventStream) {\n  if (event.data === \"[DONE]\") {\n    break;\n  }\n  const data = JSON.parse(event.data);\n\n  // WhenUse deepseek-r1 when，model willGeneratereasoning chainContent\n  const think = data?.choices?.[0]?.delta?.reasoning_content;\n  if (think) {\n    console.log(think);\n  }\n\n  // Print generated text content\n  const text = data?.choices?.[0]?.delta?.content;\n  if (text) {\n    console.log(text);\n  }\n}\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation"
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```js\n// Call image generation cloud function\nwx.cloud.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: {\n    prompt: \"A cute cat playing in the sunshine\"\n  },\n  success: res => {\n    const result = res.result;\n\n    if (result.success) {\n      // Generation successful\n      console.log(\"Generation successful!\");\n      console.log(\"Image URL:\", result.imageUrl);\n      console.log(\"Optimized prompt:\", result.revised_prompt);\n\n      // Use image\n      // Note: Image URL is valid for 24 hours, please save or transfer promptly\n    } else {\n      // Generation failed\n      console.error(\"Generation failed:\", result.code, result.message);\n    }\n  },\n  fail: err => {\n    console.error(\"Call failed:\", err);\n  }\n});\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation"
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "\n```js\nfunction generateId() {\n  const timestamp = Date.now().toString().slice(-4);\n  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');\n  return timestamp + random;\n}\n\nasync function sendMessage(message) {\n  const res = await wx.cloud.extend.AI.bot.sendMessage({\n    data: {\n      // botId is required to identify the Agent\n      botId: '{%AGENT_ID%}',\n      // Refer to the HTTP Agent protocol for parameter structure:\n      // https://docs.cloudbase.net/ai/agent/http-agent-protocol\n      threadId: 'thread_id_' + generateId(),\n      runId: 'run_id_' + generateId(),\n      messages: [\n        { id: String(Date.now()), role: 'user', content: message }\n      ],\n      tools: [],\n      context: [],\n      state: {},\n      forwardedProps: {},\n    }\n  });\n\n  // Receive streaming response\n  let response = '';\n  for await (const event of res.eventStream) {\n    // Parse event.data manually\n    const data = JSON.parse(event.data);\n    // Output based on event type, see docs:\n    // https://docs.cloudbase.net/ai/agent/http-agent-protocol#response-events\n    switch (data.type) {\n      case 'TEXT_MESSAGE_CONTENT':\n        response += data.delta;\n        console.log(data.delta);  // Real-time output\n        break;\n\n      case 'RUN_ERROR':\n        console.error('Run error:', data.message);\n        break;\n\n      case 'RUN_FINISHED':\n        // Run finished\n        break;\n    }\n  }\n\n  return response;\n}\n\nsendMessage('Hello');\n```\n",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.extend.AI.bot.sendMessage({\n  data: {\n    botId: \"{%AGENT_ID%}\",\n    msg: \"Hello\"\n  }\n});\n\nfor await (const event of res.eventStream) {\n  if (event.data === \"[DONE]\") {\n    break;\n  }\n  const data = JSON.parse(event.data);\n\n  // WhenUse deepseek-r1 when，model willGeneratereasoning chainContent\n  const think = data.reasoning_content;\n  if (think) {\n    console.log(think);\n  }\n\n  // Print output content\n  const content = data.content;\n  if (content) {\n    console.log(content);\n  }\n}\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          }
        ]
      }
    ],
    "_id": "14b1f540697c80750044efae0f12d28d",
    "_openid": "anon",
    "createdAt": 1769767029468,
    "updatedAt": 1775130292997
  },
  {
    "category": "CloudBase MCP,Qwen Code",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 109,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/qwen-code",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.qwen/settings.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Qwen\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "18ffb4c969a92870004591b02535d0bc",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "Framework Integration,Web Frameworks,React(Vite)",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 3,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/api-reference/webv2/initialization",
    "content": [
      {
        "markdown": "`@cloudbase/js-sdk` allows you to use JavaScript on Web (such as PC web pages, WeChat H5, etc.) to access CloudBase services and resources.（）",
        "index": 1,
        "title": "Install SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```bash\nnpm i @cloudbase/js-sdk\n```",
            "index": 1,
            "title": "npm",
            "content": []
          },
          {
            "markdown": "```bash\nyarn add @cloudbase/js-sdk\n```",
            "index": 2,
            "title": "yarn",
            "content": []
          },
          {
            "markdown": "```bash\npnpm add @cloudbase/js-sdk\n```",
            "index": 3,
            "title": "pnpm",
            "content": []
          }
        ]
      },
      {
        "markdown": "Add the following code to your React project",
        "index": 2,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nimport cloudbaseSDK from \"@cloudbase/js-sdk\";\n\nexport const cloudbase = cloudbaseSDK.init({\n  env: import.meta.env.VITE_CLOUDBASE_ENV_ID,\n  region: import.meta.env.VITE_CLOUDBASE_REGION,\n  accessKey: import.meta.env.VITE_CLOUDBASE_ACCESS_KEY\n});\n```",
            "index": 1,
            "title": "src/utils/cloudbase.js",
            "content": []
          },
          {
            "markdown": "```properties\n# Environment ID\nVITE_CLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Region\nVITE_CLOUDBASE_REGION={%REGION%}\n\n# Anonymous access token\nVITE_CLOUDBASE_ACCESS_KEY={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": ".env",
            "content": []
          }
        ]
      },
      {
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table first 10 records\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\nif (!error) {\n  console.log(data);\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState, useEffect } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState([]);\n\n  useEffect(() => {\n    getData();\n  }, []);\n\n  const getData = async () => {\n    // Query {%TABLE_NAME%} table first 10 records\n    const { data, error } = await cloudbase\n      .rdb()\n      .from(\"{%TABLE_NAME%}\")\n      .select(\"*\")\n      .limit(10);\n    if (!error) setData(data || []);\n  };\n\n  return (\n    <ul>\n      {data.map(item => (\n        <li key={item.id}>{item.title}</li>\n      ))}\n    </ul>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} table data\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"Example Title\" });\nif (!error) {\n  console.log(\"Insert successful\");\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [title, setTitle] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  const addData = async () => {\n    // Add {%TABLE_NAME%} table data\n    const { error } = await cloudbase\n      .rdb()\n      .from(\"{%TABLE_NAME%}\")\n      .insert({ title });\n    if (!error) {\n      setTitle(\"\");\n      setMessage(\"Insert successful！\");\n    } else {\n      setMessage(\"Insert failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <input value={title} onChange={e => setTitle(e.target.value)} />\n      <button onClick={addData}>Add</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} table id with specified value\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ title: \"New Title\" })\n  .eq(\"id\", \"<data id>\");\nif (!error) {\n  console.log(\"Update successful\");\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const updateData = async () => {\n    // Update {%TABLE_NAME%} table id with specified value\n    const { error } = await cloudbase\n      .rdb()\n      .from(\"{%TABLE_NAME%}\")\n      .update({ title: \"New Title\" })\n      .eq(\"id\", \"<data id>\");\n    if (!error) {\n      setMessage(\"Update successful！\");\n    } else {\n      setMessage(\"Update failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={updateData}>Update</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Example Title\" });\nif (!error) {\n  console.log(\"Operation successful\");\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const upsertData = async () => {\n    // If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\n    const { error } = await cloudbase\n      .rdb()\n      .from(\"{%TABLE_NAME%}\")\n      .upsert({ id: 1, title: \"Example Title\" });\n    if (!error) {\n      setMessage(\"Operation successful！\");\n    } else {\n      setMessage(\"Operation failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={upsertData}>UpdateorCreate</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} table id with specified value\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", \"<data id>\");\nif (!error) {\n  console.log(\"Delete successful\");\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const deleteData = async () => {\n    // Delete {%TABLE_NAME%} table id with specified value\n    const { error } = await cloudbase\n      .rdb()\n      .from(\"{%TABLE_NAME%}\")\n      .delete()\n      .eq(\"id\", \"<data id>\");\n    if (!error) {\n      setMessage(\"Delete successful！\");\n    } else {\n      setMessage(\"Delete failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={deleteData}>Delete</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table first 10 records\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\nconsole.log(res.data);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState, useEffect } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState([]);\n\n  useEffect(() => {\n    getData();\n  }, []);\n\n  const getData = async () => {\n    // Query {%TABLE_NAME%} table first 10 records\n    const db = cloudbase.database();\n    const res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n    setData(res.data || []);\n  };\n\n  return (\n    <ul>\n      {data.map(item => (\n        <li key={item._id}>{item.title}</li>\n      ))}\n    </ul>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} table data\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({ title: \"Example Title\" });\nconsole.log(`Insert successful! id: ${res.id}`);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const addData = async () => {\n    try {\n      // Add {%TABLE_NAME%} table data\n      const db = cloudbase.database();\n      const res = await db\n        .collection(\"{%TABLE_NAME%}\")\n        .add({ title: \"Example Title\" });\n      setMessage(`Insert successful! id: ${res.id}`);\n    } catch (error) {\n      setMessage(\"Insert failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={addData}>Add</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} table id with specified value\nconst db = cloudbase.database();\nawait db\n  .collection(\"{%TABLE_NAME%}\")\n  .doc(\"<data id>\")\n  .update({ title: \"New Title\" });\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const updateData = async () => {\n    try {\n      // Update {%TABLE_NAME%} table id with specified value\n      const db = cloudbase.database();\n      await db\n        .collection(\"{%TABLE_NAME%}\")\n        .doc(\"<data id>\")\n        .update({ title: \"New Title\" });\n      setMessage(\"Update successful！\");\n    } catch (error) {\n      setMessage(\"Update failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={updateData}>Update</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} table id with specified value\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").remove();\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const deleteData = async () => {\n    try {\n      // Delete {%TABLE_NAME%} table id with specified value\n      const db = cloudbase.database();\n      await db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").remove();\n      setMessage(\"Delete successful！\");\n    } catch (error) {\n      setMessage(\"Delete failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={deleteData}>Delete</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} Data Modelbefore10recordsData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\nconsole.log(res.data?.records);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState, useEffect } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState([]);\n\n  useEffect(() => {\n    getData();\n  }, []);\n\n  const getData = async () => {\n    // Query {%TABLE_NAME%} Data Modelbefore10recordsData\n    const res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n      pageNumber: 1,\n      pagesize: 10\n    });\n    setData(res.data?.records || []);\n  };\n\n  return (\n    <ul>\n      {data.map(item => (\n        <li key={item._id}>{item.title}</li>\n      ))}\n    </ul>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} Data ModelData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: { title: \"Example Title\" }\n});\nconsole.log(`Insert successful! id: ${res.data.id}`);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const addData = async () => {\n    try {\n      // Add {%TABLE_NAME%} Data ModelData\n      const res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n        data: { title: \"Example Title\" }\n      });\n      setMessage(`Insert successful! id: ${res.data.id}`);\n    } catch (error) {\n      setMessage(\"Insert failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={addData}>Add</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} Data Model _id with specified value\nawait cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: { title: \"New Title\" },\n  filter: { where: { _id: { $eq: \"<data id>\" } } }\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const updateData = async () => {\n    try {\n      // Update {%TABLE_NAME%} Data Model _id with specified value\n      await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n        data: { title: \"New Title\" },\n        filter: { where: { _id: { $eq: \"<data id>\" } } }\n      });\n      setMessage(\"Update successful！\");\n    } catch (error) {\n      setMessage(\"Update failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={updateData}>Update</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} Data Model _id with specified value\nawait cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: { where: { _id: { $eq: \"<data id>\" } } }\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const deleteData = async () => {\n    try {\n      // Delete {%TABLE_NAME%} Data Model _id with specified value\n      await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n        filter: { where: { _id: { $eq: \"<data id>\" } } }\n      });\n      setMessage(\"Delete successful！\");\n    } catch (error) {\n      setMessage(\"Delete failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={deleteData}>Delete</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call {%FUNCTION_NAME%} Cloud Function\nconst res = await cloudbase.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {}\n});\nconsole.log(res.result);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState(null);\n\n  const getData = async () => {\n    // Call {%FUNCTION_NAME%} Cloud Function\n    const res = await cloudbase.callFunction({\n      name: \"{%FUNCTION_NAME%}\",\n      data: {}\n    });\n    setData(res.result);\n  };\n\n  return (\n    <div>\n      <button onClick={getData}>CallCloud Function</button>\n      {data && <pre>{JSON.stringify(data, null, 2)}</pre>}\n    </div>\n  );\n}\n\nexport default Page;\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function",
            "content": []
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call {%SERVICE_NAME%} Cloud Runservice\nconst res = await cloudbase.callContainer({\n  name: \"{%SERVICE_NAME%}\"\n  method: 'POST',\n  path: '/',\n  header:{\n    'Content-Type': 'application/json; charset=utf-8'\n  },\n  data: {},\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState(null);\n\n  const getData = async () => {\n    // Call {%SERVICE_NAME%} Cloud Runservice\n    const res = await cloudbase.callContainer({\n      name: \"{%SERVICE_NAME%}\"\n      method: 'POST',\n      path: '/',\n      header:{\n        'Content-Type': 'application/json; charset=utf-8'\n      },\n      data: {},\n    });\n    setData(res);\n  };\n\n  return (\n    <div>\n      <button onClick={getData}>CallCloud Run</button>\n      {data && <pre>{JSON.stringify(data, null, 2)}</pre>}\n    </div>\n  );\n}\n\nexport default Page;\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run",
            "content": []
          },
          {
            "index": 6,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.uploadFile({\n  cloudPath: `images/${Date.now()}-${file.name}`, // Path to upload in cloud\n  filePath: file\n});\nconsole.log(res.fileID);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [fileID, setFileID] = useState(\"\");\n\n  const uploadFile = async e => {\n    const file = e.target.files[0];\n    const res = await cloudbase.uploadFile({\n      cloudPath: `images/${Date.now()}-${file.name}`, // Path to upload in cloud\n      filePath: file\n    });\n    setFileID(res.fileID);\n  };\n\n  return (\n    <div>\n      <input type=\"file\" onChange={uploadFile} />\n      {fileID && <p>Upload successful: {fileID}</p>}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "title": "Upload File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.getTempFileURL({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\nconsole.log(res.fileList[0].tempFileURL);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [fileUrl, setFileUrl] = useState(\"\");\n\n  const getData = async () => {\n    const res = await cloudbase.getTempFileURL({\n      fileList: [\"cloud://xxx.png\"] // File fileID list\n    });\n    setFileUrl(res.fileList[0].tempFileURL);\n  };\n\n  return (\n    <div>\n      <button onClick={getData}>GetURL</button>\n      {fileUrl && <p>URL: {fileUrl}</p>}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 2,
                "title": "Get File URL"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nawait cloudbase.downloadFile({\n  fileID: \"cloud://xxx.png\" // File fileID\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const downloadFile = async () => {\n    await cloudbase.downloadFile({\n      fileID: \"cloud://xxx.png\" // File fileID\n    });\n  };\n\n  return <button onClick={downloadFile}>Download File</button>;\n}\n\nexport default Page;\n```",
                "index": 3,
                "title": "Download File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.deleteFile({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\nif (res.fileList[0].code === \"SUCCESS\") {\n  console.log(\"Delete successful\");\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const deleteFile = async () => {\n    const res = await cloudbase.deleteFile({\n      fileList: [\"cloud://xxx.png\"] // File fileID list\n    });\n    if (res.fileList[0].code === \"SUCCESS\") {\n      setMessage(\"Delete successful！\");\n    } else {\n      setMessage(\"Delete failed！\", res.fileList);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={deleteFile}>Delete File</button>\n      {message && <p>{message}</p>}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 4,
                "title": "Delete File"
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase\n  .ai()\n  .createModel(\"{%AI_MODEL_NAME%}\")\n  .streamText({\n    model: \"{%AI_SUB_MODEL_NAME%}\",\n    messages: [{ role: \"user\", content: \"Hello\" }]\n  });\n\nfor await (let data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data?.choices?.[0]?.delta?.reasoning_content;\n  if (think) console.log(think);\n\n  // Print generated text content\n  const text = data?.choices?.[0]?.delta?.content;\n  if (text) console.log(text);\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState(\"\");\n  const [input, setInput] = useState(\"\");\n\n  const getData = async () => {\n    const res = await cloudbase\n      .ai()\n      .createModel(\"{%AI_MODEL_NAME%}\")\n      .streamText({\n        model: \"{%AI_SUB_MODEL_NAME%}\",\n        messages: [{ role: \"user\", content: input }]\n      });\n\n    let result = \"\";\n    for await (let data of res.dataStream) {\n      // Print reasoning content if available\n      const think = data?.choices?.[0]?.delta?.reasoning_content;\n      if (think) {\n        result += think;\n      }\n\n      // Print generated text content\n      const text = data?.choices?.[0]?.delta?.content;\n      if (text) result += text;\n\n      setData(result);\n    }\n  };\n\n  return (\n    <div>\n      <input\n        value={input}\n        placeholder=\"Enter AI conversation content\"\n        onChange={e => setInput(e.target.value)}\n      />\n      <button onClick={getData}>Send</button>\n      <p>{data}</p>\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation"
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call image generation cloud function\nconst res = await cloudbase.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: {\n    prompt: \"A cute cat playing in the sunshine\"\n  }\n});\n\nconst result = res.result;\n\nif (result.success) {\n  // Generation successful\n  console.log(\"Generation successful!\");\n  console.log(\"Image URL:\", result.imageUrl);\n  console.log(\"Optimized prompt:\", result.revised_prompt);\n\n  // Use image\n  // Note: Image URL is valid for 24 hours, please save or transfer promptly\n} else {\n  // Generation failed\n  console.error(\"Generation failed:\", result.code, result.message);\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [prompt, setPrompt] = useState(\"\");\n  const [imageUrl, setImageUrl] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n  const [loading, setLoading] = useState(false);\n\n  const generateImage = async () => {\n    setLoading(true);\n    setMessage(\"\");\n    setImageUrl(\"\");\n\n    try {\n      // Call image generation cloud function\n      const res = await cloudbase.callFunction({\n        name: \"<YOUR_FUNCTION_NAME>\",\n        data: {\n          prompt: prompt\n        }\n      });\n\n      const result = res.result;\n\n      if (result.success) {\n        setImageUrl(result.imageUrl);\n        setMessage(\"Generation successful！\");\n      } else {\n        setMessage(`Generation failed：${result.message}`);\n      }\n    } catch (error) {\n      setMessage(\"Call failed：\" + error.message);\n    } finally {\n      setLoading(false);\n    }\n  };\n\n  return (\n    <div>\n      <input\n        value={prompt}\n        placeholder=\"Enter image description\"\n        onChange={e => setPrompt(e.target.value)}\n      />\n      <button onClick={generateImage} disabled={!prompt || loading}>\n        {loading ? \"Generating...\" : \"Generate Image\"}\n      </button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n      {imageUrl && (\n        <div>\n          <img src={imageUrl} alt=\"Generated image\" style={{ maxWidth: \"100%\" }} />\n          <p style={{ fontSize: \"12px\", color: \"#666\" }}>\n            Note: Image URL is valid for 24 hours, please save promptly\n          </p>\n        </div>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation"
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from './utils/cloudbase';\n\nconst res = await cloudbase.ai().bot.sendMessage({\n  botId: '{%AGENT_ID%}',\n  // Refer to frontend-backend communication protocol for input structure：\n  //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n  threadId: '550e8400-e29b-41d4-a716-446655440000',\n  runId: 'run_001',\n  messages: [\n    {\n      id: 'msg_001',\n      role: 'user',\n      content: 'Hello',\n    },\n  ],\n  tools: [],\n  context: [],\n  state: {},\n  forwardedProps: {},\n});\n\nfor await (const data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data.reasoning_content;\n  if (think) console.log(think);\n\n  // Print output content\n  const content = data.content;\n  if (content) console.log(content);\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from 'react';\nimport { cloudbase } from './utils/cloudbase';\n\nfunction Page() {\n  const [data, setData] = useState('');\n  const [input, setInput] = useState('');\n\n  const getData = async () => {\n    const res = await cloudbase.ai().bot.sendMessage({\n      botId: '{%AGENT_ID%}',\n      // Refer to frontend-backend communication protocol for input structure：\n      //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n      threadId: '550e8400-e29b-41d4-a716-446655440000',\n      runId: 'run_001',\n      messages: [\n        {\n          id: 'msg_001',\n          role: 'user',\n          content: input,\n        },\n      ],\n      tools: [],\n      context: [],\n      state: {},\n      forwardedProps: {},\n    });\n\n    let result = '';\n    for await (const data of res.dataStream) {\n      // Print reasoning content if available\n      const think = data.reasoning_content;\n      if (think) {\n        result += think;\n      }\n\n      // Print output content\n      const content = data.content;\n      if (content) result += content;\n\n      setData(result);\n    }\n  };\n\n  return (\n    <div>\n      <input value={input} placeholder=\"Enter Agent conversation content\" onChange={(e) => setInput(e.target.value)} />\n      <button onClick={getData}>Send</button>\n      <p>{data}</p>\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.ai().bot.sendMessage({\n  botId: \"{%AGENT_ID%}\",\n  msg: \"Hello\"\n});\n\nfor await (const data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data.reasoning_content;\n  if (think) console.log(think);\n\n  // Print output content\n  const content = data.content;\n  if (content) console.log(content);\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState(\"\");\n  const [input, setInput] = useState(\"\");\n\n  const getData = async () => {\n    const res = await cloudbase.ai().bot.sendMessage({\n      botId: \"{%AGENT_ID%}\",\n      msg: input\n    });\n\n    let result = \"\";\n    for await (const data of res.dataStream) {\n      // Print reasoning content if available\n      const think = data.reasoning_content;\n      if (think) {\n        result += think;\n      }\n\n      // Print output content\n      const content = data.content;\n      if (content) result += content;\n\n      setData(result);\n    }\n  };\n\n  return (\n    <div>\n      <input\n        value={input}\n        placeholder=\"Enter Agent conversation content\"\n        onChange={e => setInput(e.target.value)}\n      />\n      <button onClick={getData}>Send</button>\n      <p>{data}</p>\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 9,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "Use **SMS Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMSVerification code**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: phone });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  phone_number: `+86 ${phone}`,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${phone.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [phone, setPhone] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationId, setVerificationId] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ phone_number: phone });\n      setVerificationId(res.verification_id);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(\"Send failed：\" + error.message);\n    }\n  };\n\n  // Register\n  const register = async () => {\n    try {\n      const auth = cloudbase.auth();\n      // Verify the code\n      const verifyRes = await auth.verify({\n        verification_id: verificationId,\n        verification_code: code\n      });\n      // Register (auto-login if user exists)\n      await auth.signUp({\n        phone_number: `+86 ${phone}`,\n        verification_code: code,\n        verification_token: verifyRes.verification_token,\n        name: `user_${phone.slice(-4)}`,\n        password: \"admin@123\"\n      });\n      setMessage(\"Registration successful！\");\n    } catch (error) {\n      setMessage(\"Registration failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <label>Phone number：</label>\n      <input\n        value={phone}\n        onChange={e => setPhone(e.target.value)}\n        placeholder=\"13800000000\"\n      />\n      <div>\n        <label>Verification code：</label>\n        <input\n          value={code}\n          onChange={e => setCode(e.target.value)}\n          placeholder=\"Verification code\"\n        />\n        <button disabled={!phone} onClick={sendCode}>\n          Send Code\n        </button>\n      </div>\n      <button disabled={!verificationId || !code} onClick={register}>\n        Register\n      </button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "title": "SMS Code Registration"
              },
              {
                "markdown": "Use **Email Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  email,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${email.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [email, setEmail] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationId, setVerificationId] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ email });\n      setVerificationId(res.verification_id);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(\"Send failed：\" + error.message);\n    }\n  };\n\n  // Register\n  const register = async () => {\n    try {\n      const auth = cloudbase.auth();\n      // Verify the code\n      const verifyRes = await auth.verify({\n        verification_id: verificationId,\n        verification_code: code\n      });\n      // Register (auto-login if user exists)\n      await auth.signUp({\n        email,\n        verification_code: code,\n        verification_token: verifyRes.verification_token,\n        name: `user_${email.slice(-4)}`,\n        password: \"admin@123\"\n      });\n      setMessage(\"Registration successful！\");\n    } catch (error) {\n      setMessage(\"Registration failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <label>Email：</label>\n      <input\n        value={email}\n        onChange={e => setEmail(e.target.value)}\n        placeholder=\"example@email.com\"\n      />\n      <div>\n        <label>Verification code：</label>\n        <input\n          value={code}\n          onChange={e => setCode(e.target.value)}\n          placeholder=\"Verification code\"\n        />\n        <button disabled={!email} onClick={sendCode}>\n          Send Code\n        </button>\n      </div>\n      <button disabled={!verificationId || !code} onClick={register}>\n        Register\n      </button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 2,
                "title": "Email Code Registration"
              },
              {
                "markdown": "Use **Username Password Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **UsernamePasswordLogin**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\nawait auth.signIn({\n  username, // Can be username, phone or email\n  password\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [username, setUsername] = useState(\"\");\n  const [password, setPassword] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  // Login\n  const login = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signIn({\n        username: username, // Can be username, phone or email\n        password: password\n      });\n      setMessage(\"Login successful！\");\n    } catch (error) {\n      setMessage(\"Login failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <label>Account：</label>\n      <input\n        value={username}\n        onChange={e => setUsername(e.target.value)}\n        placeholder=\"Username/Phone/Email\"\n      />\n      Note: Add country code for phone login +86\n      <br />\n      <label>Password：</label>\n      <input\n        type=\"password\"\n        value={password}\n        onChange={e => setPassword(e.target.value)}\n        placeholder=\"Enter password\"\n      />\n      <br />\n      <button disabled={!username || !password} onClick={login}>\n        Login\n      </button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login"
              },
              {
                "markdown": "Use **SMS Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMS Verification Login**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n\n// Login\nawait auth.signInWithSms({\n  verificationInfo: res,\n  verificationCode: code,\n  phoneNum: `+86 ${phone}`\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [phone, setPhone] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationInfo, setVerificationInfo] = useState(null);\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n      setVerificationInfo(res);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(\"Send failed：\" + error.message);\n    }\n  };\n\n  // Login\n  const login = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInWithSms({\n        verificationInfo,\n        verificationCode: code,\n        phoneNum: `+86 ${phone}`\n      });\n      setMessage(\"Login successful！\");\n    } catch (error) {\n      setMessage(\"Login failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <label>Phone number：</label>\n      <input\n        value={phone}\n        onChange={e => setPhone(e.target.value)}\n        placeholder=\"13800000000\"\n      />\n      <div>\n        <label>Verification code：</label>\n        <input\n          value={code}\n          onChange={e => setCode(e.target.value)}\n          placeholder=\"Verification code\"\n        />\n        <button onClick={sendCode} disabled={!phone}>\n          Send Code\n        </button>\n      </div>\n      <button onClick={login} disabled={!verificationInfo || !code}>\n        Login\n      </button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login"
              },
              {
                "markdown": "Use **Email Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Login\nawait auth.signInWithEmail({\n  verificationInfo: res,\n  verificationCode: code,\n  email\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [email, setEmail] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationInfo, setVerificationInfo] = useState(null);\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ email });\n      setVerificationInfo(res);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(\"Send failed：\" + error.message);\n    }\n  };\n\n  // Login\n  const login = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInWithEmail({\n        verificationInfo,\n        verificationCode: code,\n        email\n      });\n      setMessage(\"Login successful！\");\n    } catch (error) {\n      setMessage(\"Login failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <label>Email：</label>\n      <input\n        value={email}\n        onChange={e => setEmail(e.target.value)}\n        placeholder=\"example@email.com\"\n      />\n      <div>\n        <label>Verification code：</label>\n        <input\n          value={code}\n          onChange={e => setCode(e.target.value)}\n          placeholder=\"Verification code\"\n        />\n        <button onClick={sendCode} disabled={!email}>\n          Send Code\n        </button>\n      </div>\n      <button onClick={login} disabled={!verificationInfo || !code}>\n        Login\n      </button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login"
              },
              {
                "markdown": "Use **Google OAuth Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **Google OAuth Login**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Step1：GenerateGoogleauthorization URLandRedirect\nconst state = Date.now().toString();\nlocalStorage.setItem(\"google_login_state\", state);\nconst { uri } = await auth.genProviderRedirectUri({\n  provider_id: \"google\",\n  provider_redirect_uri: window.location.href,\n  state: state\n});\nwindow.location.href = uri;\n\n// Step2：Usecodeexchange forprovider_token\nconst { provider_token } = await auth.grantProviderToken({\n  provider_id: \"google\",\n  provider_redirect_uri: window.location.origin + window.location.pathname,\n  provider_code: code\n});\n\n// Step3：Useprovider_tokenLogin\nawait auth.signInWithProvider({\n  provider_token: provider_token\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState, useEffect } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n  const [isCallback, setIsCallback] = useState(false);\n\n  useEffect(() => {\n    // CheckYesNoYesGoogleCallbackPage\n    const urlParams = new URLSearchParams(window.location.search);\n    const code = urlParams.get(\"code\");\n    const state = urlParams.get(\"state\");\n\n    if (code && state) {\n      setIsCallback(true);\n      handleGoogleCallback(code, state);\n    }\n  }, []);\n\n  // Step1：Redirect toGoogleauthorization page\n  const startGoogleLogin = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const state = Date.now().toString(); // Generate unique identifier to prevent CSRF attacks\n\n      // Save state locally for callback verification\n      localStorage.setItem(\"google_login_state\", state);\n\n      // GenerateGoogleauthorization URL\n      const { uri } = await auth.genProviderRedirectUri({\n        provider_id: \"google\", // Fixed value, representingGoogleOpen Platform\n        provider_redirect_uri: window.location.href, // Callback to current page after authorization\n        state: state\n      });\n\n      // Redirect toGoogleauthorization page\n      window.location.href = uri;\n    } catch (error) {\n      setMessage(\"Redirect failed：\" + error.message);\n    }\n  };\n\n  // Step2and3：ProcessGoogleCallbackandDoneLogin\n  const handleGoogleCallback = async (code, state) => {\n    try {\n      // Verify state matches to prevent CSRF attacks\n      const savedState = localStorage.getItem(\"google_login_state\");\n      if (savedState !== state) {\n        setMessage(\"Login failed：State verification failed\");\n        return;\n      }\n\n      const auth = cloudbase.auth();\n\n      // Usecodeexchange forprovider_token\n      const { provider_token } = await auth.grantProviderToken({\n        provider_id: \"google\",\n        provider_redirect_uri:\n          window.location.origin + window.location.pathname,\n        provider_code: code\n      });\n\n      try {\n        // Try direct login\n        await auth.signInWithProvider({\n          provider_token: provider_token\n        });\n\n        setMessage(\"Login successful！\");\n\n        // Clear URL parameters and local storage\n        localStorage.removeItem(\"google_login_state\");\n        window.history.replaceState(\n          {},\n          document.title,\n          window.location.pathname\n        );\n      } catch (loginError) {\n        // IfYesfirst-timeGoogleLogin，needfirstRegisterandbindthe\n        if (loginError.error === \"not_found\") {\n          setMessage(\"Detected first-timeGoogleLogin，Need to bindaccount...\");\n\n          // Here you need to guide the user to complete the registration process\n          // For example: collect phone verification code for registration\n          // After successful registration, call bindWithProvider bindtheGoogleidentity\n\n          // Example: Assuming an account registered via other methods, bindirect\n          await auth.bindWithProvider({\n            provider_token: provider_token\n          });\n\n          // Re-login after successful bindng\n          await auth.signInWithProvider({\n            provider_token: provider_token\n          });\n\n          setMessage(\"bindand login successful！\");\n\n          // Clear URL parameters and local storage\n          localStorage.removeItem(\"google_login_state\");\n          window.history.replaceState(\n            {},\n            document.title,\n            window.location.pathname\n          );\n        } else {\n          throw loginError;\n        }\n      }\n    } catch (error) {\n      setMessage(\"Login failed：\" + error.message);\n      localStorage.removeItem(\"google_login_state\");\n    }\n  };\n\n  return (\n    <div>\n      {!isCallback && <button onClick={startGoogleLogin}>GoogleLogin</button>}\n      {isCallback && <p>ProcessingGoogleLogin...</p>}\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 6,
                "id": "google",
                "title": "Google OAuth Login"
              }
            ]
          }
        ]
      }
    ],
    "_id": "18ffb4c969a92871004591b92fd6a4e7",
    "_openid": "anon",
    "createdAt": 1769767035561,
    "updatedAt": 1769767035561
  },
  {
    "category": "Framework Integration,Backend Frameworks,Python",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 9,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/http-api/basic/overview",
    "content": [
      {
        "markdown": "Use **HTTP Request** in **python** Callvarious CloudBase capabilities\n\n```bash\npip install requests python-dotenv\n```",
        "index": 1,
        "title": "Install Dependencies",
        "content": []
      },
      {
        "markdown": "Add the following code to your **Python** project",
        "index": 2,
        "title": "Initialize Configuration",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```python\nimport os\nimport requests\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nclass CloudBaseClient:\n\tdef __init__(self):\n\t\tself.env_id = os.getenv(\"CLOUDBASE_ENV_ID\")\n\t\tself.access_token = os.getenv(\"CLOUDBASE_ACCESS_TOKEN\")\n\t\tself.base_url = f\"https://{self.env_id}.api.tcloudbasegateway.com\"\n\t\tself.headers = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"Accept\": \"application/json\",\n\t\t\t\"Authorization\": f\"Bearer {self.access_token}\"\n\t\t}\n\n\tdef request(self, method, path, **kwargs):\n\t\t\"\"\"\n\t\tUnified HTTP request method\n\n\t\tArgs:\n\t\t\tmethod: Request method (GET, POST, PUT, PATCH, DELETE)\n\t\t\tpath: APIPath (such as /v1/rdb/rest/table_name)\n\t\t\t**kwargs: otherRequestparameter (json, params, headersetc)\n\n\t\tReturns:\n\t\t\tResponseDataorNone\n\t\t\"\"\"\n\t\turl = f\"{self.base_url}{path}\"\n\t\theaders = self.headers.copy()\n\n\t\t# AllowCustomheaders\n\t\tif \"headers\" in kwargs:\n\t\t\theaders.update(kwargs.pop(\"headers\"))\n\n\t\ttry:\n\t\t\tresponse = requests.request(method, url, headers=headers, **kwargs)\n\t\t\tresponse.raise_for_status()\n\n\t\t\t# IfResponseis empty，ReturnTruerepresentssuccessful\n\t\t\tif not response.content:\n\t\t\t\treturn True\n\n\t\t\treturn response.json()\n\t\texcept requests.exceptions.RequestException as e:\n\t\t\tprint(f\"Requestfailed: {e}\")\n\t\t\treturn None\n\ncloudbase = CloudBaseClient()\n```",
            "index": 1,
            "title": "cloudbase_client.py"
          },
          {
            "markdown": "> 💡Note: If admin permission is needed, obtain the APIKey from the [CloudBase Platform/ApiKeymanagement page](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}&#/env/apikey) Get APIKey to replace CLOUDBASE_ACCESS_TOKEN\n\n```properties\n# Environment ID\nCLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Anonymous access token\nCLOUDBASE_ACCESS_TOKEN={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": ".env"
          }
        ]
      },
      {
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef get_mysql_data(table_name):\n\t\"\"\"Query MySQL database data\"\"\"\n\tdata = cloudbase.request(\"GET\", f\"/v1/rdb/rest/{table_name}?limit=10\")\n\n\tif data:\n\t\tprint(\"Querysuccessful:\", data)\n\treturn data or []\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = get_mysql_data(\"{%TABLE_NAME%}\")\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef add_mysql_data(table_name, data):\n\t\"\"\"Add MySQL database data\"\"\"\n\tresult = cloudbase.request(\"POST\", f\"/v1/rdb/rest/{table_name}\", json=data)\n\n\tif result:\n\t\tprint(\"Insert successful:\", result)\n\treturn result\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = add_mysql_data(\"{%TABLE_NAME%}\", {\"title\": \"Example Title\"})\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef update_mysql_data(table_name, data_id, data):\n\t\"\"\"Update MySQL database data\"\"\"\n\tresult = cloudbase.request(\"PATCH\", f\"/v1/rdb/rest/{table_name}?id=eq.{data_id}\", json=data)\n\n\tif result:\n\t\tprint(\"Update successful:\", result)\n\treturn result\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = update_mysql_data(\"{%TABLE_NAME%}\", \"<data id>\", {\"title\": \"New Title\"})\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef delete_mysql_data(table_name, data_id):\n\t\"\"\"Delete MySQL database data\"\"\"\n\tresult = cloudbase.request(\"DELETE\", f\"/v1/rdb/rest/{table_name}?id=eq.{data_id}\")\n\n\tif result:\n\t\tprint(\"Delete successful\")\n\t\treturn True\n\treturn False\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = delete_mysql_data(\"{%TABLE_NAME%}\", \"<data id>\")\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef get_model_data(model_name, env_type=\"prod\"):\n\t\"\"\"QueryData ModelData\"\"\"\n\tpayload = {\n\t\t\"pageSize\": 10,\n\t\t\"pageNumber\": 1,\n\t\t\"getCount\": True\n\t}\n\n\tresult = cloudbase.request(\"POST\", f\"/v1/model/{env_type}/{model_name}/list\", json=payload)\n\n\tif result:\n\t\trecords = result.get(\"data\", {}).get(\"records\", [])\n\t\tprint(\"Querysuccessful:\", records)\n\t\treturn records\n\treturn []\n\n# Usage Example\nif __name__ == \"__main__\":\n\trecords = get_model_data(\"{%TABLE_NAME%}\")\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef add_model_data(model_name, data, env_type=\"prod\"):\n\t\"\"\"AddData ModelData\"\"\"\n\tresult = cloudbase.request(\"POST\", f\"/v1/model/{env_type}/{model_name}/create\", json={\"data\": data})\n\n\tif result:\n\t\tdoc_id = result.get(\"data\", {}).get(\"id\")\n\t\tprint(f\"Insert successful! id: {doc_id}\")\n\treturn result\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = add_model_data(\"{%TABLE_NAME%}\", {\"title\": \"Example Title\"})\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef update_model_data(model_name, data_id, data, env_type=\"prod\"):\n\t\"\"\"UpdateData ModelData\"\"\"\n\tpayload = {\n\t\t\"data\": data,\n\t\t\"filter\": {\n\t\t\t\"where\": {\n\t\t\t\t\"_id\": {\"$eq\": data_id}\n\t\t\t}\n\t\t}\n\t}\n\n\tresult = cloudbase.request(\"PUT\", f\"/v1/model/{env_type}/{model_name}/update\", json=payload)\n\n\tif result:\n\t\tprint(\"Update successful!\")\n\t\treturn True\n\treturn False\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = update_model_data(\"{%TABLE_NAME%}\", \"<data id>\", {\"title\": \"New Title\"})\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef delete_model_data(model_name, data_id, env_type=\"prod\"):\n\t\"\"\"DeleteData ModelData\"\"\"\n\tpayload = {\n\t\t\"filter\": {\n\t\t\t\"where\": {\n\t\t\t\t\"_id\": {\"$eq\": data_id}\n\t\t\t}\n\t\t}\n\t}\n\n\tresult = cloudbase.request(\"POST\", f\"/v1/model/{env_type}/{model_name}/delete\", json=payload)\n\n\tif result:\n\t\tprint(\"Delete successful!\")\n\t\treturn True\n\treturn False\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = delete_model_data(\"{%TABLE_NAME%}\", \"<data id>\")\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef call_function(function_name, data=None):\n\t\"\"\"CallCloud Function\"\"\"\n\tresult = cloudbase.request(\"POST\", f\"/v1/functions/{function_name}\", json=data or {})\n\n\tif result:\n\t\tprint(\"Cloud function call result:\", result)\n\treturn result\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = call_function(\"{%FUNCTION_NAME%}\")\n```",
            "index": 3,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef call_container(service_name, path=\"\", method=\"GET\", data=None):\n\t\"\"\"CallCloud Runservice\"\"\"\n\tfull_path = f\"/v1/cloudrun/{service_name}/{path}\".rstrip(\"/\")\n\tresult = cloudbase.request(method.upper(), full_path, json=data)\n\n\tif result:\n\t\tprint(\"Cloud RunCallResult:\", result)\n\treturn result\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = call_container(\"{%SERVICE_NAME%}\")\n```",
            "index": 4,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```python\nimport os\nimport requests\nfrom datetime import datetime\nfrom cloudbase_client import cloudbase\n\ndef upload_file(file_path, object_id=None):\n\t\"\"\"Upload FiletoCloud Storage\"\"\"\n\tif not object_id:\n\t\tfilename = os.path.basename(file_path)\n\t\ttimestamp = int(datetime.now().timestamp() * 1000)\n\t\tobject_id = f\"uploads/{timestamp}-{filename}\"\n\n\t# 1. Get upload info\n\tupload_info = cloudbase.request(\"POST\", \"/v1/storages/get-objects-upload-info\",\n\t\tjson=[{\"objectId\": object_id}])\n\n\tif not upload_info:\n\t\treturn None\n\n\tupload_info = upload_info[0]\n\tupload_url = upload_info[\"uploadUrl\"]\n\n\ttry:\n\t\t# 2. Upload File\n\t\tupload_headers = {\n\t\t\t\"Authorization\": upload_info[\"authorization\"],\n\t\t\t\"X-Cos-Security-Token\": upload_info[\"token\"],\n\t\t\t\"X-Cos-Meta-Fileid\": upload_info[\"cloudObjectMeta\"]\n\t\t}\n\n\t\twith open(file_path, \"rb\") as f:\n\t\t\tfile_data = f.read()\n\n\t\tupload_response = requests.put(upload_url, headers=upload_headers, data=file_data)\n\t\tupload_response.raise_for_status()\n\n\t\tresult = {\n\t\t\t\"cloudObjectId\": upload_info[\"cloudObjectId\"],\n\t\t\t\"downloadUrl\": upload_info[\"downloadUrl\"],\n\t\t\t\"objectId\": object_id\n\t\t}\n\n\t\tprint(\"fileUpload successful:\")\n\t\tprint(f\"- Object ID: {result['objectId']}\")\n\t\tprint(f\"- DownloadURL: {result['downloadUrl']}\")\n\n\t\treturn result\n\n\texcept FileNotFoundError:\n\t\tprint(f\"filedoes not exist: {file_path}\")\n\t\treturn None\n\texcept Exception as e:\n\t\tprint(f\"fileUploadfailed: {e}\")\n\t\treturn None\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = upload_file(\"./example.jpg\")\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef get_file_url(cloud_object_id):\n\t\"\"\"GetCloud Storagefiletemporary accessURL\"\"\"\n\tresult = cloudbase.request(\"POST\", \"/v1/storages/get-objects-download-info\",\n\t\tjson=[{\"cloudObjectId\": cloud_object_id}])\n\n\tif result:\n\t\tdownload_url = result[0].get(\"downloadUrl\")\n\t\tprint(\"fileURL:\", download_url)\n\t\treturn download_url\n\treturn None\n\n# Usage Example\nif __name__ == \"__main__\":\n\tfile_url = get_file_url(\"cloud://xxx.png\")\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```python\nimport os\nimport requests\nfrom cloudbase_client import cloudbase\n\ndef download_file(cloud_object_id, save_path=\"./\"):\n\t\"\"\"DownloadCloud Storagefiletolocal\"\"\"\n\t# 1. GetDownloadURL\n\tresult = cloudbase.request(\"POST\", \"/v1/storages/get-objects-download-info\",\n\t\tjson=[{\"cloudObjectId\": cloud_object_id}])\n\n\tif not result:\n\t\treturn False\n\n\tdownload_url = result[0].get(\"downloadUrl\")\n\n\ttry:\n\t\t# 2. fromURLExtractfilename\n\t\tfilename = download_url.split(\"/\")[-1].split(\"?\")[0]\n\n\t\t# 3. Ifsave_pathYesDirectory，thenConcatenatefilename\n\t\tif os.path.isdir(save_path) or save_path.endswith(\"/\"):\n\t\t\tfull_path = os.path.join(save_path, filename)\n\t\telse:\n\t\t\tfull_path = save_path\n\n\t\t# 4. Download File\n\t\tfile_response = requests.get(download_url)\n\t\tfile_response.raise_for_status()\n\n\t\t# 5. Save to local\n\t\twith open(full_path, \"wb\") as f:\n\t\t\tf.write(file_response.content)\n\n\t\tprint(f\"Downloadsuccessful! filesaved to: {full_path}\")\n\t\treturn True\n\texcept Exception as e:\n\t\tprint(f\"Downloadfailed: {e}\")\n\t\treturn False\n\n# Usage Example\nif __name__ == \"__main__\":\n\t# Downloadto current directory，Useoriginalfilename\n\tresult = download_file(\"cloud://xxx.png\")\n\n\t# Downloadto specified directory\n\tresult = download_file(\"cloud://xxx.png\", \"./downloads/\")\n\n\t# Downloadand rename\n\tresult = download_file(\"cloud://xxx.png\", \"./my-image.png\")\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef delete_file(cloud_object_ids):\n\t\"\"\"DeleteCloud Storagefile\"\"\"\n\t# IfpassedYessingle string，convert toList\n\tif isinstance(cloud_object_ids, str):\n\t\tcloud_object_ids = [cloud_object_ids]\n\n\tdata = [{\"cloudObjectId\": obj_id} for obj_id in cloud_object_ids]\n\tresult = cloudbase.request(\"POST\", \"/v1/storages/delete-objects\", json=data)\n\n\tif result:\n\t\tprint(\"Delete successful!\")\n\t\treturn True\n\treturn False\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = delete_file(\"cloud://xxx.png\")\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```python\nimport requests\nimport json\nfrom cloudbase_client import cloudbase\n\ndef stream_text(model, sub_model, messages):\n\t\"\"\"streamingtextthisGenerate\"\"\"\n\tpayload = {\n\t\t\"model\": sub_model,\n\t\t\"messages\": messages,\n\t\t\"stream\": True\n\t}\n\n\turl = f\"{cloudbase.base_url}/v1/ai/{model}/chat/completions\"\n\theaders = cloudbase.headers.copy()\n\theaders[\"Accept\"] = \"text/event-stream\"\n\n\ttry:\n\t\tresponse = requests.post(url, headers=headers, json=payload, stream=True)\n\t\tresponse.raise_for_status()\n\n\t\tprint(\"AI Streaming response:\")\n\t\tfull_content = \"\"\n\n\t\tfor line in response.iter_lines():\n\t\t\tif line:\n\t\t\t\tline_str = line.decode(\"utf-8\")\n\t\t\t\tif line_str.startswith(\"data: \"):\n\t\t\t\t\tdata_str = line_str[6:]\n\t\t\t\t\tif data_str.strip() != \"[DONE]\":\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tchunk_data = json.loads(data_str)\n\t\t\t\t\t\t\tcontent = chunk_data.get(\"choices\", [{}])[0].get(\"delta\", {}).get(\"content\", \"\")\n\t\t\t\t\t\t\tif content:\n\t\t\t\t\t\t\t\tprint(content, end=\"\", flush=True)\n\t\t\t\t\t\t\t\tfull_content += content\n\t\t\t\t\t\texcept json.JSONDecodeError:\n\t\t\t\t\t\t\tcontinue\n\n\t\tprint()  # newline\n\t\treturn full_content\n\texcept Exception as e:\n\t\tprint(f\"AI Call failed: {e}\")\n\t\treturn None\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresponse = stream_text(\n\t\t\"{%AI_MODEL_NAME%}\",\n\t\t\"{%AI_SUB_MODEL_NAME%}\",\n\t\t[\n\t\t\t{\"role\": \"system\", \"content\": \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\"},\n\t\t\t{\"role\": \"user\", \"content\": \"Spring\"}\n\t\t]\n\t)\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```python\nimport requests\nfrom cloudbase_client import cloudbase\n\ndef generate_image(prompt):\n\t\"\"\"Call image generation cloud function\"\"\"\n\turl = f\"{cloudbase.base_url}/v1/functions/<YOUR_FUNCTION_NAME>/invoke\"\n\theaders = cloudbase.headers\n\tpayload = {\n\t\t\"prompt\": prompt\n\t}\n\n\ttry:\n\t\tresponse = requests.post(url, headers=headers, json=payload)\n\t\tresponse.raise_for_status()\n\t\tresult = response.json()\n\n\t\tif result.get(\"success\"):\n\t\t\t# Generation successful\n\t\t\tprint(\"Generation successful!\")\n\t\t\tprint(f\"Image URL: {result.get('imageUrl')}\")\n\t\t\tprint(f\"Optimized prompt: {result.get('revised_prompt')}\")\n\n\t\t\t# Use image\n\t\t\t# Note: Image URL is valid for 24 hours, please save or transfer promptly\n\t\t\treturn result\n\t\telse:\n\t\t\t# Generation failed\n\t\t\tprint(f\"Generation failed: {result.get('code')} {result.get('message')}\")\n\t\t\treturn None\n\texcept Exception as e:\n\t\tprint(f\"Call failed: {e}\")\n\t\treturn None\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = generate_image(\"A cute cat playing in the sunshine\")\n\tif result:\n\t\tprint(f\"Image URL: {result.get('imageUrl')}\")\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```python\n\"\"\"\nPython Call Agent Example (AG-UI Protocol)\nProtocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n\"\"\"\nimport requests\nimport json\nimport uuid\nfrom cloudbase_client import cloudbase\n\ndef chat_with_agent_stream(bot_id, msg, history=None):\n    \"\"\"\n    streamingCallAgent（AG-UI Protocol)\n    \n    AG-UI protocolparameterdescription：\n    - messages: Required，MessageList，contains id/role/content\n    - threadId: Optional，Session ID，for multi-turn conversation management\n    - runId: Optional，RunID，for tracking a singleexecute\n    - tools: Optional，Frontend tool definitions\n    - context: Optional，contextInfo\n    - forwardedProps: Optional，pass-throughparameter\n    \"\"\"\n    if history is None:\n        history = []\n\n    url = f\"{cloudbase.base_url}/v1/aibot/bots/{bot_id}/send-message\"\n\n    # Build message list (AG-UI protocol format)\n    messages = []\n    \n    # AddHistoryMessage\n    for h in history:\n        messages.append({\n            \"id\": h.get(\"id\", f\"msg-{uuid.uuid4()}\"),\n            \"role\": h.get(\"role\", \"user\"),\n            \"content\": h.get(\"content\", \"\")\n        })\n    \n    # AddCurrentuserMessage\n    messages.append({\n        \"id\": f\"msg-{uuid.uuid4()}\",\n        \"role\": \"user\",\n        \"content\": msg\n    })\n\n    # AG-UI protocolRequestbody\n    payload = {\n        \"messages\": messages,                      # Required: Message list\n        \"threadId\": f\"thread-{uuid.uuid4()}\",     # Optional：Session ID\n        \"runId\": f\"run-{uuid.uuid4()}\",           # Optional：RunID\n        \"tools\": [],                               # Optional: Frontend tool definitions\n        \"context\": [],                             # Optional: Context information\n        \"forwardedProps\": {}                       # Optional: Pass-through parameters\n    }\n\n    headers = cloudbase.headers.copy()\n    headers[\"Accept\"] = \"text/event-stream\"\n\n    try:\n        response = requests.post(\n            url,\n            headers=headers,\n            json=payload,\n            stream=True,\n            timeout=30\n        )\n        response.raise_for_status()\n\n        print(\"AI Streaming response:\")\n        full_content = \"\"\n        buffer = \"\"\n\n        for chunk in response.iter_content(chunk_size=None, decode_unicode=False):\n            if chunk:\n                try:\n                    # Decodebyte stream\n                    buffer += chunk.decode('utf-8')\n\n                    # Processcomplete line\n                    while '\\n' in buffer:\n                        line, buffer = buffer.split('\\n', 1)\n                        line = line.strip()\n\n                        if line.startswith(\"data: \"):\n                            data_str = line[6:].strip()\n                            if data_str and data_str != \"[DONE]\":\n                                try:\n                                    chunk_data = json.loads(data_str)\n                                    # support multipleResponseformat\n                                    content = (\n                                        chunk_data.get(\"content\") or\n                                        chunk_data.get(\"choices\", [{}])[0].get(\"delta\", {}).get(\"content\", \"\") or\n                                        chunk_data.get(\"choices\", [{}])[0].get(\"message\", {}).get(\"content\", \"\")\n                                    )\n                                    if content:\n                                        print(content, end=\"\", flush=True)\n                                        full_content += content\n                                except json.JSONDecodeError:\n                                    pass\n                except UnicodeDecodeError:\n                    continue\n\n        print()  # newline\n        return full_content\n\n    except requests.exceptions.Timeout:\n        print(\"RequestTimeout，pleaseChecknetworkConnectorincreaseTimeoutwhentime\")\n        return None\n    except requests.exceptions.RequestException as e:\n        print(f\"AI Call failed: {e}\")\n        if hasattr(e.response, 'text'):\n            print(f\"ResponseContent: {e.response.text}\")\n        return None\n\n# Usage Example\nif __name__ == \"__main__\":\n    response = chat_with_agent_stream(\"{%AGENT_ID%}\", \"Who are you\")\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```python\nimport requests\nimport json\nfrom cloudbase_client import cloudbase\n\ndef chat_with_agent_stream(bot_id, msg, history=None):\n\t\"\"\"streamingCallAgent\"\"\"\n\tif history is None:\n\t\thistory = []\n\n\turl = f\"{cloudbase.base_url}/v1/aibot/bots/{bot_id}/send-message\"\n\n\tpayload = {\n\t\t\"history\": history,\n\t\t\"msg\": msg\n\t}\n\n\theaders = cloudbase.headers.copy()\n\theaders[\"Accept\"] = \"text/event-stream\"\n\n\ttry:\n\t\tresponse = requests.post(\n\t\t\turl,\n\t\t\theaders=headers,\n\t\t\tjson=payload,\n\t\t\tstream=True,\n\t\t\ttimeout=30\n\t\t)\n\t\tresponse.raise_for_status()\n\n\t\tprint(\"AI Streaming response:\")\n\t\tfull_content = \"\"\n\t\tbuffer = \"\"\n\n\t\tfor chunk in response.iter_content(chunk_size=None, decode_unicode=False):\n\t\t\tif chunk:\n\t\t\t\ttry:\n\t\t\t\t\t# Decodebyte stream\n\t\t\t\t\tbuffer += chunk.decode('utf-8')\n\n\t\t\t\t\t# Processcomplete line\n\t\t\t\t\twhile '\\n' in buffer:\n\t\t\t\t\t\tline, buffer = buffer.split('\\n', 1)\n\t\t\t\t\t\tline = line.strip()\n\n\t\t\t\t\t\tif line.startswith(\"data: \"):\n\t\t\t\t\t\t\tdata_str = line[6:].strip()\n\t\t\t\t\t\t\tif data_str and data_str != \"[DONE]\":\n\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\tchunk_data = json.loads(data_str)\n\t\t\t\t\t\t\t\t\t# support multipleResponseformat\n\t\t\t\t\t\t\t\t\tcontent = (\n\t\t\t\t\t\t\t\t\t\tchunk_data.get(\"content\") or\n\t\t\t\t\t\t\t\t\t\tchunk_data.get(\"choices\", [{}])[0].get(\"delta\", {}).get(\"content\", \"\") or\n\t\t\t\t\t\t\t\t\t\tchunk_data.get(\"choices\", [{}])[0].get(\"message\", {}).get(\"content\", \"\")\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tif content:\n\t\t\t\t\t\t\t\t\t\tprint(content, end=\"\", flush=True)\n\t\t\t\t\t\t\t\t\t\tfull_content += content\n\t\t\t\t\t\t\t\texcept json.JSONDecodeError:\n\t\t\t\t\t\t\t\t\tpass\n\t\t\t\texcept UnicodeDecodeError:\n\t\t\t\t\tcontinue\n\n\t\tprint()  # newline\n\t\treturn full_content\n\n\texcept requests.exceptions.Timeout:\n\t\tprint(\"RequestTimeout，pleaseChecknetworkConnectorincreaseTimeoutwhentime\")\n\t\treturn None\n\texcept requests.exceptions.RequestException as e:\n\t\tprint(f\"AI Call failed: {e}\")\n\t\tif hasattr(e.response, 'text'):\n\t\t\tprint(f\"ResponseContent: {e.response.text}\")\n\t\treturn None\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresponse = chat_with_agent_stream(\"{%AGENT_ID%}\", \"Who are you\")\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef sign_in(username, password):\n\t\"\"\"Username Password Login\"\"\"\n\tresult = cloudbase.request(\"POST\", \"/auth/v1/signin\",\n\t\tjson={\"username\": username, \"password\": password})\n\n\tif result:\n\t\taccess_token = result.get(\"access_token\")\n\t\trefresh_token = result.get(\"refresh_token\")\n\t\tuser_id = result.get(\"sub\")\n\n\t\tprint(f\"Login successful! User ID: {user_id}\")\n\t\tprint(f\"Access token: {access_token[:20]}...\")\n\t\treturn result\n\treturn None\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = sign_in(\"your_username\", \"your_password\")\n```",
            "index": 8,
            "id": "identity",
            "title": "Authentication"
          }
        ]
      }
    ],
    "_id": "1cec055169a9286e0043719909372e76",
    "_openid": "anon",
    "createdAt": 1769744603277,
    "updatedAt": 1769766701104
  },
  {
    "category": "Framework Integration,Mobile Frameworks,Flutter",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 30,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/http-api/basic/overview",
    "content": [
      {
        "markdown": "Use **HTTP Request** in **Flutter** Callvarious CloudBase capabilities\n\nin `pubspec.yaml` Add dependencies：\n\n```yaml\ndependencies:\n  http: ^1.1.0\n  flutter_dotenv: ^5.1.0\n```\n\nThen run：\n\n```bash\nflutter pub get\n```",
        "index": 1,
        "title": "Install Dependencies",
        "content": []
      },
      {
        "markdown": "Add the following code to your **Flutter** project",
        "index": 2,
        "title": "Initialize Configuration",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```dart\nimport 'dart:convert';\nimport 'package:http/http.dart' as http;\nimport 'package:flutter_dotenv/flutter_dotenv.dart';\n\nclass CloudBaseClient {\n  late String envId;\n  late String accessToken;\n  late String baseUrl;\n  late Map<String, String> headers;\n\n  CloudBaseClient() {\n    envId = dotenv.env['CLOUDBASE_ENV_ID'] ?? '';\n    accessToken = dotenv.env['CLOUDBASE_ACCESS_TOKEN'] ?? '';\n    baseUrl = 'https://$envId.api.tcloudbasegateway.com';\n    headers = {\n      'Content-Type': 'application/json',\n      'Accept': 'application/json',\n      'Authorization': 'Bearer $accessToken',\n    };\n  }\n\n  /// UpdateAccess token\n  ///\n  /// [newToken] new access token\n  void updateAccessToken(String newToken) {\n    accessToken = newToken;\n    headers['Authorization'] = 'Bearer $newToken';\n    print('Access token has beenUpdate');\n  }\n\n  /// Unified HTTP request method\n  ///\n  /// [method] Request method (GET, POST, PUT, PATCH, DELETE)\n  /// [path] APIPath (such as /v1/rdb/rest/table_name)\n  /// [body] Request body data\n  /// [customHeaders] Customheaders\n  ///\n  /// Returns response data ornull\n  Future<dynamic> request(\n    String method,\n    String path, {\n    dynamic body,\n    Map<String, String>? customHeaders,\n  }) async {\n    final url = Uri.parse('$baseUrl$path');\n    final requestHeaders = Map<String, String>.from(headers);\n\n    if (customHeaders != null) {\n      requestHeaders.addAll(customHeaders);\n    }\n\n    try {\n      http.Response response;\n\n      switch (method.toUpperCase()) {\n        case 'GET':\n          response = await http.get(url, headers: requestHeaders);\n          break;\n        case 'POST':\n          response = await http.post(\n            url,\n            headers: requestHeaders,\n            body: body != null ? jsonEncode(body) : null,\n          );\n          break;\n        case 'PUT':\n          response = await http.put(\n            url,\n            headers: requestHeaders,\n            body: body != null ? jsonEncode(body) : null,\n          );\n          break;\n        case 'PATCH':\n          response = await http.patch(\n            url,\n            headers: requestHeaders,\n            body: body != null ? jsonEncode(body) : null,\n          );\n          break;\n        case 'DELETE':\n          response = await http.delete(url, headers: requestHeaders);\n          break;\n        default:\n          throw Exception('Unsupported HTTP method: $method');\n      }\n\n      if (response.statusCode >= 200 && response.statusCode < 300) {\n        if (response.body.isEmpty) {\n          return true;\n        }\n        return jsonDecode(response.body);\n      } else {\n        print('Requestfailed: ${response.statusCode} ${response.body}');\n        return null;\n      }\n    } catch (e) {\n      print('Requestfailed: $e');\n      return null;\n    }\n  }\n}\n\nfinal cloudbase = CloudBaseClient();\n```",
            "index": 1,
            "title": "cloudbase_client.dart"
          },
          {
            "markdown": "> 💡Note: For user permissions, refer to the \"Authentication\" module to obtain access_token\n\n```properties\n# Environment ID\nCLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Anonymous access token\nCLOUDBASE_ACCESS_TOKEN={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": ".env"
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<void> example() async {\n  final cloudbase = CloudBaseClient();\n\n  // Query {%TABLE_NAME%} table (limit 10 records)\n  final data = await cloudbase.request(\n    \"GET\",\n    \"/v1/rdb/rest/{{%TABLE_NAME%}}?select=*&limit=10\",\n  );\n\n  if (data != null) {\n    print(\"Query result: $data\");\n  }\n}\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<void> example() async {\n  final cloudbase = CloudBaseClient();\n\n  // Insert data into {%TABLE_NAME%}\n  final data = await cloudbase.request(\n    \"POST\",\n    \"/v1/rdb/rest/{{%TABLE_NAME%}}\",\n    body: '{\"title\": \"New Post\", \"status\": \"draft\"}',\n    headers: {\"Prefer\": \"return=representation\"},\n  );\n\n  if (data != null) {\n    print(\"Insert result: $data\");\n  }\n}\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<void> example() async {\n  final cloudbase = CloudBaseClient();\n\n  // Update record in {%TABLE_NAME%}\n  final data = await cloudbase.request(\n    \"PATCH\",\n    \"/v1/rdb/rest/{{%TABLE_NAME%}}?id=eq.1\",\n    body: '{\"status\": \"published\"}',\n    headers: {\"Prefer\": \"return=representation\"},\n  );\n\n  if (data != null) {\n    print(\"Update result: $data\");\n  }\n}\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<void> example() async {\n  final cloudbase = CloudBaseClient();\n\n  // Update record in {%TABLE_NAME%}\n  final data = await cloudbase.request(\n    \"POST\",\n    \"/v1/rdb/rest/{{%TABLE_NAME%}}\",\n    body: '{\"id\": 1, \"title\": \"Post Title\", \"status\": \"published\"}',\n    headers: {\"Prefer\": \"resolution=merge-duplicates,return=representation\"},\n  );\n\n  if (data != null) {\n    print(\"Upsert result: $data\");\n  }\n}\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<void> example() async {\n  final cloudbase = CloudBaseClient();\n\n  // Delete record from {%TABLE_NAME%}\n  final data = await cloudbase.request(\n    \"DELETE\",\n    \"/v1/rdb/rest/{{%TABLE_NAME%}}?id=eq.1\",\n  );\n\n  if (data != null) {\n    print(\"Delete completed: $data\");\n  }\n}\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<List<dynamic>> getMysqlData(String tableName) async {\n  /// Query MySQL database data\n  final data = await cloudbase.request('GET', '/v1/rdb/rest/$tableName?limit=10');\n\n  if (data != null) {\n    print('Querysuccessful: $data');\n    return data as List<dynamic>;\n  }\n  return [];\n}\n\n// Usage Example\nvoid main() async {\n  final result = await getMysqlData('{%TABLE_NAME%}');\n  print(result);\n}\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<dynamic> addMysqlData(String tableName, Map<String, dynamic> data) async {\n  /// Add MySQL database data\n  final result = await cloudbase.request('POST', '/v1/rdb/rest/$tableName', body: data);\n\n  if (result != null) {\n    print('Insert successful: $result');\n  }\n  return result;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await addMysqlData('{%TABLE_NAME%}', {'title': 'Example Title'});\n  print(result);\n}\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<dynamic> updateMysqlData(String tableName, String dataId, Map<String, dynamic> data) async {\n  /// Update MySQL database data\n  final result = await cloudbase.request(\n    'PATCH',\n    '/v1/rdb/rest/$tableName?id=eq.$dataId',\n    body: data,\n  );\n\n  if (result != null) {\n    print('Update successful: $result');\n  }\n  return result;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await updateMysqlData('{%TABLE_NAME%}', '<data id>', {'title': 'New Title'});\n  print(result);\n}\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<bool> deleteMysqlData(String tableName, String dataId) async {\n  /// Delete MySQL database data\n  final result = await cloudbase.request('DELETE', '/v1/rdb/rest/$tableName?id=eq.$dataId');\n\n  if (result != null) {\n    print('Delete successful');\n    return true;\n  }\n  return false;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await deleteMysqlData('{%TABLE_NAME%}', '<data id>');\n  print(result);\n}\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<List<dynamic>> getModelData(String modelName, {String envType = 'prod'}) async {\n  /// QueryData ModelData\n  final payload = {\n    'pageSize': 10,\n    'pageNumber': 1,\n    'getCount': true,\n  };\n\n  final result = await cloudbase.request('POST', '/v1/model/$envType/$modelName/list', body: payload);\n\n  if (result != null) {\n    final records = result['data']?['records'] ?? [];\n    print('Querysuccessful: $records');\n    return records;\n  }\n  return [];\n}\n\n// Usage Example\nvoid main() async {\n  final records = await getModelData('{%TABLE_NAME%}');\n  print(records);\n}\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<dynamic> addModelData(String modelName, Map<String, dynamic> data, {String envType = 'prod'}) async {\n  /// AddData ModelData\n  final result = await cloudbase.request(\n    'POST',\n    '/v1/model/$envType/$modelName/create',\n    body: {'data': data},\n  );\n\n  if (result != null) {\n    final docId = result['data']?['id'];\n    print('Insert successful! id: $docId');\n  }\n  return result;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await addModelData('{%TABLE_NAME%}', {'title': 'Example Title'});\n  print(result);\n}\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<bool> updateModelData(String modelName, String dataId, Map<String, dynamic> data, {String envType = 'prod'}) async {\n  /// UpdateData ModelData\n  final payload = {\n    'data': data,\n    'filter': {\n      'where': {\n        '_id': {'\\$eq': dataId}\n      }\n    }\n  };\n\n  final result = await cloudbase.request('PUT', '/v1/model/$envType/$modelName/update', body: payload);\n\n  if (result != null) {\n    print('Update successful!');\n    return true;\n  }\n  return false;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await updateModelData('{%TABLE_NAME%}', '<data id>', {'title': 'New Title'});\n  print(result);\n}\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<bool> deleteModelData(String modelName, String dataId, {String envType = 'prod'}) async {\n  /// DeleteData ModelData\n  final payload = {\n    'filter': {\n      'where': {\n        '_id': {'\\$eq': dataId}\n      }\n    }\n  };\n\n  final result = await cloudbase.request('POST', '/v1/model/$envType/$modelName/delete', body: payload);\n\n  if (result != null) {\n    print('Delete successful!');\n    return true;\n  }\n  return false;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await deleteModelData('{%TABLE_NAME%}', '<data id>');\n  print(result);\n}\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<dynamic> callFunction(String functionName, {Map<String, dynamic>? data}) async {\n  /// CallCloud Function\n  final result = await cloudbase.request('POST', '/v1/functions/$functionName', body: data ?? {});\n\n  if (result != null) {\n    print('Cloud function call result: $result');\n  }\n  return result;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await callFunction('{%FUNCTION_NAME%}');\n  print(result);\n}\n```",
            "index": 3,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<dynamic> callContainer(String serviceName, {String path = '', String method = 'GET', Map<String, dynamic>? data}) async {\n  /// CallCloud Runservice\n  final fullPath = '/v1/cloudrun/$serviceName/$path'.replaceAll(RegExp(r'/+$'), '');\n  final result = await cloudbase.request(method.toUpperCase(), fullPath, body: data);\n\n  if (result != null) {\n    print('Cloud RunCallResult: $result');\n  }\n  return result;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await callContainer('{%SERVICE_NAME%}');\n  print(result);\n}\n```",
            "index": 4,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```dart\nimport 'dart:io';\nimport 'package:http/http.dart' as http;\nimport 'cloudbase_client.dart';\n\nFuture<Map<String, dynamic>?> uploadFile(String filePath, {String? objectId}) async {\n  /// Upload FiletoCloud Storage\n  final file = File(filePath);\n\n  if (!await file.exists()) {\n    print('filedoes not exist: $filePath');\n    return null;\n  }\n\n  if (objectId == null) {\n    final filename = filePath.split('/').last;\n    final timestamp = DateTime.now().millisecondsSinceEpoch;\n    objectId = 'uploads/$timestamp-$filename';\n  }\n\n  // 1. Get upload info\n  final uploadInfo = await cloudbase.request(\n    'POST',\n    '/v1/storages/get-objects-upload-info',\n    body: [{'objectId': objectId}],\n  );\n\n  if (uploadInfo == null || uploadInfo.isEmpty) {\n    return null;\n  }\n\n  final info = uploadInfo[0];\n  final uploadUrl = info['uploadUrl'];\n\n  try {\n    // 2. Upload File\n    final fileData = await file.readAsBytes();\n    final uploadHeaders = {\n      'Authorization': info['authorization'],\n      'X-Cos-Security-Token': info['token'],\n      'X-Cos-Meta-Fileid': info['cloudObjectMeta'],\n    };\n\n    final uploadResponse = await http.put(\n      Uri.parse(uploadUrl),\n      headers: uploadHeaders,\n      body: fileData,\n    );\n\n    if (uploadResponse.statusCode >= 200 && uploadResponse.statusCode < 300) {\n      final result = {\n        'cloudObjectId': info['cloudObjectId'],\n        'downloadUrl': info['downloadUrl'],\n        'objectId': objectId,\n      };\n\n      print('fileUpload successful:');\n      print('- Object ID: ${result['objectId']}');\n      print('- DownloadURL: ${result['downloadUrl']}');\n\n      return result;\n    }\n\n    print('fileUploadfailed: ${uploadResponse.statusCode}');\n    return null;\n  } catch (e) {\n    print('fileUploadfailed: $e');\n    return null;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final result = await uploadFile('./example.jpg');\n  print(result);\n}\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<String?> getFileUrl(String cloudObjectId) async {\n  /// GetCloud Storagefiletemporary accessURL\n  final result = await cloudbase.request(\n    'POST',\n    '/v1/storages/get-objects-download-info',\n    body: [{'cloudObjectId': cloudObjectId}],\n  );\n\n  if (result != null && result.isNotEmpty) {\n    final downloadUrl = result[0]['downloadUrl'];\n    print('fileURL: $downloadUrl');\n    return downloadUrl;\n  }\n  return null;\n}\n\n// Usage Example\nvoid main() async {\n  final fileUrl = await getFileUrl('cloud://xxx.png');\n  print(fileUrl);\n}\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'dart:io';\nimport 'package:http/http.dart' as http;\nimport 'cloudbase_client.dart';\n\nFuture<bool> downloadFile(String cloudObjectId, {String savePath = './'}) async {\n  /// DownloadCloud Storagefiletolocal\n  // 1. GetDownloadURL\n  final result = await cloudbase.request(\n    'POST',\n    '/v1/storages/get-objects-download-info',\n    body: [{'cloudObjectId': cloudObjectId}],\n  );\n\n  if (result == null || result.isEmpty) {\n    return false;\n  }\n\n  final downloadUrl = result[0]['downloadUrl'];\n\n  try {\n    // 2. fromURLExtractfilename\n    final uri = Uri.parse(downloadUrl);\n    final filename = uri.pathSegments.last.split('?').first;\n\n    // 3. Determine full path\n    String fullPath;\n    final saveDir = Directory(savePath);\n    if (await saveDir.exists() || savePath.endsWith('/')) {\n      fullPath = '$savePath/$filename';\n    } else {\n      fullPath = savePath;\n    }\n\n    // 4. Download File\n    final fileResponse = await http.get(Uri.parse(downloadUrl));\n\n    if (fileResponse.statusCode >= 200 && fileResponse.statusCode < 300) {\n      // 5. Save to local\n      final file = File(fullPath);\n      await file.writeAsBytes(fileResponse.bodyBytes);\n\n      print('Downloadsuccessful! filesaved to: $fullPath');\n      return true;\n    }\n\n    print('Downloadfailed: ${fileResponse.statusCode}');\n    return false;\n  } catch (e) {\n    print('Downloadfailed: $e');\n    return false;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  // Downloadto current directory，Useoriginalfilename\n  await downloadFile('cloud://xxx.png');\n\n  // Downloadto specified directory\n  await downloadFile('cloud://xxx.png', savePath: './downloads/');\n\n  // Downloadand rename\n  await downloadFile('cloud://xxx.png', savePath: './my-image.png');\n}\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<bool> deleteFile(dynamic cloudObjectIds) async {\n  /// DeleteCloud Storagefile\n  List<String> ids;\n  if (cloudObjectIds is String) {\n    ids = [cloudObjectIds];\n  } else if (cloudObjectIds is List<String>) {\n    ids = cloudObjectIds;\n  } else {\n    print('Parameter type error');\n    return false;\n  }\n\n  final data = ids.map((id) => {'cloudObjectId': id}).toList();\n  final result = await cloudbase.request('POST', '/v1/storages/delete-objects', body: data);\n\n  if (result != null) {\n    print('Delete successful!');\n    return true;\n  }\n  return false;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await deleteFile('cloud://xxx.png');\n  print(result);\n}\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```dart\nimport 'dart:convert';\nimport 'package:http/http.dart' as http;\nimport 'cloudbase_client.dart';\n\nFuture<String?> streamText(String model, String subModel, List<Map<String, String>> messages) async {\n  /// streamingtextthisGenerate\n  final payload = {\n    'model': subModel,\n    'messages': messages,\n    'stream': true,\n  };\n\n  final url = '${cloudbase.baseUrl}/v1/ai/$model/chat/completions';\n  final headers = Map<String, String>.from(cloudbase.headers);\n  headers['Accept'] = 'text/event-stream';\n\n  try {\n    final request = http.Request('POST', Uri.parse(url));\n    request.headers.addAll(headers);\n    request.body = jsonEncode(payload);\n\n    final streamedResponse = await request.send();\n\n    if (streamedResponse.statusCode >= 200 && streamedResponse.statusCode < 300) {\n      print('AI Streaming response:');\n      String fullContent = '';\n\n      await for (var chunk in streamedResponse.stream.transform(utf8.decoder)) {\n        final lines = chunk.split('\\n');\n        for (var line in lines) {\n          if (line.startsWith('data: ')) {\n            final dataStr = line.substring(6);\n            if (dataStr.trim() != '[DONE]') {\n              try {\n                final chunkData = jsonDecode(dataStr);\n                final content = chunkData['choices']?[0]?['delta']?['content'] ?? '';\n                if (content.isNotEmpty) {\n                  print(content);\n                  fullContent += content;\n                }\n              } catch (e) {\n                // Ignore JSON parsing error\n              }\n            }\n          }\n        }\n      }\n\n      return fullContent;\n    } else {\n      print('AI Call failed: ${streamedResponse.statusCode}');\n      return null;\n    }\n  } catch (e) {\n    print('AI Call failed: $e');\n    return null;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final response = await streamText(\n    '{%AI_MODEL_NAME%}',\n    '{%AI_SUB_MODEL_NAME%}',\n    [\n      {'role': 'system', 'content': 'Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create'},\n      {'role': 'user', 'content': 'Spring'}\n    ],\n  );\n  print('\\nComplete response: $response');\n}\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```dart\nimport 'cloudbase_client.dart';\n\nFuture<Map<String, dynamic>?> generateImage(String prompt) async {\n  /// Call image generation cloud function\n  final result = await cloudbase.request(\n    'POST',\n    '/v1/functions/<YOUR_FUNCTION_NAME>/invoke',\n    body: {\n      'prompt': prompt,\n    },\n  );\n\n  if (result != null) {\n    final success = result['success'] ?? false;\n    \n    if (success) {\n      // Generation successful\n      print('Generation successful!');\n      print('Image URL: ${result['imageUrl']}');\n      print('Optimized prompt: ${result['revised_prompt']}');\n\n      // Use image\n      // Note: Image URL is valid for 24 hours, please save or transfer promptly\n      return result;\n    } else {\n      // Generation failed\n      print('Generation failed: ${result['code']} ${result['message']}');\n      return null;\n    }\n  }\n  return null;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await generateImage('A cute cat playing in the sunshine');\n  if (result != null) {\n    print('Image URL: ${result['imageUrl']}');\n  }\n}\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```dart\n/**\n * Flutter Call Agent Example (AG-UI Protocol)\n * Protocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n */\nimport 'dart:convert';\nimport 'package:http/http.dart' as http;\nimport 'cloudbase_client.dart';\n\nFuture<String?> chatWithAgentStream(String botId, String userMessage) async {\n  // Build message list (AG-UI protocol format)\n  final messages = [\n    {\n      'id': 'msg_001',\n      'role': 'user',\n      'content': userMessage,\n    }\n  ];\n\n  // AG-UI Protocol request parameters\n  final payload = {\n    'messages': messages,                                    // Required: Message list\n    'threadId': '550e8400-e29b-41d4-a716-446655440000',      // Optional: Session ID for multi-turn conversation\n    'runId': 'run_001',                                       // Optional: Run ID for execution tracking\n    'tools': [],                                              // Optional: Frontend tool definitions\n    'context': [],                                            // Optional: Context information\n    'forwardedProps': {},                                     // Optional: Pass-through parameters\n  };\n\n  final url = '${cloudbase.baseUrl}/v1/aibot/bots/$botId/send-message';\n  final headers = Map<String, String>.from(cloudbase.headers);\n  headers['Accept'] = 'text/event-stream';\n\n  try {\n    final request = http.Request('POST', Uri.parse(url));\n    request.headers.addAll(headers);\n    request.body = jsonEncode(payload);\n\n    final streamedResponse = await request.send();\n\n    if (streamedResponse.statusCode >= 200 && streamedResponse.statusCode < 300) {\n      print('AI Streaming response:');\n      String fullContent = '';\n      String buffer = '';\n\n      await for (var chunk in streamedResponse.stream.transform(utf8.decoder)) {\n        buffer += chunk;\n\n        while (buffer.contains('\\n')) {\n          final newlineIndex = buffer.indexOf('\\n');\n          final line = buffer.substring(0, newlineIndex).trim();\n          buffer = buffer.substring(newlineIndex + 1);\n\n          if (line.startsWith('data: ')) {\n            final dataStr = line.substring(6).trim();\n            if (dataStr.isNotEmpty && dataStr != '[DONE]') {\n              try {\n                final chunkData = jsonDecode(dataStr);\n                final content = chunkData['content'] ??\n                    chunkData['choices']?[0]?['delta']?['content'] ??\n                    chunkData['choices']?[0]?['message']?['content'] ??\n                    '';\n                if (content.isNotEmpty) {\n                  print(content);\n                  fullContent += content;\n                }\n              } catch (e) {\n                // Ignore JSON parsing error\n              }\n            }\n          }\n        }\n      }\n\n      print('');\n      return fullContent;\n    } else {\n      print('AI Call failed: ${streamedResponse.statusCode}');\n      return null;\n    }\n  } catch (e) {\n    print('AI Call failed: $e');\n    return null;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final response = await chatWithAgentStream('{%AGENT_ID%}', 'Who are you');\n  print('\\nComplete response: $response');\n}\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```dart\nimport 'dart:convert';\nimport 'package:http/http.dart' as http;\nimport 'cloudbase_client.dart';\n\nFuture<String?> chatWithAgentStream(String botId, String msg, {List<Map<String, String>>? history}) async {\n  /// streamingCallAgent\n  final payload = {\n    'history': history ?? [],\n    'msg': msg,\n  };\n\n  final url = '${cloudbase.baseUrl}/v1/aibot/bots/$botId/send-message';\n  final headers = Map<String, String>.from(cloudbase.headers);\n  headers['Accept'] = 'text/event-stream';\n\n  try {\n    final request = http.Request('POST', Uri.parse(url));\n    request.headers.addAll(headers);\n    request.body = jsonEncode(payload);\n\n    final streamedResponse = await request.send();\n\n    if (streamedResponse.statusCode >= 200 && streamedResponse.statusCode < 300) {\n      print('AI Streaming response:');\n      String fullContent = '';\n      String buffer = '';\n\n      await for (var chunk in streamedResponse.stream.transform(utf8.decoder)) {\n        buffer += chunk;\n\n        while (buffer.contains('\\n')) {\n          final newlineIndex = buffer.indexOf('\\n');\n          final line = buffer.substring(0, newlineIndex).trim();\n          buffer = buffer.substring(newlineIndex + 1);\n\n          if (line.startsWith('data: ')) {\n            final dataStr = line.substring(6).trim();\n            if (dataStr.isNotEmpty && dataStr != '[DONE]') {\n              try {\n                final chunkData = jsonDecode(dataStr);\n                final content = chunkData['content'] ??\n                    chunkData['choices']?[0]?['delta']?['content'] ??\n                    chunkData['choices']?[0]?['message']?['content'] ??\n                    '';\n                if (content.isNotEmpty) {\n                  print(content);\n                  fullContent += content;\n                }\n              } catch (e) {\n                // Ignore JSON parsing error\n              }\n            }\n          }\n        }\n      }\n\n      print('');\n      return fullContent;\n    } else {\n      print('AI Call failed: ${streamedResponse.statusCode}');\n      return null;\n    }\n  } catch (e) {\n    print('AI Call failed: $e');\n    return null;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final response = await chatWithAgentStream('{%AGENT_ID%}', 'Who are you');\n  print('\\nComplete response: $response');\n}\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 8,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<Map<String, dynamic>?> signUpWithPhoneCode(String phoneNumber, String verificationCode, {String? username, String? password, String? captchaToken}) async {\n  try {\n    // Step1: SendSMSVerification code\n    final sendBody = {\n      'phone_number': phoneNumber.startsWith('+86') ? phoneNumber : '+86$phoneNumber',\n      'target': 'NON_USER',  // \"NON_USER\" - Accountdoes not existthenSend; \"ANY\" - No restriction\n    };\n\n    final sendHeaders = captchaToken != null ? {'x-captcha-token': captchaToken} : null;\n\n    final sendResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification',\n      body: sendBody,\n      customHeaders: sendHeaders,\n    );\n\n    if (sendResult == null) {\n      print('Send Codefailed');\n      return null;\n    }\n\n    final verificationId = sendResult['verification_id'];\n    print('Verification codeSendsuccessful! ID: $verificationId');\n\n    // Step2: Verify the code\n    final verifyResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification/verify',\n      body: {\n        'verification_id': verificationId,\n        'verification_code': verificationCode,\n      },\n    );\n\n    if (verifyResult == null) {\n      print('Verification codeError');\n      return null;\n    }\n\n    final verificationToken = verifyResult['verification_token'];\n    print('Verifysuccessful!');\n\n    // Step3: UseVerifytokenRegister\n    final signUpBody = {\n      'phone_number': phoneNumber.startsWith('+86') ? phoneNumber : '+86$phoneNumber',\n      'verification_token': verificationToken,\n    };\n\n    // Optional：AddUsernameandPassword\n    if (username != null) signUpBody['username'] = username;\n    if (password != null) signUpBody['password'] = password;\n\n    final signUpResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/signup',\n      body: signUpBody,\n    );\n\n    if (signUpResult != null) {\n      final accessToken = signUpResult['access_token'];\n      final userId = signUpResult['sub'];\n\n      print('Registration successful! User ID: $userId');\n      print('Access token: ${accessToken.substring(0, 20)}...');\n\n      // UpdateAccess token\n      cloudbase.updateAccessToken(accessToken);\n      return signUpResult;\n    }\n\n    print('Registration failed');\n    return null;\n  } catch (e) {\n    print('Registration failed: $e');\n    return null;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final result = await signUpWithPhoneCode('13800138000', '123456', username: 'myusername', password: 'mypassword');\n  if (result != null) {\n    print('Phone numberRegistration successful');\n  }\n}\n```",
                "index": 1,
                "title": "SMS Code Registration",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<Map<String, dynamic>?> signUpWithEmailCode(String email, String verificationCode, {String? username, String? password, String? captchaToken}) async {\n  try {\n    // Step1: SendEmailVerification code\n    final sendBody = {\n      'email': email,\n      'target': 'NON_USER',  // \"NON_USER\" - Accountdoes not existthenSend; \"ANY\" - No restriction\n    };\n\n    final sendHeaders = captchaToken != null ? {'x-captcha-token': captchaToken} : null;\n\n    final sendResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification',\n      body: sendBody,\n      customHeaders: sendHeaders,\n    );\n\n    if (sendResult == null) {\n      print('Send Codefailed');\n      return null;\n    }\n\n    final verificationId = sendResult['verification_id'];\n    print('Verification codeSendsuccessful! ID: $verificationId');\n\n    // Step2: Verify the code\n    final verifyResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification/verify',\n      body: {\n        'verification_id': verificationId,\n        'verification_code': verificationCode,\n      },\n    );\n\n    if (verifyResult == null) {\n      print('Verification codeError');\n      return null;\n    }\n\n    final verificationToken = verifyResult['verification_token'];\n    print('Verifysuccessful!');\n\n    // Step3: UseVerifytokenRegister\n    final signUpBody = {\n      'email': email,\n      'verification_token': verificationToken,\n    };\n\n    // Optional：AddUsernameandPassword\n    if (username != null) signUpBody['username'] = username;\n    if (password != null) signUpBody['password'] = password;\n\n    final signUpResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/signup',\n      body: signUpBody,\n    );\n\n    if (signUpResult != null) {\n      final accessToken = signUpResult['access_token'];\n      final userId = signUpResult['sub'];\n\n      print('Registration successful! User ID: $userId');\n      print('Access token: ${accessToken.substring(0, 20)}...');\n\n      // UpdateAccess token\n      cloudbase.updateAccessToken(accessToken);\n      return signUpResult;\n    }\n\n    print('Registration failed');\n    return null;\n  } catch (e) {\n    print('Registration failed: $e');\n    return null;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final result = await signUpWithEmailCode('user@example.com', '123456', username: 'myusername', password: 'mypassword');\n  if (result != null) {\n    print('EmailRegistration successful');\n  }\n}\n```",
                "index": 2,
                "title": "Email Code Registration",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<Map<String, dynamic>?> signIn(String username, String password) async {\n  /// Username Password Login\n  final result = await cloudbase.request(\n    'POST',\n    '/auth/v1/signin',\n    body: {'username': username, 'password': password},\n  );\n\n  if (result != null) {\n    final accessToken = result['access_token'];\n    final refreshToken = result['refresh_token'];\n    final userId = result['sub'];\n\n    print('Login successful! User ID: $userId');\n    print('Access token: ${accessToken.substring(0, 20)}...');\n\n    // UpdateAccess token\n    cloudbase.updateAccessToken(accessToken);\n    return result;\n  }\n  return null;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await signIn('your_username', 'your_password');\n  print(result);\n}\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<bool> loginWithPhoneCode(String phoneNumber, String verificationCode, {String? captchaToken}) async {\n  try {\n    // Step1: SendSMSVerification code\n    final sendBody = {\n      'phone_number': phoneNumber.startsWith('+86') ? phoneNumber : '+86$phoneNumber',\n      'target': 'ANY',  // \"ANY\" - No restriction，Noneregardless of userYesNoexistsallSend; \"USER\" - AccountmustexiststhenSend\n    };\n\n    final sendHeaders = captchaToken != null ? {'x-captcha-token': captchaToken} : null;\n\n    final sendResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification',\n      body: sendBody,\n      customHeaders: sendHeaders,\n    );\n\n    if (sendResult == null) {\n      print('Send Codefailed');\n      return false;\n    }\n\n    final verificationId = sendResult['verification_id'];\n    print('Verification codeSendsuccessful! ID: $verificationId');\n\n    // Step2: Verify the code\n    final verifyResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification/verify',\n      body: {\n        'verification_id': verificationId,\n        'verification_code': verificationCode,\n      },\n    );\n\n    if (verifyResult == null) {\n      print('Verification codeError');\n      return false;\n    }\n\n    final verificationToken = verifyResult['verification_token'];\n    print('Verifysuccessful!');\n\n    // Step3: UseVerifytokenLogin\n    final loginResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/signin',\n      body: {\n        'phone_number': phoneNumber.startsWith('+86') ? phoneNumber : '+86$phoneNumber',\n        'verification_token': verificationToken,\n      },\n    );\n\n    if (loginResult != null) {\n      final accessToken = loginResult['access_token'];\n      print('Login successful!');\n      cloudbase.updateAccessToken(accessToken);\n      return true;\n    }\n\n    print('Login failed');\n    return false;\n  } catch (e) {\n    print('Login failed: $e');\n    return false;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final success = await loginWithPhoneCode('13800138000', '123456');\n  if (success) {\n    print('Phone numberLogin successful');\n  }\n}\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<bool> loginWithEmailCode(String email, String verificationCode, {String? captchaToken}) async {\n  try {\n    // Step1: SendEmailVerification code\n    final sendBody = {\n      'email': email,\n      'target': 'ANY',  // \"ANY\" - No restriction，Noneregardless of userYesNoexistsallSend; \"USER\" - AccountmustexiststhenSend\n    };\n\n    final sendHeaders = captchaToken != null ? {'x-captcha-token': captchaToken} : null;\n\n    final sendResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification',\n      body: sendBody,\n      customHeaders: sendHeaders,\n    );\n\n    if (sendResult == null) {\n      print('Send Codefailed');\n      return false;\n    }\n\n    final verificationId = sendResult['verification_id'];\n    print('Verification codeSendsuccessful! ID: $verificationId');\n\n    // Step2: Verify the code\n    final verifyResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification/verify',\n      body: {\n        'verification_id': verificationId,\n        'verification_code': verificationCode,\n      },\n    );\n\n    if (verifyResult == null) {\n      print('Verification codeError');\n      return false;\n    }\n\n    final verificationToken = verifyResult['verification_token'];\n    print('Verifysuccessful!');\n\n    // Step3: UseVerifytokenLogin\n    final loginResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/signin',\n      body: {\n        'email': email,\n        'verification_token': verificationToken,\n      },\n    );\n\n    if (loginResult != null) {\n      final accessToken = loginResult['access_token'];\n      print('Login successful!');\n      cloudbase.updateAccessToken(accessToken);\n      return true;\n    }\n\n    print('Login failed');\n    return false;\n  } catch (e) {\n    print('Login failed: $e');\n    return false;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final success = await loginWithEmailCode('user@example.com', '123456');\n  if (success) {\n    print('EmailLogin successful');\n  }\n}\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login",
                "content": []
              }
            ]
          }
        ]
      }
    ],
    "_id": "25cb905f697c28d60037e44a73b4769d",
    "_openid": "anon",
    "createdAt": 1769744598537,
    "updatedAt": 1769766696389
  },
  {
    "category": "Framework Integration,Backend Frameworks,Java",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 23,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/http-api/basic/overview",
    "content": [
      {
        "markdown": "Use **HTTP Request** in **Java** Callvarious CloudBase capabilities",
        "index": 1,
        "title": "Install Dependencies",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```xml\n<dependencies>\n    <!-- HTTP client -->\n    <dependency>\n        <groupId>com.squareup.okhttp3</groupId>\n        <artifactId>okhttp</artifactId>\n        <version>4.12.0</version>\n    </dependency>\n\n    <!-- JSON Process -->\n    <dependency>\n        <groupId>com.google.code.gson</groupId>\n        <artifactId>gson</artifactId>\n        <version>2.10.1</version>\n    </dependency>\n\n    <!-- Environment variableLoad -->\n    <dependency>\n        <groupId>io.github.cdimascio</groupId>\n        <artifactId>dotenv-java</artifactId>\n        <version>3.0.0</version>\n    </dependency>\n</dependencies>\n```",
            "index": 1,
            "title": "Maven"
          },
          {
            "markdown": "```groovy\ndependencies {\n    implementation 'com.squareup.okhttp3:okhttp:4.12.0'\n    implementation 'com.google.code.gson:gson:2.10.1'\n    implementation 'io.github.cdimascio:dotenv-java:3.0.0'\n}\n```",
            "index": 2,
            "title": "Gradle"
          }
        ]
      },
      {
        "markdown": "Add the following code to your **Java** project",
        "index": 2,
        "title": "Initialize Configuration",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```java\npackage com.cloudbase;\n\nimport com.google.gson.Gson;\nimport com.google.gson.JsonObject;\nimport io.github.cdimascio.dotenv.Dotenv;\nimport okhttp3.*;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class CloudBaseClient {\n    private final String envId;\n    private final String accessToken;\n    private final String baseUrl;\n    private final OkHttpClient client;\n    private final Gson gson;\n    private final Map<String, String> defaultHeaders;\n\n    public CloudBaseClient() {\n        // LoadEnvironment variable\n        Dotenv dotenv = Dotenv.configure().ignoreIfMissing().load();\n        this.envId = dotenv.get(\"CLOUDBASE_ENV_ID\");\n        this.accessToken = dotenv.get(\"CLOUDBASE_ACCESS_TOKEN\");\n        this.baseUrl = \"https://\" + envId + \".api.tcloudbasegateway.com\";\n\n        this.client = new OkHttpClient();\n        this.gson = new Gson();\n\n        // SetDefaultRequest header\n        this.defaultHeaders = new HashMap<>();\n        this.defaultHeaders.put(\"Content-Type\", \"application/json\");\n        this.defaultHeaders.put(\"Accept\", \"application/json\");\n        this.defaultHeaders.put(\"Authorization\", \"Bearer \" + accessToken);\n    }\n\n    public String getEnvId() {\n        return envId;\n    }\n\n    public String getAccessToken() {\n        return accessToken;\n    }\n\n    public OkHttpClient getClient() {\n        return client;\n    }\n\n    public Gson getGson() {\n        return gson;\n    }\n\n    /**\n     * Unified HTTP request method\n     *\n     * @param method Request method (GET, POST, PUT, PATCH, DELETE)\n     * @param path APIPath (such as /v1/rdb/rest/table_name)\n     * @param body Requestbody (Optional)\n     * @param customHeaders CustomRequest header (Optional)\n     * @return ResponseDataornull\n     */\n    public JsonObject request(String method, String path, Object body, Map<String, String> customHeaders) {\n        try {\n            String url = baseUrl + path;\n\n            // BuildRequest header\n            Headers.Builder headersBuilder = new Headers.Builder();\n            defaultHeaders.forEach(headersBuilder::add);\n            if (customHeaders != null) {\n                customHeaders.forEach(headersBuilder::add);\n            }\n\n            // BuildRequestbody\n            RequestBody requestBody = null;\n            if (body != null) {\n                String jsonBody = gson.toJson(body);\n                requestBody = RequestBody.create(jsonBody, MediaType.parse(\"application/json\"));\n            } else if (method.equals(\"POST\") || method.equals(\"PUT\") || method.equals(\"PATCH\")) {\n                requestBody = RequestBody.create(\"\", MediaType.parse(\"application/json\"));\n            }\n\n            // BuildRequest\n            Request.Builder requestBuilder = new Request.Builder()\n                    .url(url)\n                    .headers(headersBuilder.build())\n                    .method(method, requestBody);\n\n            // SendRequest\n            try (Response response = client.newCall(requestBuilder.build()).execute()) {\n                if (!response.isSuccessful()) {\n                    System.err.println(\"Requestfailed: \" + response.code() + \" \" + response.message());\n                    return null;\n                }\n\n                // IfResponseis empty，Returnsuccessfulidentifier\n                String responseBody = response.body().string();\n                if (responseBody == null || responseBody.isEmpty()) {\n                    JsonObject result = new JsonObject();\n                    result.addProperty(\"success\", true);\n                    return result;\n                }\n\n                return gson.fromJson(responseBody, JsonObject.class);\n            }\n        } catch (IOException e) {\n            System.err.println(\"Requestfailed: \" + e.getMessage());\n            return null;\n        }\n    }\n\n    public JsonObject request(String method, String path, Object body) {\n        return request(method, path, body, null);\n    }\n\n    public JsonObject request(String method, String path) {\n        return request(method, path, null, null);\n    }\n}\n```",
            "index": 1,
            "title": "CloudBaseClient.java"
          },
          {
            "markdown": "> 💡Note: If admin permission is needed, obtain the APIKey from the [CloudBase Platform/ApiKeymanagement page](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}&#/env/apikey) Get APIKey to replace CLOUDBASE_ACCESS_TOKEN\n\n```properties\n# Environment ID\nCLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Anonymous access token\nCLOUDBASE_ACCESS_TOKEN={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": ".env"
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // Query {%TABLE_NAME%} table (limit 10 records)\n        JsonObject data = cloudbase.request(\"GET\", \"/v1/rdb/rest/{{%TABLE_NAME%}}?select=*&limit=10\");\n\n        if (data != null) {\n            System.out.println(\"Query result: \" + data);\n        }\n    }\n}\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // Insert data into {%TABLE_NAME%}\n        Map<String, String> headers = new HashMap<>();\n        headers.put(\"Prefer\", \"return=representation\");\n        JsonObject data = cloudbase.request(\"POST\", \"/v1/rdb/rest/{{%TABLE_NAME%}}\", \"{\"title\":\"New Post\",\"status\":\"draft\"}\", headers);\n\n        if (data != null) {\n            System.out.println(\"Insert result: \" + data);\n        }\n    }\n}\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // Update record in {%TABLE_NAME%}\n        Map<String, String> headers = new HashMap<>();\n        headers.put(\"Prefer\", \"return=representation\");\n        JsonObject data = cloudbase.request(\"PATCH\", \"/v1/rdb/rest/{{%TABLE_NAME%}}?id=eq.1\", \"{\"status\":\"published\"}\", headers);\n\n        if (data != null) {\n            System.out.println(\"Update result: \" + data);\n        }\n    }\n}\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // Update record in {%TABLE_NAME%}\n        Map<String, String> headers = new HashMap<>();\n        headers.put(\"Prefer\", \"resolution=merge-duplicates,return=representation\");\n        JsonObject data = cloudbase.request(\"POST\", \"/v1/rdb/rest/{{%TABLE_NAME%}}\", \"{\"id\":1,\"title\":\"Post Title\",\"status\":\"published\"}\", headers);\n\n        if (data != null) {\n            System.out.println(\"Upsert result: \" + data);\n        }\n    }\n}\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // Delete record from {%TABLE_NAME%}\n        JsonObject data = cloudbase.request(\"DELETE\", \"/v1/rdb/rest/{{%TABLE_NAME%}}?id=eq.1\");\n\n        if (data != null) {\n            System.out.println(\"Delete completed: \" + data);\n        }\n    }\n}\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // Query MySQL database data\n        JsonObject data = cloudbase.request(\"GET\", \"/v1/rdb/rest/{%TABLE_NAME%}?limit=10\");\n\n        if (data != null) {\n            System.out.println(\"Querysuccessful: \" + data);\n        }\n    }\n}\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // PrepareData\n        Map<String, Object> data = new HashMap<>();\n        data.put(\"title\", \"Example Title\");\n\n        // Add MySQL database data\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/rdb/rest/{%TABLE_NAME%}\", data);\n\n        if (result != null) {\n            System.out.println(\"Insert successful: \" + result);\n        }\n    }\n}\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // PrepareUpdate Data\n        Map<String, Object> data = new HashMap<>();\n        data.put(\"title\", \"New Title\");\n\n        // Update MySQL database data\n        String dataId = \"<data id>\";\n        JsonObject result = cloudbase.request(\"PATCH\", \"/v1/rdb/rest/{%TABLE_NAME%}?id=eq.\" + dataId, data);\n\n        if (result != null) {\n            System.out.println(\"Update successful: \" + result);\n        }\n    }\n}\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // Delete MySQL database data\n        String dataId = \"<data id>\";\n        JsonObject result = cloudbase.request(\"DELETE\", \"/v1/rdb/rest/{%TABLE_NAME%}?id=eq.\" + dataId);\n\n        if (result != null) {\n            System.out.println(\"Delete successful\");\n        }\n    }\n}\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // PrepareQueryparameter\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"pageSize\", 10);\n        payload.put(\"pageNumber\", 1);\n        payload.put(\"getCount\", true);\n\n        // QueryData ModelData\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/model/prod/{%TABLE_NAME%}/list\", payload);\n\n        if (result != null) {\n            JsonArray records = result.getAsJsonObject(\"data\").getAsJsonArray(\"records\");\n            System.out.println(\"Querysuccessful: \" + records);\n        }\n    }\n}\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // PrepareData\n        Map<String, Object> data = new HashMap<>();\n        data.put(\"title\", \"Example Title\");\n\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"data\", data);\n\n        // AddData ModelData\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/model/prod/{%TABLE_NAME%}/create\", payload);\n\n        if (result != null) {\n            String docId = result.getAsJsonObject(\"data\").get(\"id\").getAsString();\n            System.out.println(\"Insert successful! id: \" + docId);\n        }\n    }\n}\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // PrepareUpdate Data\n        Map<String, Object> data = new HashMap<>();\n        data.put(\"title\", \"New Title\");\n\n        // PrepareFiltercondition\n        Map<String, Object> eqCondition = new HashMap<>();\n        eqCondition.put(\"$eq\", \"<data id>\");\n\n        Map<String, Object> whereCondition = new HashMap<>();\n        whereCondition.put(\"_id\", eqCondition);\n\n        Map<String, Object> filter = new HashMap<>();\n        filter.put(\"where\", whereCondition);\n\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"data\", data);\n        payload.put(\"filter\", filter);\n\n        // UpdateData ModelData\n        JsonObject result = cloudbase.request(\"PUT\", \"/v1/model/prod/{%TABLE_NAME%}/update\", payload);\n\n        if (result != null) {\n            System.out.println(\"Update successful!\");\n        }\n    }\n}\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // PrepareFiltercondition\n        Map<String, Object> eqCondition = new HashMap<>();\n        eqCondition.put(\"$eq\", \"<data id>\");\n\n        Map<String, Object> whereCondition = new HashMap<>();\n        whereCondition.put(\"_id\", eqCondition);\n\n        Map<String, Object> filter = new HashMap<>();\n        filter.put(\"where\", whereCondition);\n\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"filter\", filter);\n\n        // DeleteData ModelData\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/model/prod/{%TABLE_NAME%}/delete\", payload);\n\n        if (result != null) {\n            System.out.println(\"Delete successful!\");\n        }\n    }\n}\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // CallCloud Function\n        Map<String, Object> data = new HashMap<>();\n        // data.put(\"key\", \"value\"); // Optionalparameter\n\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/functions/{%FUNCTION_NAME%}\", data);\n\n        if (result != null) {\n            System.out.println(\"Cloud function call result: \" + result);\n        }\n    }\n}\n```",
            "index": 3,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // CallCloud Runservice\n        String serviceName = \"{%SERVICE_NAME%}\";\n        String path = \"\"; // OptionalPath\n        String fullPath = \"/v1/cloudrun/\" + serviceName + (path.isEmpty() ? \"\" : \"/\" + path);\n\n        JsonObject result = cloudbase.request(\"GET\", fullPath);\n\n        if (result != null) {\n            System.out.println(\"Cloud RunCallResult: \" + result);\n        }\n    }\n}\n```",
            "index": 4,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonObject;\nimport okhttp3.*;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) throws IOException {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // Upload FiletoCloud Storage\n        String filePath = \"./example.jpg\";\n        String objectId = \"uploads/\" + System.currentTimeMillis() + \"-\" + new File(filePath).getName();\n\n        // 1. Get upload info\n        List<Map<String, String>> uploadInfoRequest = new ArrayList<>();\n        Map<String, String> objectInfo = new HashMap<>();\n        objectInfo.put(\"objectId\", objectId);\n        uploadInfoRequest.add(objectInfo);\n\n        JsonObject uploadInfoResponse = cloudbase.request(\"POST\", \"/v1/storages/get-objects-upload-info\", uploadInfoRequest);\n\n        if (uploadInfoResponse == null) {\n            System.err.println(\"Get upload infofailed\");\n            return;\n        }\n\n        JsonObject uploadInfo = uploadInfoResponse.getAsJsonArray().get(0).getAsJsonObject();\n        String uploadUrl = uploadInfo.get(\"uploadUrl\").getAsString();\n        String authorization = uploadInfo.get(\"authorization\").getAsString();\n        String token = uploadInfo.get(\"token\").getAsString();\n        String cloudObjectMeta = uploadInfo.get(\"cloudObjectMeta\").getAsString();\n\n        // 2. Upload File\n        File file = new File(filePath);\n        byte[] fileData = Files.readAllBytes(file.toPath());\n\n        OkHttpClient client = new OkHttpClient();\n        RequestBody requestBody = RequestBody.create(fileData, MediaType.parse(\"application/octet-stream\"));\n\n        Request uploadRequest = new Request.Builder()\n                .url(uploadUrl)\n                .put(requestBody)\n                .addHeader(\"Authorization\", authorization)\n                .addHeader(\"X-Cos-Security-Token\", token)\n                .addHeader(\"X-Cos-Meta-Fileid\", cloudObjectMeta)\n                .build();\n\n        try (Response response = client.newCall(uploadRequest).execute()) {\n            if (response.isSuccessful()) {\n                String cloudObjectId = uploadInfo.get(\"cloudObjectId\").getAsString();\n                String downloadUrl = uploadInfo.get(\"downloadUrl\").getAsString();\n\n                System.out.println(\"fileUpload successful:\");\n                System.out.println(\"- Object ID: \" + objectId);\n                System.out.println(\"- cloudObject ID: \" + cloudObjectId);\n                System.out.println(\"- DownloadURL: \" + downloadUrl);\n            } else {\n                System.err.println(\"fileUploadfailed: \" + response.code());\n            }\n        }\n    }\n}\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonObject;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // GetCloud Storagefiletemporary accessURL\n        String cloudObjectId = \"cloud://xxx.png\";\n\n        List<Map<String, String>> request = new ArrayList<>();\n        Map<String, String> objectInfo = new HashMap<>();\n        objectInfo.put(\"cloudObjectId\", cloudObjectId);\n        request.add(objectInfo);\n\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/storages/get-objects-download-info\", request);\n\n        if (result != null) {\n            String downloadUrl = result.getAsJsonArray().get(0).getAsJsonObject().get(\"downloadUrl\").getAsString();\n            System.out.println(\"fileURL: \" + downloadUrl);\n        }\n    }\n}\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) throws IOException {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // DownloadCloud Storagefiletolocal\n        String cloudObjectId = \"cloud://xxx.png\";\n        String savePath = \"./downloaded.png\";\n\n        // 1. GetDownloadURL\n        List<Map<String, String>> request = new ArrayList<>();\n        Map<String, String> objectInfo = new HashMap<>();\n        objectInfo.put(\"cloudObjectId\", cloudObjectId);\n        request.add(objectInfo);\n\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/storages/get-objects-download-info\", request);\n\n        if (result == null) {\n            System.err.println(\"GetDownloadURLfailed\");\n            return;\n        }\n\n        String downloadUrl = result.getAsJsonArray().get(0).getAsJsonObject().get(\"downloadUrl\").getAsString();\n\n        // 2. Download File\n        OkHttpClient client = new OkHttpClient();\n        Request downloadRequest = new Request.Builder().url(downloadUrl).build();\n\n        try (Response response = client.newCall(downloadRequest).execute()) {\n            if (response.isSuccessful() && response.body() != null) {\n                try (FileOutputStream fos = new FileOutputStream(savePath)) {\n                    fos.write(response.body().bytes());\n                }\n                System.out.println(\"Downloadsuccessful! filesaved to: \" + savePath);\n            } else {\n                System.err.println(\"Downloadfailed: \" + response.code());\n            }\n        }\n    }\n}\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // DeleteCloud Storagefile\n        String cloudObjectId = \"cloud://xxx.png\";\n\n        List<Map<String, String>> request = new ArrayList<>();\n        Map<String, String> objectInfo = new HashMap<>();\n        objectInfo.put(\"cloudObjectId\", cloudObjectId);\n        request.add(objectInfo);\n\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/storages/delete-objects\", request);\n\n        if (result != null) {\n            System.out.println(\"Delete successful!\");\n        }\n    }\n}\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport okhttp3.*;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.nio.charset.StandardCharsets;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) throws IOException {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // streamingtextthisGenerate\n        String model = \"{%AI_MODEL_NAME%}\";\n        String subModel = \"{%AI_SUB_MODEL_NAME%}\";\n\n        // PrepareMessage\n        List<Map<String, String>> messages = new ArrayList<>();\n        Map<String, String> systemMsg = new HashMap<>();\n        systemMsg.put(\"role\", \"system\");\n        systemMsg.put(\"content\", \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\");\n        messages.add(systemMsg);\n\n        Map<String, String> userMsg = new HashMap<>();\n        userMsg.put(\"role\", \"user\");\n        userMsg.put(\"content\", \"Spring\");\n        messages.add(userMsg);\n\n        // PrepareRequestbody\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"model\", subModel);\n        payload.put(\"messages\", messages);\n        payload.put(\"stream\", true);\n\n        // Use CloudBaseClient ConfigurationBuildstreamingRequest\n        String url = \"https://\" + cloudbase.getEnvId() + \".api.tcloudbasegateway.com/v1/ai/\" + model + \"/chat/completions\";\n        String jsonPayload = cloudbase.getGson().toJson(payload);\n\n        RequestBody requestBody = RequestBody.create(jsonPayload, MediaType.parse(\"application/json\"));\n\n        Request request = new Request.Builder()\n                .url(url)\n                .post(requestBody)\n                .addHeader(\"Content-Type\", \"application/json\")\n                .addHeader(\"Accept\", \"text/event-stream\")\n                .addHeader(\"Authorization\", \"Bearer \" + cloudbase.getAccessToken())\n                .build();\n\n        System.out.println(\"AI Streaming response:\");\n        StringBuilder fullContent = new StringBuilder();\n\n        try (Response response = cloudbase.getClient().newCall(request).execute()) {\n            if (response.isSuccessful() && response.body() != null) {\n                BufferedReader reader = new BufferedReader(\n                    new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8)\n                );\n                String line;\n\n                while ((line = reader.readLine()) != null) {\n                    if (line.startsWith(\"data: \")) {\n                        String dataStr = line.substring(6);\n                        if (!dataStr.trim().equals(\"[DONE]\")) {\n                            try {\n                                JsonObject chunkData = cloudbase.getGson().fromJson(dataStr, JsonObject.class);\n                                if (chunkData.has(\"choices\") && chunkData.getAsJsonArray(\"choices\").size() > 0) {\n                                    JsonObject choice = chunkData.getAsJsonArray(\"choices\").get(0).getAsJsonObject();\n                                    if (choice.has(\"delta\") && choice.getAsJsonObject(\"delta\").has(\"content\")) {\n                                        String content = choice.getAsJsonObject(\"delta\").get(\"content\").getAsString();\n                                        System.out.print(content);\n                                        fullContent.append(content);\n                                    }\n                                }\n                            } catch (Exception e) {\n                                // Ignore JSON parsing error\n                            }\n                        }\n                    }\n                }\n                System.out.println(); // newline\n            }\n        }\n    }\n}\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        try {\n            // PrepareCallparameter\n            Map<String, Object> data = new HashMap<>();\n            data.put(\"prompt\", \"A cute cat playing in the sunshine\");\n\n            // CallCloud FunctionGenerate Image\n            JsonObject result = cloudbase.request(\"POST\", \"/v1/functions/<YOUR_FUNCTION_NAME>\", data);\n\n            if (result != null) {\n                boolean success = result.has(\"success\") && result.get(\"success\").getAsBoolean();\n                \n                if (success) {\n                    String imageUrl = result.get(\"imageUrl\").getAsString();\n                    String revisedPrompt = result.has(\"revised_prompt\") \n                        ? result.get(\"revised_prompt\").getAsString() \n                        : \"\";\n                    \n                    System.out.println(\"Generation successful!\");\n                    System.out.println(\"Image URL: \" + imageUrl);\n                    System.out.println(\"Optimized prompt: \" + revisedPrompt);\n                    System.out.println(\"Note: Image URLValidis valid for24hours\");\n                } else {\n                    String code = result.has(\"code\") ? result.get(\"code\").getAsString() : \"\";\n                    String message = result.has(\"message\") ? result.get(\"message\").getAsString() : \"\";\n                    System.err.println(\"Generation failed: \" + code + \" - \" + message);\n                }\n            } else {\n                System.err.println(\"Requestfailed\");\n            }\n        } catch (Exception e) {\n            System.err.println(\"Generate Imagewhenerror: \" + e.getMessage());\n        }\n    }\n}\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```java\n/**\n * Java Call Agent Example (AG-UI Protocol)\n * Protocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n */\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport okhttp3.*;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.nio.charset.StandardCharsets;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) throws IOException {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // streamingCallAgent（AG-UI Protocol)\n        String botId = \"{%AGENT_ID%}\";\n\n        // PrepareMessageList（AG-UI protocol format)\n        List<Map<String, Object>> messages = new ArrayList<>();\n        Map<String, Object> userMessage = new HashMap<>();\n        userMessage.put(\"id\", \"msg-\" + UUID.randomUUID().toString());\n        userMessage.put(\"role\", \"user\");\n        userMessage.put(\"content\", \"Who are you\");\n        messages.add(userMessage);\n\n        // PrepareRequestbody（AG-UI Protocol)\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"messages\", messages);                    // Required: Message list\n        payload.put(\"threadId\", \"thread-\" + UUID.randomUUID().toString()); // Optional: Session ID for multi-turn conversation\n        payload.put(\"runId\", \"run-\" + UUID.randomUUID().toString());       // Optional：this timeRunID\n        payload.put(\"tools\", new ArrayList<>());              // Optional: Frontend tool definitions\n        payload.put(\"context\", new ArrayList<>());            // Optional: Context information\n        payload.put(\"forwardedProps\", new HashMap<>());       // Optional: Pass-through parameters\n\n        // Use CloudBaseClient ConfigurationBuildstreamingRequest\n        String url = \"https://\" + cloudbase.getEnvId() + \".api.tcloudbasegateway.com/v1/aibot/bots/\" + botId + \"/send-message\";\n        String jsonPayload = cloudbase.getGson().toJson(payload);\n\n        RequestBody requestBody = RequestBody.create(jsonPayload, MediaType.parse(\"application/json\"));\n\n        Request request = new Request.Builder()\n                .url(url)\n                .post(requestBody)\n                .addHeader(\"Content-Type\", \"application/json\")\n                .addHeader(\"Accept\", \"text/event-stream\")\n                .addHeader(\"Authorization\", \"Bearer \" + cloudbase.getAccessToken())\n                .build();\n\n        System.out.println(\"AI Streaming response:\");\n        StringBuilder fullContent = new StringBuilder();\n\n        try (Response response = cloudbase.getClient().newCall(request).execute()) {\n            if (response.isSuccessful() && response.body() != null) {\n                BufferedReader reader = new BufferedReader(\n                    new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8)\n                );\n                String line;\n\n                while ((line = reader.readLine()) != null) {\n                    if (line.startsWith(\"data: \")) {\n                        String dataStr = line.substring(6).trim();\n                        if (!dataStr.isEmpty() && !dataStr.equals(\"[DONE]\")) {\n                            try {\n                                JsonObject chunkData = cloudbase.getGson().fromJson(dataStr, JsonObject.class);\n\n                                // support multipleResponseformat\n                                String content = null;\n                                if (chunkData.has(\"content\")) {\n                                    content = chunkData.get(\"content\").getAsString();\n                                } else if (chunkData.has(\"choices\") && chunkData.getAsJsonArray(\"choices\").size() > 0) {\n                                    JsonObject choice = chunkData.getAsJsonArray(\"choices\").get(0).getAsJsonObject();\n                                    if (choice.has(\"delta\") && choice.getAsJsonObject(\"delta\").has(\"content\")) {\n                                        content = choice.getAsJsonObject(\"delta\").get(\"content\").getAsString();\n                                    } else if (choice.has(\"message\") && choice.getAsJsonObject(\"message\").has(\"content\")) {\n                                        content = choice.getAsJsonObject(\"message\").get(\"content\").getAsString();\n                                    }\n                                }\n\n                                if (content != null && !content.isEmpty()) {\n                                    System.out.print(content);\n                                    fullContent.append(content);\n                                }\n                            } catch (Exception e) {\n                                // Ignore JSON parsing error\n                            }\n                        }\n                    }\n                }\n                System.out.println(); // newline\n            }\n        }\n    }\n}\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport okhttp3.*;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.nio.charset.StandardCharsets;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) throws IOException {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // streamingCallAgent\n        String botId = \"{%AGENT_ID%}\";\n        String msg = \"Who are you\";\n        List<Map<String, String>> history = new ArrayList<>();\n\n        // PrepareRequestbody\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"history\", history);\n        payload.put(\"msg\", msg);\n\n        // Use CloudBaseClient ConfigurationBuildstreamingRequest\n        String url = \"https://\" + cloudbase.getEnvId() + \".api.tcloudbasegateway.com/v1/aibot/bots/\" + botId + \"/send-message\";\n        String jsonPayload = cloudbase.getGson().toJson(payload);\n\n        RequestBody requestBody = RequestBody.create(jsonPayload, MediaType.parse(\"application/json\"));\n\n        Request request = new Request.Builder()\n                .url(url)\n                .post(requestBody)\n                .addHeader(\"Content-Type\", \"application/json\")\n                .addHeader(\"Accept\", \"text/event-stream\")\n                .addHeader(\"Authorization\", \"Bearer \" + cloudbase.getAccessToken())\n                .build();\n\n        System.out.println(\"AI Streaming response:\");\n        StringBuilder fullContent = new StringBuilder();\n\n        try (Response response = cloudbase.getClient().newCall(request).execute()) {\n            if (response.isSuccessful() && response.body() != null) {\n                BufferedReader reader = new BufferedReader(\n                    new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8)\n                );\n                String line;\n\n                while ((line = reader.readLine()) != null) {\n                    if (line.startsWith(\"data: \")) {\n                        String dataStr = line.substring(6).trim();\n                        if (!dataStr.isEmpty() && !dataStr.equals(\"[DONE]\")) {\n                            try {\n                                JsonObject chunkData = cloudbase.getGson().fromJson(dataStr, JsonObject.class);\n\n                                // support multipleResponseformat\n                                String content = null;\n                                if (chunkData.has(\"content\")) {\n                                    content = chunkData.get(\"content\").getAsString();\n                                } else if (chunkData.has(\"choices\") && chunkData.getAsJsonArray(\"choices\").size() > 0) {\n                                    JsonObject choice = chunkData.getAsJsonArray(\"choices\").get(0).getAsJsonObject();\n                                    if (choice.has(\"delta\") && choice.getAsJsonObject(\"delta\").has(\"content\")) {\n                                        content = choice.getAsJsonObject(\"delta\").get(\"content\").getAsString();\n                                    } else if (choice.has(\"message\") && choice.getAsJsonObject(\"message\").has(\"content\")) {\n                                        content = choice.getAsJsonObject(\"message\").get(\"content\").getAsString();\n                                    }\n                                }\n\n                                if (content != null && !content.isEmpty()) {\n                                    System.out.print(content);\n                                    fullContent.append(content);\n                                }\n                            } catch (Exception e) {\n                                // Ignore JSON parsing error\n                            }\n                        }\n                    }\n                }\n                System.out.println(); // newline\n            }\n        }\n    }\n}\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // Username Password Login\n        Map<String, String> credentials = new HashMap<>();\n        credentials.put(\"username\", \"your_username\");\n        credentials.put(\"password\", \"your_password\");\n\n        JsonObject result = cloudbase.request(\"POST\", \"/auth/v1/signin\", credentials);\n\n        if (result != null) {\n            String accessToken = result.get(\"access_token\").getAsString();\n            String refreshToken = result.get(\"refresh_token\").getAsString();\n            String userId = result.get(\"sub\").getAsString();\n\n            System.out.println(\"Login successful! User ID: \" + userId);\n            System.out.println(\"Access token: \" + accessToken.substring(0, 20) + \"...\");\n        }\n    }\n}\n```",
            "index": 8,
            "id": "identity",
            "title": "Authentication"
          }
        ]
      }
    ],
    "_id": "2cf12107697c28d700353fa73b958433",
    "_openid": "anon",
    "createdAt": 1769744599895,
    "updatedAt": 1769766697784
  },
  {
    "category": "Framework Integration,Backend Frameworks,Python",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 21,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/http-api/basic/overview",
    "content": [
      {
        "markdown": "Use **HTTP Request** in **python** Callvarious CloudBase capabilities\n\n```bash\npip install requests python-dotenv\n```",
        "index": 1,
        "title": "Install Dependencies",
        "content": []
      },
      {
        "markdown": "Add the following code to your **Python** project",
        "index": 2,
        "title": "Initialize Configuration",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```python\nimport os\nimport requests\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nclass CloudBaseClient:\n\tdef __init__(self):\n\t\tself.env_id = os.getenv(\"CLOUDBASE_ENV_ID\")\n\t\tself.access_token = os.getenv(\"CLOUDBASE_ACCESS_TOKEN\")\n\t\tself.base_url = f\"https://{self.env_id}.api.tcloudbasegateway.com\"\n\t\tself.headers = {\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"Accept\": \"application/json\",\n\t\t\t\"Authorization\": f\"Bearer {self.access_token}\"\n\t\t}\n\n\tdef request(self, method, path, **kwargs):\n\t\t\"\"\"\n\t\tUnified HTTP request method\n\n\t\tArgs:\n\t\t\tmethod: Request method (GET, POST, PUT, PATCH, DELETE)\n\t\t\tpath: APIPath (such as /v1/rdb/rest/table_name)\n\t\t\t**kwargs: otherRequestparameter (json, params, headersetc)\n\n\t\tReturns:\n\t\t\tResponseDataorNone\n\t\t\"\"\"\n\t\turl = f\"{self.base_url}{path}\"\n\t\theaders = self.headers.copy()\n\n\t\t# AllowCustomheaders\n\t\tif \"headers\" in kwargs:\n\t\t\theaders.update(kwargs.pop(\"headers\"))\n\n\t\ttry:\n\t\t\tresponse = requests.request(method, url, headers=headers, **kwargs)\n\t\t\tresponse.raise_for_status()\n\n\t\t\t# IfResponseis empty，ReturnTruerepresentssuccessful\n\t\t\tif not response.content:\n\t\t\t\treturn True\n\n\t\t\treturn response.json()\n\t\texcept requests.exceptions.RequestException as e:\n\t\t\tprint(f\"Requestfailed: {e}\")\n\t\t\treturn None\n\ncloudbase = CloudBaseClient()\n```",
            "index": 1,
            "title": "cloudbase_client.py"
          },
          {
            "markdown": "> 💡Note: If admin permission is needed, obtain the APIKey from the [CloudBase Platform/ApiKeymanagement page](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}&#/env/apikey) Get APIKey to replace CLOUDBASE_ACCESS_TOKEN\n\n```properties\n# Environment ID\nCLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Anonymous access token\nCLOUDBASE_ACCESS_TOKEN={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": ".env"
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n# Query {%TABLE_NAME%} table (limit 10 records)\nresponse = cloudbase.request(\n    \"GET\",\n    f\"/v1/rdb/rest/{{%TABLE_NAME%}}?select=*&limit=10\",\n)\nprint(\"Query result:\", response.json())\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n# Insert data into {%TABLE_NAME%}\nresponse = cloudbase.request(\n    \"POST\",\n    f\"/v1/rdb/rest/{{%TABLE_NAME%}\",\n    json={\"title\": \"New Post\", \"status\": \"draft\"},\n    headers={\"Prefer\": \"return=representation\"},\n)\nprint(\"Insert result:\", response.json())\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n# Update data in {%TABLE_NAME%}\nresponse = cloudbase.request(\n    \"PATCH\",\n    f\"/v1/rdb/rest/{{%TABLE_NAME%}?id=eq.1\",\n    json={\"status\": \"published\"},\n    headers={\"Prefer\": \"return=representation\"},\n)\nprint(\"Update result:\", response.json())\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n# Upsert data in {%TABLE_NAME%}\nresponse = cloudbase.request(\n    \"POST\",\n    f\"/v1/rdb/rest/{{%TABLE_NAME%}\",\n    json={\"id\": 1, \"title\": \"Post Title\", \"status\": \"published\"},\n    headers={\"Prefer\": \"resolution=merge-duplicates,return=representation\"},\n)\nprint(\"Upsert result:\", response.json())\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n# Delete record by id in {%TABLE_NAME%}\nresponse = cloudbase.request(\n    \"DELETE\",\n    f\"/v1/rdb/rest/{{%TABLE_NAME%}}?id=eq.1\",\n)\nprint(\"Delete completed:\", response.status_code)\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef get_mysql_data(table_name):\n\t\"\"\"Query MySQL database data\"\"\"\n\tdata = cloudbase.request(\"GET\", f\"/v1/rdb/rest/{table_name}?limit=10\")\n\n\tif data:\n\t\tprint(\"Querysuccessful:\", data)\n\treturn data or []\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = get_mysql_data(\"{%TABLE_NAME%}\")\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef add_mysql_data(table_name, data):\n\t\"\"\"Add MySQL database data\"\"\"\n\tresult = cloudbase.request(\"POST\", f\"/v1/rdb/rest/{table_name}\", json=data)\n\n\tif result:\n\t\tprint(\"Insert successful:\", result)\n\treturn result\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = add_mysql_data(\"{%TABLE_NAME%}\", {\"title\": \"Example Title\"})\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef update_mysql_data(table_name, data_id, data):\n\t\"\"\"Update MySQL database data\"\"\"\n\tresult = cloudbase.request(\"PATCH\", f\"/v1/rdb/rest/{table_name}?id=eq.{data_id}\", json=data)\n\n\tif result:\n\t\tprint(\"Update successful:\", result)\n\treturn result\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = update_mysql_data(\"{%TABLE_NAME%}\", \"<data id>\", {\"title\": \"New Title\"})\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef delete_mysql_data(table_name, data_id):\n\t\"\"\"Delete MySQL database data\"\"\"\n\tresult = cloudbase.request(\"DELETE\", f\"/v1/rdb/rest/{table_name}?id=eq.{data_id}\")\n\n\tif result:\n\t\tprint(\"Delete successful\")\n\t\treturn True\n\treturn False\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = delete_mysql_data(\"{%TABLE_NAME%}\", \"<data id>\")\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef get_model_data(model_name, env_type=\"prod\"):\n\t\"\"\"QueryData ModelData\"\"\"\n\tpayload = {\n\t\t\"pageSize\": 10,\n\t\t\"pageNumber\": 1,\n\t\t\"getCount\": True\n\t}\n\n\tresult = cloudbase.request(\"POST\", f\"/v1/model/{env_type}/{model_name}/list\", json=payload)\n\n\tif result:\n\t\trecords = result.get(\"data\", {}).get(\"records\", [])\n\t\tprint(\"Querysuccessful:\", records)\n\t\treturn records\n\treturn []\n\n# Usage Example\nif __name__ == \"__main__\":\n\trecords = get_model_data(\"{%TABLE_NAME%}\")\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef add_model_data(model_name, data, env_type=\"prod\"):\n\t\"\"\"AddData ModelData\"\"\"\n\tresult = cloudbase.request(\"POST\", f\"/v1/model/{env_type}/{model_name}/create\", json={\"data\": data})\n\n\tif result:\n\t\tdoc_id = result.get(\"data\", {}).get(\"id\")\n\t\tprint(f\"Insert successful! id: {doc_id}\")\n\treturn result\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = add_model_data(\"{%TABLE_NAME%}\", {\"title\": \"Example Title\"})\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef update_model_data(model_name, data_id, data, env_type=\"prod\"):\n\t\"\"\"UpdateData ModelData\"\"\"\n\tpayload = {\n\t\t\"data\": data,\n\t\t\"filter\": {\n\t\t\t\"where\": {\n\t\t\t\t\"_id\": {\"$eq\": data_id}\n\t\t\t}\n\t\t}\n\t}\n\n\tresult = cloudbase.request(\"PUT\", f\"/v1/model/{env_type}/{model_name}/update\", json=payload)\n\n\tif result:\n\t\tprint(\"Update successful!\")\n\t\treturn True\n\treturn False\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = update_model_data(\"{%TABLE_NAME%}\", \"<data id>\", {\"title\": \"New Title\"})\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef delete_model_data(model_name, data_id, env_type=\"prod\"):\n\t\"\"\"DeleteData ModelData\"\"\"\n\tpayload = {\n\t\t\"filter\": {\n\t\t\t\"where\": {\n\t\t\t\t\"_id\": {\"$eq\": data_id}\n\t\t\t}\n\t\t}\n\t}\n\n\tresult = cloudbase.request(\"POST\", f\"/v1/model/{env_type}/{model_name}/delete\", json=payload)\n\n\tif result:\n\t\tprint(\"Delete successful!\")\n\t\treturn True\n\treturn False\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = delete_model_data(\"{%TABLE_NAME%}\", \"<data id>\")\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef call_function(function_name, data=None):\n\t\"\"\"CallCloud Function\"\"\"\n\tresult = cloudbase.request(\"POST\", f\"/v1/functions/{function_name}\", json=data or {})\n\n\tif result:\n\t\tprint(\"Cloud function call result:\", result)\n\treturn result\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = call_function(\"{%FUNCTION_NAME%}\")\n```",
            "index": 3,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef call_container(service_name, path=\"\", method=\"GET\", data=None):\n\t\"\"\"CallCloud Runservice\"\"\"\n\tfull_path = f\"/v1/cloudrun/{service_name}/{path}\".rstrip(\"/\")\n\tresult = cloudbase.request(method.upper(), full_path, json=data)\n\n\tif result:\n\t\tprint(\"Cloud RunCallResult:\", result)\n\treturn result\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = call_container(\"{%SERVICE_NAME%}\")\n```",
            "index": 4,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```python\nimport os\nimport requests\nfrom datetime import datetime\nfrom cloudbase_client import cloudbase\n\ndef upload_file(file_path, object_id=None):\n\t\"\"\"Upload FiletoCloud Storage\"\"\"\n\tif not object_id:\n\t\tfilename = os.path.basename(file_path)\n\t\ttimestamp = int(datetime.now().timestamp() * 1000)\n\t\tobject_id = f\"uploads/{timestamp}-{filename}\"\n\n\t# 1. Get upload info\n\tupload_info = cloudbase.request(\"POST\", \"/v1/storages/get-objects-upload-info\",\n\t\tjson=[{\"objectId\": object_id}])\n\n\tif not upload_info:\n\t\treturn None\n\n\tupload_info = upload_info[0]\n\tupload_url = upload_info[\"uploadUrl\"]\n\n\ttry:\n\t\t# 2. Upload File\n\t\tupload_headers = {\n\t\t\t\"Authorization\": upload_info[\"authorization\"],\n\t\t\t\"X-Cos-Security-Token\": upload_info[\"token\"],\n\t\t\t\"X-Cos-Meta-Fileid\": upload_info[\"cloudObjectMeta\"]\n\t\t}\n\n\t\twith open(file_path, \"rb\") as f:\n\t\t\tfile_data = f.read()\n\n\t\tupload_response = requests.put(upload_url, headers=upload_headers, data=file_data)\n\t\tupload_response.raise_for_status()\n\n\t\tresult = {\n\t\t\t\"cloudObjectId\": upload_info[\"cloudObjectId\"],\n\t\t\t\"downloadUrl\": upload_info[\"downloadUrl\"],\n\t\t\t\"objectId\": object_id\n\t\t}\n\n\t\tprint(\"fileUpload successful:\")\n\t\tprint(f\"- Object ID: {result['objectId']}\")\n\t\tprint(f\"- DownloadURL: {result['downloadUrl']}\")\n\n\t\treturn result\n\n\texcept FileNotFoundError:\n\t\tprint(f\"filedoes not exist: {file_path}\")\n\t\treturn None\n\texcept Exception as e:\n\t\tprint(f\"fileUploadfailed: {e}\")\n\t\treturn None\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = upload_file(\"./example.jpg\")\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef get_file_url(cloud_object_id):\n\t\"\"\"GetCloud Storagefiletemporary accessURL\"\"\"\n\tresult = cloudbase.request(\"POST\", \"/v1/storages/get-objects-download-info\",\n\t\tjson=[{\"cloudObjectId\": cloud_object_id}])\n\n\tif result:\n\t\tdownload_url = result[0].get(\"downloadUrl\")\n\t\tprint(\"fileURL:\", download_url)\n\t\treturn download_url\n\treturn None\n\n# Usage Example\nif __name__ == \"__main__\":\n\tfile_url = get_file_url(\"cloud://xxx.png\")\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```python\nimport os\nimport requests\nfrom cloudbase_client import cloudbase\n\ndef download_file(cloud_object_id, save_path=\"./\"):\n\t\"\"\"DownloadCloud Storagefiletolocal\"\"\"\n\t# 1. GetDownloadURL\n\tresult = cloudbase.request(\"POST\", \"/v1/storages/get-objects-download-info\",\n\t\tjson=[{\"cloudObjectId\": cloud_object_id}])\n\n\tif not result:\n\t\treturn False\n\n\tdownload_url = result[0].get(\"downloadUrl\")\n\n\ttry:\n\t\t# 2. fromURLExtractfilename\n\t\tfilename = download_url.split(\"/\")[-1].split(\"?\")[0]\n\n\t\t# 3. Ifsave_pathYesDirectory，thenConcatenatefilename\n\t\tif os.path.isdir(save_path) or save_path.endswith(\"/\"):\n\t\t\tfull_path = os.path.join(save_path, filename)\n\t\telse:\n\t\t\tfull_path = save_path\n\n\t\t# 4. Download File\n\t\tfile_response = requests.get(download_url)\n\t\tfile_response.raise_for_status()\n\n\t\t# 5. Save to local\n\t\twith open(full_path, \"wb\") as f:\n\t\t\tf.write(file_response.content)\n\n\t\tprint(f\"Downloadsuccessful! filesaved to: {full_path}\")\n\t\treturn True\n\texcept Exception as e:\n\t\tprint(f\"Downloadfailed: {e}\")\n\t\treturn False\n\n# Usage Example\nif __name__ == \"__main__\":\n\t# Downloadto current directory，Useoriginalfilename\n\tresult = download_file(\"cloud://xxx.png\")\n\n\t# Downloadto specified directory\n\tresult = download_file(\"cloud://xxx.png\", \"./downloads/\")\n\n\t# Downloadand rename\n\tresult = download_file(\"cloud://xxx.png\", \"./my-image.png\")\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef delete_file(cloud_object_ids):\n\t\"\"\"DeleteCloud Storagefile\"\"\"\n\t# IfpassedYessingle string，convert toList\n\tif isinstance(cloud_object_ids, str):\n\t\tcloud_object_ids = [cloud_object_ids]\n\n\tdata = [{\"cloudObjectId\": obj_id} for obj_id in cloud_object_ids]\n\tresult = cloudbase.request(\"POST\", \"/v1/storages/delete-objects\", json=data)\n\n\tif result:\n\t\tprint(\"Delete successful!\")\n\t\treturn True\n\treturn False\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = delete_file(\"cloud://xxx.png\")\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```python\nimport requests\nimport json\nfrom cloudbase_client import cloudbase\n\ndef stream_text(model, sub_model, messages):\n\t\"\"\"streamingtextthisGenerate\"\"\"\n\tpayload = {\n\t\t\"model\": sub_model,\n\t\t\"messages\": messages,\n\t\t\"stream\": True\n\t}\n\n\turl = f\"{cloudbase.base_url}/v1/ai/{model}/chat/completions\"\n\theaders = cloudbase.headers.copy()\n\theaders[\"Accept\"] = \"text/event-stream\"\n\n\ttry:\n\t\tresponse = requests.post(url, headers=headers, json=payload, stream=True)\n\t\tresponse.raise_for_status()\n\n\t\tprint(\"AI Streaming response:\")\n\t\tfull_content = \"\"\n\n\t\tfor line in response.iter_lines():\n\t\t\tif line:\n\t\t\t\tline_str = line.decode(\"utf-8\")\n\t\t\t\tif line_str.startswith(\"data: \"):\n\t\t\t\t\tdata_str = line_str[6:]\n\t\t\t\t\tif data_str.strip() != \"[DONE]\":\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tchunk_data = json.loads(data_str)\n\t\t\t\t\t\t\tcontent = chunk_data.get(\"choices\", [{}])[0].get(\"delta\", {}).get(\"content\", \"\")\n\t\t\t\t\t\t\tif content:\n\t\t\t\t\t\t\t\tprint(content, end=\"\", flush=True)\n\t\t\t\t\t\t\t\tfull_content += content\n\t\t\t\t\t\texcept json.JSONDecodeError:\n\t\t\t\t\t\t\tcontinue\n\n\t\tprint()  # newline\n\t\treturn full_content\n\texcept Exception as e:\n\t\tprint(f\"AI Call failed: {e}\")\n\t\treturn None\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresponse = stream_text(\n\t\t\"{%AI_MODEL_NAME%}\",\n\t\t\"{%AI_SUB_MODEL_NAME%}\",\n\t\t[\n\t\t\t{\"role\": \"system\", \"content\": \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\"},\n\t\t\t{\"role\": \"user\", \"content\": \"Spring\"}\n\t\t]\n\t)\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```python\nimport requests\nfrom cloudbase_client import cloudbase\n\ndef generate_image(prompt):\n\t\"\"\"Call image generation cloud function\"\"\"\n\turl = f\"{cloudbase.base_url}/v1/functions/<YOUR_FUNCTION_NAME>/invoke\"\n\theaders = cloudbase.headers\n\tpayload = {\n\t\t\"prompt\": prompt\n\t}\n\n\ttry:\n\t\tresponse = requests.post(url, headers=headers, json=payload)\n\t\tresponse.raise_for_status()\n\t\tresult = response.json()\n\n\t\tif result.get(\"success\"):\n\t\t\t# Generation successful\n\t\t\tprint(\"Generation successful!\")\n\t\t\tprint(f\"Image URL: {result.get('imageUrl')}\")\n\t\t\tprint(f\"Optimized prompt: {result.get('revised_prompt')}\")\n\n\t\t\t# Use image\n\t\t\t# Note: Image URL is valid for 24 hours, please save or transfer promptly\n\t\t\treturn result\n\t\telse:\n\t\t\t# Generation failed\n\t\t\tprint(f\"Generation failed: {result.get('code')} {result.get('message')}\")\n\t\t\treturn None\n\texcept Exception as e:\n\t\tprint(f\"Call failed: {e}\")\n\t\treturn None\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = generate_image(\"A cute cat playing in the sunshine\")\n\tif result:\n\t\tprint(f\"Image URL: {result.get('imageUrl')}\")\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```python\n\"\"\"\nPython Call Agent Example (AG-UI Protocol)\nProtocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n\"\"\"\nimport requests\nimport json\nimport uuid\nfrom cloudbase_client import cloudbase\n\ndef chat_with_agent_stream(bot_id, msg, history=None):\n    \"\"\"\n    streamingCallAgent（AG-UI Protocol)\n    \n    AG-UI protocolparameterdescription：\n    - messages: Required，MessageList，contains id/role/content\n    - threadId: Optional，Session ID，for multi-turn conversation management\n    - runId: Optional，RunID，for tracking a singleexecute\n    - tools: Optional，Frontend tool definitions\n    - context: Optional，contextInfo\n    - forwardedProps: Optional，pass-throughparameter\n    \"\"\"\n    if history is None:\n        history = []\n\n    url = f\"{cloudbase.base_url}/v1/aibot/bots/{bot_id}/send-message\"\n\n    # Build message list (AG-UI protocol format)\n    messages = []\n    \n    # AddHistoryMessage\n    for h in history:\n        messages.append({\n            \"id\": h.get(\"id\", f\"msg-{uuid.uuid4()}\"),\n            \"role\": h.get(\"role\", \"user\"),\n            \"content\": h.get(\"content\", \"\")\n        })\n    \n    # AddCurrentuserMessage\n    messages.append({\n        \"id\": f\"msg-{uuid.uuid4()}\",\n        \"role\": \"user\",\n        \"content\": msg\n    })\n\n    # AG-UI protocolRequestbody\n    payload = {\n        \"messages\": messages,                      # Required: Message list\n        \"threadId\": f\"thread-{uuid.uuid4()}\",     # Optional：Session ID\n        \"runId\": f\"run-{uuid.uuid4()}\",           # Optional：RunID\n        \"tools\": [],                               # Optional: Frontend tool definitions\n        \"context\": [],                             # Optional: Context information\n        \"forwardedProps\": {}                       # Optional: Pass-through parameters\n    }\n\n    headers = cloudbase.headers.copy()\n    headers[\"Accept\"] = \"text/event-stream\"\n\n    try:\n        response = requests.post(\n            url,\n            headers=headers,\n            json=payload,\n            stream=True,\n            timeout=30\n        )\n        response.raise_for_status()\n\n        print(\"AI Streaming response:\")\n        full_content = \"\"\n        buffer = \"\"\n\n        for chunk in response.iter_content(chunk_size=None, decode_unicode=False):\n            if chunk:\n                try:\n                    # Decodebyte stream\n                    buffer += chunk.decode('utf-8')\n\n                    # Processcomplete line\n                    while '\\n' in buffer:\n                        line, buffer = buffer.split('\\n', 1)\n                        line = line.strip()\n\n                        if line.startswith(\"data: \"):\n                            data_str = line[6:].strip()\n                            if data_str and data_str != \"[DONE]\":\n                                try:\n                                    chunk_data = json.loads(data_str)\n                                    # support multipleResponseformat\n                                    content = (\n                                        chunk_data.get(\"content\") or\n                                        chunk_data.get(\"choices\", [{}])[0].get(\"delta\", {}).get(\"content\", \"\") or\n                                        chunk_data.get(\"choices\", [{}])[0].get(\"message\", {}).get(\"content\", \"\")\n                                    )\n                                    if content:\n                                        print(content, end=\"\", flush=True)\n                                        full_content += content\n                                except json.JSONDecodeError:\n                                    pass\n                except UnicodeDecodeError:\n                    continue\n\n        print()  # newline\n        return full_content\n\n    except requests.exceptions.Timeout:\n        print(\"RequestTimeout，pleaseChecknetworkConnectorincreaseTimeoutwhentime\")\n        return None\n    except requests.exceptions.RequestException as e:\n        print(f\"AI Call failed: {e}\")\n        if hasattr(e.response, 'text'):\n            print(f\"ResponseContent: {e.response.text}\")\n        return None\n\n# Usage Example\nif __name__ == \"__main__\":\n    response = chat_with_agent_stream(\"{%AGENT_ID%}\", \"Who are you\")\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```python\nimport requests\nimport json\nfrom cloudbase_client import cloudbase\n\ndef chat_with_agent_stream(bot_id, msg, history=None):\n\t\"\"\"streamingCallAgent\"\"\"\n\tif history is None:\n\t\thistory = []\n\n\turl = f\"{cloudbase.base_url}/v1/aibot/bots/{bot_id}/send-message\"\n\n\tpayload = {\n\t\t\"history\": history,\n\t\t\"msg\": msg\n\t}\n\n\theaders = cloudbase.headers.copy()\n\theaders[\"Accept\"] = \"text/event-stream\"\n\n\ttry:\n\t\tresponse = requests.post(\n\t\t\turl,\n\t\t\theaders=headers,\n\t\t\tjson=payload,\n\t\t\tstream=True,\n\t\t\ttimeout=30\n\t\t)\n\t\tresponse.raise_for_status()\n\n\t\tprint(\"AI Streaming response:\")\n\t\tfull_content = \"\"\n\t\tbuffer = \"\"\n\n\t\tfor chunk in response.iter_content(chunk_size=None, decode_unicode=False):\n\t\t\tif chunk:\n\t\t\t\ttry:\n\t\t\t\t\t# Decodebyte stream\n\t\t\t\t\tbuffer += chunk.decode('utf-8')\n\n\t\t\t\t\t# Processcomplete line\n\t\t\t\t\twhile '\\n' in buffer:\n\t\t\t\t\t\tline, buffer = buffer.split('\\n', 1)\n\t\t\t\t\t\tline = line.strip()\n\n\t\t\t\t\t\tif line.startswith(\"data: \"):\n\t\t\t\t\t\t\tdata_str = line[6:].strip()\n\t\t\t\t\t\t\tif data_str and data_str != \"[DONE]\":\n\t\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\t\tchunk_data = json.loads(data_str)\n\t\t\t\t\t\t\t\t\t# support multipleResponseformat\n\t\t\t\t\t\t\t\t\tcontent = (\n\t\t\t\t\t\t\t\t\t\tchunk_data.get(\"content\") or\n\t\t\t\t\t\t\t\t\t\tchunk_data.get(\"choices\", [{}])[0].get(\"delta\", {}).get(\"content\", \"\") or\n\t\t\t\t\t\t\t\t\t\tchunk_data.get(\"choices\", [{}])[0].get(\"message\", {}).get(\"content\", \"\")\n\t\t\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t\t\tif content:\n\t\t\t\t\t\t\t\t\t\tprint(content, end=\"\", flush=True)\n\t\t\t\t\t\t\t\t\t\tfull_content += content\n\t\t\t\t\t\t\t\texcept json.JSONDecodeError:\n\t\t\t\t\t\t\t\t\tpass\n\t\t\t\texcept UnicodeDecodeError:\n\t\t\t\t\tcontinue\n\n\t\tprint()  # newline\n\t\treturn full_content\n\n\texcept requests.exceptions.Timeout:\n\t\tprint(\"RequestTimeout，pleaseChecknetworkConnectorincreaseTimeoutwhentime\")\n\t\treturn None\n\texcept requests.exceptions.RequestException as e:\n\t\tprint(f\"AI Call failed: {e}\")\n\t\tif hasattr(e.response, 'text'):\n\t\t\tprint(f\"ResponseContent: {e.response.text}\")\n\t\treturn None\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresponse = chat_with_agent_stream(\"{%AGENT_ID%}\", \"Who are you\")\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "markdown": "```python\nfrom cloudbase_client import cloudbase\n\ndef sign_in(username, password):\n\t\"\"\"Username Password Login\"\"\"\n\tresult = cloudbase.request(\"POST\", \"/auth/v1/signin\",\n\t\tjson={\"username\": username, \"password\": password})\n\n\tif result:\n\t\taccess_token = result.get(\"access_token\")\n\t\trefresh_token = result.get(\"refresh_token\")\n\t\tuser_id = result.get(\"sub\")\n\n\t\tprint(f\"Login successful! User ID: {user_id}\")\n\t\tprint(f\"Access token: {access_token[:20]}...\")\n\t\treturn result\n\treturn None\n\n# Usage Example\nif __name__ == \"__main__\":\n\tresult = sign_in(\"your_username\", \"your_password\")\n```",
            "index": 8,
            "id": "identity",
            "title": "Authentication"
          }
        ]
      }
    ],
    "_id": "2cf12107697c28db00353fcd437a1ec7",
    "_openid": "anon",
    "createdAt": 1769744603277,
    "updatedAt": 1769766701104
  },
  {
    "category": "Framework Integration,Mobile Frameworks,iOS Swift",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 32,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/http-api/basic/overview",
    "content": [
      {
        "markdown": "Use **HTTP Request** in **iOS Swift** Callvarious CloudBase capabilities\n\nthisprojectUse Swift Native URLSession，NoneneedadditionalDependency。\n\nif neededUsethird-party library，canUse CocoaPods or Swift Package Manager Install：\n\n```ruby\n# Podfile\npod 'Alamofire', '~> 5.8'\n```",
        "index": 1,
        "title": "Install Dependencies",
        "content": []
      },
      {
        "markdown": "Add the following code to your **iOS Swift** project",
        "index": 2,
        "title": "Initialize Configuration",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```swift\nimport Foundation\n\nclass CloudBaseClient {\n    let envId: String\n    private(set) var accessToken: String\n    let baseUrl: String\n\n    init(envId: String, accessToken: String) {\n        self.envId = envId\n        self.accessToken = accessToken\n        self.baseUrl = \"https://\\(envId).api.tcloudbasegateway.com\"\n    }\n\n    /// UpdateAccess token\n    ///\n    /// - Parameter newToken: new access token\n    func updateAccessToken(_ newToken: String) {\n        self.accessToken = newToken\n        print(\"Access token has beenUpdate\")\n    }\n\n    /// Unified HTTP request method\n    ///\n    /// - Parameters:\n    ///   - method: Request method (GET, POST, PUT, PATCH, DELETE)\n    ///   - path: APIPath (such as /v1/rdb/rest/table_name)\n    ///   - body: Request body data\n    ///   - customHeaders: Customheaders\n    /// - Returns: ResponseDataornil\n    func request<T: Decodable>(\n        method: String,\n        path: String,\n        body: [String: Any]? = nil,\n        customHeaders: [String: String] = [:],\n        completion: @escaping (T?) -> Void\n    ) {\n        guard let url = URL(string: \"\\(baseUrl)\\(path)\") else {\n            print(\"InvalidURL\")\n            completion(nil)\n            return\n        }\n\n        var request = URLRequest(url: url)\n        request.httpMethod = method.uppercased()\n        request.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n        request.setValue(\"application/json\", forHTTPHeaderField: \"Accept\")\n        request.setValue(\"Bearer \\(accessToken)\", forHTTPHeaderField: \"Authorization\")\n\n        // AddCustomheaders\n        customHeaders.forEach { key, value in\n            request.setValue(value, forHTTPHeaderField: key)\n        }\n\n        // SetRequestbody\n        if let body = body {\n            do {\n                request.httpBody = try JSONSerialization.data(withJSONObject: body)\n            } catch {\n                print(\"JSONSerializefailed: \\(error)\")\n                completion(nil)\n                return\n            }\n        }\n\n        let task = URLSession.shared.dataTask(with: request) { data, response, error in\n            if let error = error {\n                print(\"Requestfailed: \\(error.localizedDescription)\")\n                completion(nil)\n                return\n            }\n\n            guard let httpResponse = response as? HTTPURLResponse,\n                  (200...299).contains(httpResponse.statusCode) else {\n                print(\"Requestfailed: \\((response as? HTTPURLResponse)?.statusCode ?? -1)\")\n                completion(nil)\n                return\n            }\n\n            guard let data = data else {\n                // IfResponseis empty，Returntruerepresentssuccessful\n                if T.self == Bool.self {\n                    completion(true as? T)\n                } else {\n                    completion(nil)\n                }\n                return\n            }\n\n            do {\n                let decoder = JSONDecoder()\n                let result = try decoder.decode(T.self, from: data)\n                completion(result)\n            } catch {\n                // try asasAnyDecode\n                if let json = try? JSONSerialization.jsonObject(with: data) as? T {\n                    completion(json)\n                } else {\n                    print(\"JSONParsefailed: \\(error)\")\n                    completion(nil)\n                }\n            }\n        }\n\n        task.resume()\n    }\n\n    /// SyncVersion（Use async/await）\n    @available(iOS 13.0, *)\n    func request<T: Decodable>(\n        method: String,\n        path: String,\n        body: [String: Any]? = nil,\n        customHeaders: [String: String] = [:]\n    ) async -> T? {\n        await withCheckedContinuation { continuation in\n            request(method: method, path: path, body: body, customHeaders: customHeaders) { (result: T?) in\n                continuation.resume(returning: result)\n            }\n        }\n    }\n}\n\n// ConfigurationfileorInitializewhenCreateinstance\n// let cloudbase = CloudBaseClient(\n//     envId: \"your-env-id\",\n//     accessToken: \"your-access-token\"\n// )\n```",
            "index": 1,
            "title": "CloudBaseClient.swift"
          },
          {
            "markdown": "Create `Config.plist` fileStorageConfiguration：\n\n> 💡 Note: For user permissions, refer to the \"Authentication\" module to obtain access_token\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n    <!-- Environment ID -->\n    <key>CLOUDBASE_ENV_ID</key>\n    <string>{%ENV_ID%}</string>\n    <!-- Anonymous access token -->\n    <key>CLOUDBASE_ACCESS_TOKEN</key>\n    <string>{%PUBLISHABLE_KEY%}</string>\n</dict>\n</plist>\n```\n\nReadConfigurationandInitializeclient：\n\n```swift\nfunc loadConfig() -> (envId: String, accessToken: String)? {\n    guard let path = Bundle.main.path(forResource: \"Config\", ofType: \"plist\"),\n          let config = NSDictionary(contentsOfFile: path),\n          let envId = config[\"CLOUDBASE_ENV_ID\"] as? String,\n          let accessToken = config[\"CLOUDBASE_ACCESS_TOKEN\"] as? String else {\n        return nil\n    }\n    return (envId, accessToken)\n}\n\n// in AppDelegate or SceneDelegate Initialize\nclass AppDelegate: UIResponder, UIApplicationDelegate {\n    var cloudbase: CloudBaseClient?\n\n    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n        // fromConfigurationfileLoadEnvironmentInfo\n        if let config = loadConfig() {\n            cloudbase = CloudBaseClient(envId: config.envId, accessToken: config.accessToken)\n            print(\"CloudBaseclientInitializesuccessful\")\n        } else {\n            print(\"ConfigurationfileLoadfailed\")\n        }\n        return true\n    }\n}\n\n// orinneedplacedirectlyInitialize\n// if let config = loadConfig() {\n//     let cloudbase = CloudBaseClient(envId: config.envId, accessToken: config.accessToken)\n//     // Use cloudbase performaftersubsequentoperate\n// }\n```",
            "index": 2,
            "title": "Config.plist"
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```swift\nfunc getPgData(cloudbase: CloudBaseClient, tableName: String, completion: @escaping ([[String: Any]]?) -> Void) {\n    // Query PG database\n    cloudbase.request(\n        method: \"GET\",\n        path: \"/v1/rdb/rest/\\(tableName)?select=*&limit=10\"\n    ) { (data: [[String: Any]]?) in\n        if let data = data {\n            print(\"Query success: \\(data)\")\n        }\n        completion(data ?? [])\n    }\n}\n\n// Usage example (async/await)\n// Task {\n//     let result: [[String: Any]]? = await cloudbase.request(\n//         method: \"GET\",\n//         path: \"/v1/rdb/rest/{%TABLE_NAME%}?select=*&limit=10\"\n//     )\n//     print(result)\n// }\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```swift\nfunc addPgData(cloudbase: CloudBaseClient, tableName: String, data: [String: Any], completion: @escaping ([String: Any]?) -> Void) {\n    // Insert data into {%TABLE_NAME%}\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/rdb/rest/\\(tableName)\",\n        body: data\n    ) { (result: [String: Any]?) in\n        if let result = result {\n            print(\"Insert success: \\(result)\")\n        }\n        completion(result)\n    }\n}\n\n// Usage example (async/await)\n// Task {\n//     let result: [String: Any]? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/rdb/rest/{%TABLE_NAME%}\",\n//         body: [\"title\": \"Example title\"]\n//     )\n//     print(result)\n// }\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```swift\nfunc updatePgData(cloudbase: CloudBaseClient, tableName: String, dataId: String, data: [String: Any], completion: @escaping (Any?) -> Void) {\n    // Update record in {%TABLE_NAME%}\n    cloudbase.request(\n        method: \"PATCH\",\n        path: \"/v1/rdb/rest/\\(tableName)?id=eq.\\(dataId)\",\n        body: data\n    ) { (result: Any?) in\n        if result != nil {\n            print(\"Update success: \\(result ?? \"\")\")\n        }\n        completion(result)\n    }\n}\n\n// Usage example (async/await)\n// Task {\n//     let result: Any? = await cloudbase.request(\n//         method: \"PATCH\",\n//         path: \"/v1/rdb/rest/{%TABLE_NAME%}?id=eq.<record_id>\",\n//         body: [\"title\": \"New title\"]\n//     )\n//     print(result)\n// }\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```swift\nfunc upsertPgData(cloudbase: CloudBaseClient, tableName: String, data: [String: Any], completion: @escaping (Any?) -> Void) {\n    // Update record in {%TABLE_NAME%}\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/rdb/rest/\\(tableName)\",\n        body: data\n    ) { (result: Any?) in\n        if result != nil {\n            print(\"Upsert success: \\(result ?? \"\")\")\n        }\n        completion(result)\n    }\n}\n\n// Usage example (async/await)\n// Task {\n//     let result: Any? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/rdb/rest/{%TABLE_NAME%}\",\n//         body: [\"id\": 1, \"title\": \"Example title\"]\n//     )\n//     print(result)\n// }\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```swift\nfunc deletePgData(cloudbase: CloudBaseClient, tableName: String, dataId: String, completion: @escaping (Bool) -> Void) {\n    // Delete record from {%TABLE_NAME%}\n    cloudbase.request(\n        method: \"DELETE\",\n        path: \"/v1/rdb/rest/\\(tableName)?id=eq.\\(dataId)\"\n    ) { (result: Bool?) in\n        if result == true {\n            print(\"Delete success\")\n            completion(true)\n        } else {\n            completion(false)\n        }\n    }\n}\n\n// Usage example (async/await)\n// Task {\n//     let result: Bool? = await cloudbase.request(\n//         method: \"DELETE\",\n//         path: \"/v1/rdb/rest/{%TABLE_NAME%}?id=eq.<record_id>\"\n//     )\n//     print(result ?? false)\n// }\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```swift\nfunc getMysqlData(cloudbase: CloudBaseClient, tableName: String, completion: @escaping ([[String: Any]]?) -> Void) {\n    // Query MySQL database data\n    cloudbase.request(\n        method: \"GET\",\n        path: \"/v1/rdb/rest/\\(tableName)?limit=10\"\n    ) { (data: [[String: Any]]?) in\n        if let data = data {\n            print(\"Querysuccessful: \\(data)\")\n        }\n        completion(data ?? [])\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [[String: Any]]? = await cloudbase.request(\n//         method: \"GET\",\n//         path: \"/v1/rdb/rest/{%TABLE_NAME%}?limit=10\"\n//     )\n//     print(result)\n// }\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```swift\nfunc addMysqlData(cloudbase: CloudBaseClient, tableName: String, data: [String: Any], completion: @escaping ([String: Any]?) -> Void) {\n    // Add MySQL database data\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/rdb/rest/\\(tableName)\",\n        body: data\n    ) { (result: [String: Any]?) in\n        if let result = result {\n            print(\"Insert successful: \\(result)\")\n        }\n        completion(result)\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [String: Any]? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/rdb/rest/{%TABLE_NAME%}\",\n//         body: [\"title\": \"Example Title\"]\n//     )\n//     print(result)\n// }\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```swift\nfunc updateMysqlData(cloudbase: CloudBaseClient, tableName: String, dataId: String, data: [String: Any], completion: @escaping (Any?) -> Void) {\n    // Update MySQL database data\n    cloudbase.request(\n        method: \"PATCH\",\n        path: \"/v1/rdb/rest/\\(tableName)?id=eq.\\(dataId)\",\n        body: data\n    ) { (result: Any?) in\n        if result != nil {\n            print(\"Update successful: \\(result ?? \"\")\")\n        }\n        completion(result)\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: Any? = await cloudbase.request(\n//         method: \"PATCH\",\n//         path: \"/v1/rdb/rest/{%TABLE_NAME%}?id=eq.<data id>\",\n//         body: [\"title\": \"New Title\"]\n//     )\n//     print(result)\n// }\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```swift\nfunc deleteMysqlData(cloudbase: CloudBaseClient, tableName: String, dataId: String, completion: @escaping (Bool) -> Void) {\n    // Delete MySQL database data\n    cloudbase.request(\n        method: \"DELETE\",\n        path: \"/v1/rdb/rest/\\(tableName)?id=eq.\\(dataId)\"\n    ) { (result: Bool?) in\n        if result == true {\n            print(\"Delete successful\")\n            completion(true)\n        } else {\n            completion(false)\n        }\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: Bool? = await cloudbase.request(\n//         method: \"DELETE\",\n//         path: \"/v1/rdb/rest/{%TABLE_NAME%}?id=eq.<data id>\"\n//     )\n//     print(result ?? false)\n// }\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```swift\nfunc getModelData(cloudbase: CloudBaseClient, modelName: String, envType: String = \"prod\", completion: @escaping ([[String: Any]]) -> Void) {\n    // QueryData ModelData\n    let payload: [String: Any] = [\n        \"pageSize\": 10,\n        \"pageNumber\": 1,\n        \"getCount\": true\n    ]\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/model/\\(envType)/\\(modelName)/list\",\n        body: payload\n    ) { (result: [String: Any]?) in\n        if let result = result,\n           let data = result[\"data\"] as? [String: Any],\n           let records = data[\"records\"] as? [[String: Any]] {\n            print(\"Querysuccessful: \\(records)\")\n            completion(records)\n        } else {\n            completion([])\n        }\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [String: Any]? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/model/prod/{%TABLE_NAME%}/list\",\n//         body: [\"pageSize\": 10, \"pageNumber\": 1, \"getCount\": true]\n//     )\n//     print(result)\n// }\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```swift\nfunc addModelData(cloudbase: CloudBaseClient, modelName: String, data: [String: Any], envType: String = \"prod\", completion: @escaping ([String: Any]?) -> Void) {\n    // AddData ModelData\n    let payload: [String: Any] = [\"data\": data]\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/model/\\(envType)/\\(modelName)/create\",\n        body: payload\n    ) { (result: [String: Any]?) in\n        if let result = result,\n           let data = result[\"data\"] as? [String: Any],\n           let docId = data[\"id\"] {\n            print(\"Insert successful! id: \\(docId)\")\n        }\n        completion(result)\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [String: Any]? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/model/prod/{%TABLE_NAME%}/create\",\n//         body: [\"data\": [\"title\": \"Example Title\"]]\n//     )\n//     print(result)\n// }\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```swift\nfunc updateModelData(cloudbase: CloudBaseClient, modelName: String, dataId: String, data: [String: Any], envType: String = \"prod\", completion: @escaping (Bool) -> Void) {\n    // UpdateData ModelData\n    let payload: [String: Any] = [\n        \"data\": data,\n        \"filter\": [\n            \"where\": [\n                \"_id\": [\"$eq\": dataId]\n            ]\n        ]\n    ]\n\n    cloudbase.request(\n        method: \"PUT\",\n        path: \"/v1/model/\\(envType)/\\(modelName)/update\",\n        body: payload\n    ) { (result: Any?) in\n        if result != nil {\n            print(\"Update successful!\")\n            completion(true)\n        } else {\n            completion(false)\n        }\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let payload: [String: Any] = [\n//         \"data\": [\"title\": \"New Title\"],\n//         \"filter\": [\"where\": [\"_id\": [\"$eq\": \"<data id>\"]]]\n//     ]\n//     let result: Any? = await cloudbase.request(\n//         method: \"PUT\",\n//         path: \"/v1/model/prod/{%TABLE_NAME%}/update\",\n//         body: payload\n//     )\n//     print(result != nil)\n// }\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```swift\nfunc deleteModelData(cloudbase: CloudBaseClient, modelName: String, dataId: String, envType: String = \"prod\", completion: @escaping (Bool) -> Void) {\n    // DeleteData ModelData\n    let payload: [String: Any] = [\n        \"filter\": [\n            \"where\": [\n                \"_id\": [\"$eq\": dataId]\n            ]\n        ]\n    ]\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/model/\\(envType)/\\(modelName)/delete\",\n        body: payload\n    ) { (result: Any?) in\n        if result != nil {\n            print(\"Delete successful!\")\n            completion(true)\n        } else {\n            completion(false)\n        }\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let payload: [String: Any] = [\n//         \"filter\": [\"where\": [\"_id\": [\"$eq\": \"<data id>\"]]]\n//     ]\n//     let result: Any? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/model/prod/{%TABLE_NAME%}/delete\",\n//         body: payload\n//     )\n//     print(result != nil)\n// }\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```swift\nfunc callFunction(cloudbase: CloudBaseClient, functionName: String, data: [String: Any]? = nil, completion: @escaping ([String: Any]?) -> Void) {\n    // CallCloud Function\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/functions/\\(functionName)\",\n        body: data ?? [:]\n    ) { (result: [String: Any]?) in\n        if let result = result {\n            print(\"Cloud function call result: \\(result)\")\n        }\n        completion(result)\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [String: Any]? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/functions/{%FUNCTION_NAME%}\",\n//         body: [:]\n//     )\n//     print(result)\n// }\n```",
            "index": 3,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```swift\nfunc callContainer(cloudbase: CloudBaseClient, serviceName: String, path: String = \"\", method: String = \"GET\", data: [String: Any]? = nil, completion: @escaping (Any?) -> Void) {\n    // CallCloud Runservice\n    var fullPath = \"/v1/cloudrun/\\(serviceName)/\\(path)\"\n    if fullPath.hasSuffix(\"/\") {\n        fullPath = String(fullPath.dropLast())\n    }\n\n    cloudbase.request(\n        method: method.uppercased(),\n        path: fullPath,\n        body: data\n    ) { (result: Any?) in\n        if let result = result {\n            print(\"Cloud RunCallResult: \\(result)\")\n        }\n        completion(result)\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: Any? = await cloudbase.request(\n//         method: \"GET\",\n//         path: \"/v1/cloudrun/{%SERVICE_NAME%}\"\n//     )\n//     print(result)\n// }\n```",
            "index": 4,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```swift\nfunc uploadFile(cloudbase: CloudBaseClient, filePath: String, objectId: String? = nil, completion: @escaping ([String: String]?) -> Void) {\n    // Upload FiletoCloud Storage\n    guard let fileUrl = URL(string: filePath),\n          let fileData = try? Data(contentsOf: fileUrl) else {\n        print(\"filedoes not exist: \\(filePath)\")\n        completion(nil)\n        return\n    }\n\n    let filename = fileUrl.lastPathComponent\n    let timestamp = Int(Date().timeIntervalSince1970 * 1000)\n    let finalObjectId = objectId ?? \"uploads/\\(timestamp)-\\(filename)\"\n\n    // 1. Get upload info\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/storages/get-objects-upload-info\",\n        body: [[\"objectId\": finalObjectId]]\n    ) { (uploadInfo: [[String: Any]]?) in\n        guard let uploadInfo = uploadInfo, !uploadInfo.isEmpty else {\n            completion(nil)\n            return\n        }\n\n        let info = uploadInfo[0]\n        guard let uploadUrl = info[\"uploadUrl\"] as? String,\n              let authorization = info[\"authorization\"] as? String,\n              let token = info[\"token\"] as? String,\n              let cloudObjectMeta = info[\"cloudObjectMeta\"] as? String else {\n            completion(nil)\n            return\n        }\n\n        // 2. Upload File\n        guard let url = URL(string: uploadUrl) else {\n            completion(nil)\n            return\n        }\n\n        var request = URLRequest(url: url)\n        request.httpMethod = \"PUT\"\n        request.setValue(authorization, forHTTPHeaderField: \"Authorization\")\n        request.setValue(token, forHTTPHeaderField: \"X-Cos-Security-Token\")\n        request.setValue(cloudObjectMeta, forHTTPHeaderField: \"X-Cos-Meta-Fileid\")\n        request.httpBody = fileData\n\n        let task = URLSession.shared.dataTask(with: request) { _, response, error in\n            if let error = error {\n                print(\"fileUploadfailed: \\(error.localizedDescription)\")\n                completion(nil)\n                return\n            }\n\n            guard let httpResponse = response as? HTTPURLResponse,\n                  (200...299).contains(httpResponse.statusCode) else {\n                print(\"fileUploadfailed\")\n                completion(nil)\n                return\n            }\n\n            let result = [\n                \"cloudObjectId\": info[\"cloudObjectId\"] as? String ?? \"\",\n                \"downloadUrl\": info[\"downloadUrl\"] as? String ?? \"\",\n                \"objectId\": finalObjectId\n            ]\n\n            print(\"fileUpload successful:\")\n            print(\"- Object ID: \\(result[\"objectId\"] ?? \"\")\")\n            print(\"- DownloadURL: \\(result[\"downloadUrl\"] ?? \"\")\")\n\n            completion(result)\n        }\n\n        task.resume()\n    }\n}\n\n// Usage Example\n// uploadFile(cloudbase: cloudbase, filePath: \"./example.jpg\") { result in\n//     print(result)\n// }\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```swift\nfunc getFileUrl(cloudbase: CloudBaseClient, cloudObjectId: String, completion: @escaping (String?) -> Void) {\n    // GetCloud Storagefiletemporary accessURL\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/storages/get-objects-download-info\",\n        body: [[\"cloudObjectId\": cloudObjectId]]\n    ) { (result: [[String: Any]]?) in\n        if let result = result, !result.isEmpty,\n           let downloadUrl = result[0][\"downloadUrl\"] as? String {\n            print(\"fileURL: \\(downloadUrl)\")\n            completion(downloadUrl)\n        } else {\n            completion(nil)\n        }\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [[String: Any]]? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/storages/get-objects-download-info\",\n//         body: [[\"cloudObjectId\": \"cloud://xxx.png\"]]\n//     )\n//     if let downloadUrl = result?.first?[\"downloadUrl\"] as? String {\n//         print(downloadUrl)\n//     }\n// }\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```swift\nfunc downloadFile(cloudbase: CloudBaseClient, cloudObjectId: String, savePath: String = \"./\", completion: @escaping (Bool) -> Void) {\n    // DownloadCloud Storagefiletolocal\n    // 1. GetDownloadURL\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/storages/get-objects-download-info\",\n        body: [[\"cloudObjectId\": cloudObjectId]]\n    ) { (result: [[String: Any]]?) in\n        guard let result = result, !result.isEmpty,\n              let downloadUrl = result[0][\"downloadUrl\"] as? String else {\n            completion(false)\n            return\n        }\n\n        guard let url = URL(string: downloadUrl) else {\n            completion(false)\n            return\n        }\n\n        // 2. Download File\n        let task = URLSession.shared.downloadTask(with: url) { tempUrl, _, error in\n            if let error = error {\n                print(\"Downloadfailed: \\(error.localizedDescription)\")\n                completion(false)\n                return\n            }\n\n            guard let tempUrl = tempUrl else {\n                completion(false)\n                return\n            }\n\n            // 3. DetermineSavePath\n            let filename = url.lastPathComponent.components(separatedBy: \"?\").first ?? \"file\"\n            let fileManager = FileManager.default\n            var fullPath: URL\n\n            if savePath.hasSuffix(\"/\") {\n                fullPath = URL(fileURLWithPath: savePath).appendingPathComponent(filename)\n            } else {\n                fullPath = URL(fileURLWithPath: savePath)\n            }\n\n            // 4. Savefile\n            do {\n                if fileManager.fileExists(atPath: fullPath.path) {\n                    try fileManager.removeItem(at: fullPath)\n                }\n                try fileManager.moveItem(at: tempUrl, to: fullPath)\n                print(\"Downloadsuccessful! filesaved to: \\(fullPath.path)\")\n                completion(true)\n            } catch {\n                print(\"Downloadfailed: \\(error.localizedDescription)\")\n                completion(false)\n            }\n        }\n\n        task.resume()\n    }\n}\n\n// Usage Example\n// downloadFile(cloudbase: cloudbase, cloudObjectId: \"cloud://xxx.png\", savePath: \"./downloads/\") { success in\n//     print(success)\n// }\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```swift\nfunc deleteFile(cloudbase: CloudBaseClient, cloudObjectIds: Any, completion: @escaping (Bool) -> Void) {\n    // DeleteCloud Storagefile\n    var ids: [String] = []\n\n    if let idString = cloudObjectIds as? String {\n        ids = [idString]\n    } else if let idArray = cloudObjectIds as? [String] {\n        ids = idArray\n    } else {\n        print(\"Parameter type error\")\n        completion(false)\n        return\n    }\n\n    let data = ids.map { [\"cloudObjectId\": $0] }\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/storages/delete-objects\",\n        body: data\n    ) { (result: Any?) in\n        if result != nil {\n            print(\"Delete successful!\")\n            completion(true)\n        } else {\n            completion(false)\n        }\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let data = [[\"cloudObjectId\": \"cloud://xxx.png\"]]\n//     let result: Any? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/storages/delete-objects\",\n//         body: data\n//     )\n//     print(result != nil)\n// }\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```swift\nfunc streamText(cloudbase: CloudBaseClient, model: String, subModel: String, messages: [[String: String]], completion: @escaping (String?) -> Void) {\n    // streamingtextthisGenerate\n    let payload: [String: Any] = [\n        \"model\": subModel,\n        \"messages\": messages,\n        \"stream\": true\n    ]\n\n    guard let url = URL(string: \"\\(cloudbase.baseUrl)/v1/ai/\\(model)/chat/completions\") else {\n        completion(nil)\n        return\n    }\n\n    var request = URLRequest(url: url)\n    request.httpMethod = \"POST\"\n    request.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n    request.setValue(\"text/event-stream\", forHTTPHeaderField: \"Accept\")\n    request.setValue(\"Bearer \\(cloudbase.accessToken)\", forHTTPHeaderField: \"Authorization\")\n\n    do {\n        request.httpBody = try JSONSerialization.data(withJSONObject: payload)\n    } catch {\n        print(\"JSONSerializefailed: \\(error)\")\n        completion(nil)\n        return\n    }\n\n    let task = URLSession.shared.dataTask(with: request) { data, response, error in\n        if let error = error {\n            print(\"AI Call failed: \\(error.localizedDescription)\")\n            completion(nil)\n            return\n        }\n\n        guard let data = data,\n              let responseString = String(data: data, encoding: .utf8) else {\n            completion(nil)\n            return\n        }\n\n        print(\"AI Streaming response:\")\n        var fullContent = \"\"\n\n        let lines = responseString.components(separatedBy: \"\\n\")\n        for line in lines {\n            if line.hasPrefix(\"data: \") {\n                let dataStr = String(line.dropFirst(6))\n                if dataStr.trimmingCharacters(in: .whitespaces) != \"[DONE]\" {\n                    if let data = dataStr.data(using: .utf8),\n                       let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],\n                       let choices = json[\"choices\"] as? [[String: Any]],\n                       let delta = choices.first?[\"delta\"] as? [String: Any],\n                       let content = delta[\"content\"] as? String {\n                        print(content, terminator: \"\")\n                        fullContent += content\n                    }\n                }\n            }\n        }\n\n        print()\n        completion(fullContent)\n    }\n\n    task.resume()\n}\n\n// Usage Example\n// streamText(\n//     cloudbase: cloudbase,\n//     model: \"{%AI_MODEL_NAME%}\",\n//     subModel: \"{%AI_SUB_MODEL_NAME%}\",\n//     messages: [\n//         [\"role\": \"system\", \"content\": \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create\"],\n//         [\"role\": \"user\", \"content\": \"Spring\"]\n//     ]\n// ) { response in\n//     print(\"\\nComplete response: \\(response ?? \"\")\")\n// }\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```swift\nfunc generateImage(cloudbase: CloudBaseClient, prompt: String, completion: @escaping ([String: Any]?) -> Void) {\n    // PrepareCallparameter\n    let data: [String: Any] = [\"prompt\": prompt]\n    \n    // CallCloud FunctionGenerate Image\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/functions/<YOUR_FUNCTION_NAME>\",\n        body: data\n    ) { (result: [String: Any]?) in\n        if let result = result {\n            if let success = result[\"success\"] as? Bool, success {\n                let imageUrl = result[\"imageUrl\"] as? String ?? \"\"\n                let revisedPrompt = result[\"revised_prompt\"] as? String ?? \"\"\n                \n                print(\"Generation successful!\")\n                print(\"Image URL: \\(imageUrl)\")\n                print(\"Optimized prompt: \\(revisedPrompt)\")\n                print(\"Note: Image URLValidis valid for24hours\")\n                \n                completion(result)\n            } else {\n                let code = result[\"code\"] as? String ?? \"\"\n                let message = result[\"message\"] as? String ?? \"\"\n                print(\"Generation failed: \\(code) - \\(message)\")\n                completion(nil)\n            }\n        } else {\n            print(\"Requestfailed\")\n            completion(nil)\n        }\n    }\n}\n\n// Usage Example\n// generateImage(cloudbase: cloudbase, prompt: \"A cute cat playing in the sunshine\") { result in\n//     if let result = result {\n//         print(\"ImageGenerateDone: \\(result)\")\n//     }\n// }\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```swift\n/**\n * iOS Swift Call Agent Example (AG-UI Protocol)\n * Protocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n */\nfunc chatWithAgentStream(cloudbase: CloudBaseClient, botId: String, userMessage: String, completion: @escaping (String?) -> Void) {\n    // Build message list (AG-UI protocol format)\n    let messages: [[String: Any]] = [\n        [\n            \"id\": \"msg_001\",\n            \"role\": \"user\",\n            \"content\": userMessage\n        ]\n    ]\n\n    // AG-UI Protocol request parameters\n    let payload: [String: Any] = [\n        \"messages\": messages,                                    // Required: Message list\n        \"threadId\": \"550e8400-e29b-41d4-a716-446655440000\",     // Optional: Session ID for multi-turn conversation\n        \"runId\": \"run_001\",                                      // Optional: Run ID for execution tracking\n        \"tools\": [],                                             // Optional: Frontend tool definitions\n        \"context\": [],                                           // Optional: Context information\n        \"forwardedProps\": [:]                                    // Optional: Pass-through parameters\n    ]\n\n    guard let url = URL(string: \"\\(cloudbase.baseUrl)/v1/aibot/bots/\\(botId)/send-message\") else {\n        completion(nil)\n        return\n    }\n\n    var request = URLRequest(url: url)\n    request.httpMethod = \"POST\"\n    request.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n    request.setValue(\"text/event-stream\", forHTTPHeaderField: \"Accept\")\n    request.setValue(\"Bearer \\(cloudbase.accessToken)\", forHTTPHeaderField: \"Authorization\")\n\n    do {\n        request.httpBody = try JSONSerialization.data(withJSONObject: payload)\n    } catch {\n        print(\"JSONSerializefailed: \\(error)\")\n        completion(nil)\n        return\n    }\n\n    let task = URLSession.shared.dataTask(with: request) { data, response, error in\n        if let error = error {\n            print(\"AI Call failed: \\(error.localizedDescription)\")\n            completion(nil)\n            return\n        }\n\n        guard let data = data,\n              let responseString = String(data: data, encoding: .utf8) else {\n            completion(nil)\n            return\n        }\n\n        print(\"AI Streaming response:\")\n        var fullContent = \"\"\n\n        let lines = responseString.components(separatedBy: \"\\n\")\n        for line in lines {\n            if line.hasPrefix(\"data: \") {\n                let dataStr = String(line.dropFirst(6)).trimmingCharacters(in: .whitespaces)\n                if !dataStr.isEmpty && dataStr != \"[DONE]\" {\n                    if let data = dataStr.data(using: .utf8),\n                       let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {\n                        var content = \"\"\n\n                        if let directContent = json[\"content\"] as? String {\n                            content = directContent\n                        } else if let choices = json[\"choices\"] as? [[String: Any]] {\n                            if let delta = choices.first?[\"delta\"] as? [String: Any],\n                               let deltaContent = delta[\"content\"] as? String {\n                                content = deltaContent\n                            } else if let message = choices.first?[\"message\"] as? [String: Any],\n                                      let messageContent = message[\"content\"] as? String {\n                                content = messageContent\n                            }\n                        }\n\n                        if !content.isEmpty {\n                            print(content, terminator: \"\")\n                            fullContent += content\n                        }\n                    }\n                }\n            }\n        }\n\n        print()\n        completion(fullContent)\n    }\n\n    task.resume()\n}\n\n// Usage Example\n// chatWithAgentStream(cloudbase: cloudbase, botId: \"{%AGENT_ID%}\", userMessage: \"Who are you\") { response in\n//     print(\"\\nComplete response: \\(response ?? \"\")\")\n// }\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```swift\nfunc chatWithAgentStream(cloudbase: CloudBaseClient, botId: String, msg: String, history: [[String: String]]? = nil, completion: @escaping (String?) -> Void) {\n    // streamingCallAgent\n    let payload: [String: Any] = [\n        \"history\": history ?? [],\n        \"msg\": msg\n    ]\n\n    guard let url = URL(string: \"\\(cloudbase.baseUrl)/v1/aibot/bots/\\(botId)/send-message\") else {\n        completion(nil)\n        return\n    }\n\n    var request = URLRequest(url: url)\n    request.httpMethod = \"POST\"\n    request.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n    request.setValue(\"text/event-stream\", forHTTPHeaderField: \"Accept\")\n    request.setValue(\"Bearer \\(cloudbase.accessToken)\", forHTTPHeaderField: \"Authorization\")\n\n    do {\n        request.httpBody = try JSONSerialization.data(withJSONObject: payload)\n    } catch {\n        print(\"JSONSerializefailed: \\(error)\")\n        completion(nil)\n        return\n    }\n\n    let task = URLSession.shared.dataTask(with: request) { data, response, error in\n        if let error = error {\n            print(\"AI Call failed: \\(error.localizedDescription)\")\n            completion(nil)\n            return\n        }\n\n        guard let data = data,\n              let responseString = String(data: data, encoding: .utf8) else {\n            completion(nil)\n            return\n        }\n\n        print(\"AI Streaming response:\")\n        var fullContent = \"\"\n\n        let lines = responseString.components(separatedBy: \"\\n\")\n        for line in lines {\n            if line.hasPrefix(\"data: \") {\n                let dataStr = String(line.dropFirst(6)).trimmingCharacters(in: .whitespaces)\n                if !dataStr.isEmpty && dataStr != \"[DONE]\" {\n                    if let data = dataStr.data(using: .utf8),\n                       let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {\n                        var content = \"\"\n\n                        if let directContent = json[\"content\"] as? String {\n                            content = directContent\n                        } else if let choices = json[\"choices\"] as? [[String: Any]] {\n                            if let delta = choices.first?[\"delta\"] as? [String: Any],\n                               let deltaContent = delta[\"content\"] as? String {\n                                content = deltaContent\n                            } else if let message = choices.first?[\"message\"] as? [String: Any],\n                                      let messageContent = message[\"content\"] as? String {\n                                content = messageContent\n                            }\n                        }\n\n                        if !content.isEmpty {\n                            print(content, terminator: \"\")\n                            fullContent += content\n                        }\n                    }\n                }\n            }\n        }\n\n        print()\n        completion(fullContent)\n    }\n\n    task.resume()\n}\n\n// Usage Example\n// chatWithAgentStream(cloudbase: cloudbase, botId: \"{%AGENT_ID%}\", msg: \"Who are you\") { response in\n//     print(\"\\nComplete response: \\(response ?? \"\")\")\n// }\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 8,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```swift\nfunc signUpWithPhoneCode(cloudbase: CloudBaseClient, phoneNumber: String, verificationCode: String, username: String? = nil, password: String? = nil, captchaToken: String? = nil, completion: @escaping ([String: Any]?) -> Void) {\n    // Step1: SendSMSVerification code\n    var body: [String: Any] = [\n        \"phone_number\": phoneNumber.hasPrefix(\"+86\") ? phoneNumber : \"+86\\(phoneNumber)\",\n        \"target\": \"NON_USER\"  // \"NON_USER\" - Accountdoes not existthenSend; \"ANY\" - No restriction\n    ]\n\n    var headers: [String: String] = [:]\n    if let token = captchaToken {\n        headers[\"x-captcha-token\"] = token\n    }\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/auth/v1/verification\",\n        body: body,\n        customHeaders: headers\n    ) { (sendResult: [String: Any]?) in\n        guard let sendResult = sendResult,\n              let verificationId = sendResult[\"verification_id\"] as? String else {\n            print(\"Send Codefailed\")\n            completion(nil)\n            return\n        }\n\n        print(\"Verification codeSendsuccessful! ID: \\(verificationId)\")\n\n        // Step2: Verify the code\n        cloudbase.request(\n            method: \"POST\",\n            path: \"/auth/v1/verification/verify\",\n            body: [\n                \"verification_id\": verificationId,\n                \"verification_code\": verificationCode\n            ]\n        ) { (verifyResult: [String: Any]?) in\n            guard let verifyResult = verifyResult,\n                  let verificationToken = verifyResult[\"verification_token\"] as? String else {\n                print(\"Verification codeError\")\n                completion(nil)\n                return\n            }\n\n            print(\"Verifysuccessful!\")\n\n            // Step3: UseVerifytokenRegister\n            var signUpBody: [String: Any] = [\n                \"phone_number\": phoneNumber.hasPrefix(\"+86\") ? phoneNumber : \"+86\\(phoneNumber)\",\n                \"verification_token\": verificationToken\n            ]\n\n            // Optional：AddUsernameandPassword\n            if let username = username {\n                signUpBody[\"username\"] = username\n            }\n            if let password = password {\n                signUpBody[\"password\"] = password\n            }\n\n            cloudbase.request(\n                method: \"POST\",\n                path: \"/auth/v1/signup\",\n                body: signUpBody\n            ) { (signUpResult: [String: Any]?) in\n                if let signUpResult = signUpResult,\n                   let accessToken = signUpResult[\"access_token\"] as? String,\n                   let userId = signUpResult[\"sub\"] as? String {\n                    print(\"Registration successful! User ID: \\(userId)\")\n                    print(\"Access token: \\(String(accessToken.prefix(20)))...\")\n\n                    // UpdateAccess token\n                    cloudbase.updateAccessToken(accessToken)\n                    completion(signUpResult)\n                } else {\n                    print(\"Registration failed\")\n                    completion(nil)\n                }\n            }\n        }\n    }\n}\n\n// Usage Example\n// signUpWithPhoneCode(\n//     cloudbase: cloudbase,\n//     phoneNumber: \"13800138000\",\n//     verificationCode: \"123456\",\n//     username: \"myusername\",\n//     password: \"mypassword\"\n// ) { result in\n//     if result != nil {\n//         print(\"Phone numberRegistration successful\")\n//     }\n// }\n```",
                "index": 1,
                "title": "SMS Code Registration",
                "content": []
              },
              {
                "markdown": "```swift\nfunc signUpWithEmailCode(cloudbase: CloudBaseClient, email: String, verificationCode: String, username: String? = nil, password: String? = nil, captchaToken: String? = nil, completion: @escaping ([String: Any]?) -> Void) {\n    // Step1: SendEmailVerification code\n    var body: [String: Any] = [\n        \"email\": email,\n        \"target\": \"NON_USER\"  // \"NON_USER\" - Accountdoes not existthenSend; \"ANY\" - No restriction\n    ]\n\n    var headers: [String: String] = [:]\n    if let token = captchaToken {\n        headers[\"x-captcha-token\"] = token\n    }\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/auth/v1/verification\",\n        body: body,\n        customHeaders: headers\n    ) { (sendResult: [String: Any]?) in\n        guard let sendResult = sendResult,\n              let verificationId = sendResult[\"verification_id\"] as? String else {\n            print(\"Send Codefailed\")\n            completion(nil)\n            return\n        }\n\n        print(\"Verification codeSendsuccessful! ID: \\(verificationId)\")\n\n        // Step2: Verify the code\n        cloudbase.request(\n            method: \"POST\",\n            path: \"/auth/v1/verification/verify\",\n            body: [\n                \"verification_id\": verificationId,\n                \"verification_code\": verificationCode\n            ]\n        ) { (verifyResult: [String: Any]?) in\n            guard let verifyResult = verifyResult,\n                  let verificationToken = verifyResult[\"verification_token\"] as? String else {\n                print(\"Verification codeError\")\n                completion(nil)\n                return\n            }\n\n            print(\"Verifysuccessful!\")\n\n            // Step3: UseVerifytokenRegister\n            var signUpBody: [String: Any] = [\n                \"email\": email,\n                \"verification_token\": verificationToken\n            ]\n\n            // Optional：AddUsernameandPassword\n            if let username = username {\n                signUpBody[\"username\"] = username\n            }\n            if let password = password {\n                signUpBody[\"password\"] = password\n            }\n\n            cloudbase.request(\n                method: \"POST\",\n                path: \"/auth/v1/signup\",\n                body: signUpBody\n            ) { (signUpResult: [String: Any]?) in\n                if let signUpResult = signUpResult,\n                   let accessToken = signUpResult[\"access_token\"] as? String,\n                   let userId = signUpResult[\"sub\"] as? String {\n                    print(\"Registration successful! User ID: \\(userId)\")\n                    print(\"Access token: \\(String(accessToken.prefix(20)))...\")\n\n                    // UpdateAccess token\n                    cloudbase.updateAccessToken(accessToken)\n                    completion(signUpResult)\n                } else {\n                    print(\"Registration failed\")\n                    completion(nil)\n                }\n            }\n        }\n    }\n}\n\n// Usage Example\n// signUpWithEmailCode(\n//     cloudbase: cloudbase,\n//     email: \"user@example.com\",\n//     verificationCode: \"123456\",\n//     username: \"myusername\",\n//     password: \"mypassword\"\n// ) { result in\n//     if result != nil {\n//         print(\"EmailRegistration successful\")\n//     }\n// }\n```",
                "index": 2,
                "title": "Email Code Registration",
                "content": []
              },
              {
                "markdown": "```swift\nfunc signIn(cloudbase: CloudBaseClient, username: String, password: String, completion: @escaping ([String: Any]?) -> Void) {\n    // Username Password Login\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/auth/v1/signin\",\n        body: [\"username\": username, \"password\": password]\n    ) { (result: [String: Any]?) in\n        if let result = result,\n           let accessToken = result[\"access_token\"] as? String,\n           let userId = result[\"sub\"] as? String {\n            print(\"Login successful! User ID: \\(userId)\")\n            print(\"Access token: \\(String(accessToken.prefix(20)))...\")\n\n            // UpdateAccess token\n            cloudbase.updateAccessToken(accessToken)\n        }\n        completion(result)\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [String: Any]? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/auth/v1/signin\",\n//         body: [\"username\": \"your_username\", \"password\": \"your_password\"]\n//     )\n//     if let result = result,\n//        let accessToken = result[\"access_token\"] as? String {\n//         // UpdateAccess token\n//         cloudbase.updateAccessToken(accessToken)\n//     }\n//     print(result)\n// }\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login",
                "content": []
              },
              {
                "markdown": "```swift\nfunc loginWithPhoneCode(cloudbase: CloudBaseClient, phoneNumber: String, verificationCode: String, captchaToken: String? = nil, completion: @escaping (Bool) -> Void) {\n    // Step1: SendSMSVerification code\n    var body: [String: Any] = [\n        \"phone_number\": phoneNumber.hasPrefix(\"+86\") ? phoneNumber : \"+86\\(phoneNumber)\",\n        \"target\": \"ANY\"  // \"ANY\" - No restriction，Noneregardless of userYesNoexistsallSend; \"USER\" - AccountmustexiststhenSend\n    ]\n\n    var headers: [String: String] = [:]\n    if let token = captchaToken {\n        headers[\"x-captcha-token\"] = token\n    }\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/auth/v1/verification\",\n        body: body,\n        customHeaders: headers\n    ) { (sendResult: [String: Any]?) in\n        guard let sendResult = sendResult,\n              let verificationId = sendResult[\"verification_id\"] as? String else {\n            print(\"Send Codefailed\")\n            completion(false)\n            return\n        }\n\n        print(\"Verification codeSendsuccessful! ID: \\(verificationId)\")\n\n        // Step2: Verify the code\n        cloudbase.request(\n            method: \"POST\",\n            path: \"/auth/v1/verification/verify\",\n            body: [\n                \"verification_id\": verificationId,\n                \"verification_code\": verificationCode\n            ]\n        ) { (verifyResult: [String: Any]?) in\n            guard let verifyResult = verifyResult,\n                  let verificationToken = verifyResult[\"verification_token\"] as? String else {\n                print(\"Verification codeError\")\n                completion(false)\n                return\n            }\n\n            print(\"Verifysuccessful!\")\n\n            // Step3: UseVerifytokenLogin\n            cloudbase.request(\n                method: \"POST\",\n                path: \"/auth/v1/signin\",\n                body: [\n                    \"phone_number\": phoneNumber.hasPrefix(\"+86\") ? phoneNumber : \"+86\\(phoneNumber)\",\n                    \"verification_token\": verificationToken\n                ]\n            ) { (loginResult: [String: Any]?) in\n                if let loginResult = loginResult,\n                   let accessToken = loginResult[\"access_token\"] as? String {\n                    print(\"Login successful!\")\n                    cloudbase.updateAccessToken(accessToken)\n                    completion(true)\n                } else {\n                    print(\"Login failed\")\n                    completion(false)\n                }\n            }\n        }\n    }\n}\n\n// Usage Example\n// loginWithPhoneCode(\n//     cloudbase: cloudbase,\n//     phoneNumber: \"13800138000\",\n//     verificationCode: \"123456\"\n// ) { success in\n//     if success {\n//         print(\"Phone numberLogin successful\")\n//     }\n// }\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login",
                "content": []
              },
              {
                "markdown": "```swift\nfunc loginWithEmailCode(cloudbase: CloudBaseClient, email: String, verificationCode: String, captchaToken: String? = nil, completion: @escaping (Bool) -> Void) {\n    // Step1: SendEmailVerification code\n    var body: [String: Any] = [\n        \"email\": email,\n        \"target\": \"ANY\"  // \"ANY\" - No restriction，Noneregardless of userYesNoexistsallSend; \"USER\" - AccountmustexiststhenSend\n    ]\n\n    var headers: [String: String] = [:]\n    if let token = captchaToken {\n        headers[\"x-captcha-token\"] = token\n    }\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/auth/v1/verification\",\n        body: body,\n        customHeaders: headers\n    ) { (sendResult: [String: Any]?) in\n        guard let sendResult = sendResult,\n              let verificationId = sendResult[\"verification_id\"] as? String else {\n            print(\"Send Codefailed\")\n            completion(false)\n            return\n        }\n\n        print(\"Verification codeSendsuccessful! ID: \\(verificationId)\")\n\n        // Step2: Verify the code\n        cloudbase.request(\n            method: \"POST\",\n            path: \"/auth/v1/verification/verify\",\n            body: [\n                \"verification_id\": verificationId,\n                \"verification_code\": verificationCode\n            ]\n        ) { (verifyResult: [String: Any]?) in\n            guard let verifyResult = verifyResult,\n                  let verificationToken = verifyResult[\"verification_token\"] as? String else {\n                print(\"Verification codeError\")\n                completion(false)\n                return\n            }\n\n            print(\"Verifysuccessful!\")\n\n            // Step3: UseVerifytokenLogin\n            cloudbase.request(\n                method: \"POST\",\n                path: \"/auth/v1/signin\",\n                body: [\n                    \"email\": email,\n                    \"verification_token\": verificationToken\n                ]\n            ) { (loginResult: [String: Any]?) in\n                if let loginResult = loginResult,\n                   let accessToken = loginResult[\"access_token\"] as? String {\n                    print(\"Login successful!\")\n                    cloudbase.updateAccessToken(accessToken)\n                    completion(true)\n                } else {\n                    print(\"Login failed\")\n                    completion(false)\n                }\n            }\n        }\n    }\n}\n\n// Usage Example\n// loginWithEmailCode(\n//     cloudbase: cloudbase,\n//     email: \"user@example.com\",\n//     verificationCode: \"123456\"\n// ) { success in\n//     if success {\n//         print(\"EmailLogin successful\")\n//     }\n// }\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login",
                "content": []
              }
            ]
          }
        ]
      }
    ],
    "_id": "2f6f1f4b697c28dd003a328b531072a0",
    "_openid": "anon",
    "createdAt": 1769744605450,
    "updatedAt": 1769766703341
  },
  {
    "category": "CloudBase MCP,OpenClaw",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 100,
    "hasTemplate": false,
    "content": [
      {
        "markdown": "Operate CloudBase resources through AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "tab",
        "content": []
      }
    ],
    "_id": "33956e3d69c0b84b013849d06ed29a68",
    "_openid": "1524963278340493312",
    "createdAt": 1774237770920,
    "updatedAt": 1774249053357
  },
  {
    "category": "CloudBase MCP,Baidu Comate",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 112,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/baidu-comate",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.baidu-comate/mcp.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Comate\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "3474fddf69a9286f004225b93cf8ad2c",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "Framework Integration,MiniProgram / MiniGame,MiniGame,Native API",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 2,
    "hasTemplate": false,
    "docsUrl": "https://developers.weixin.qq.com/minigame/dev/wxcloud/",
    "content": [
      {
        "markdown": "in `game.js` InitializeCloudBase：",
        "index": 1,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "mostCloudBasecapabilities canUse `Mini GameNative API` directlyCall，NoneneedInstall SDK，If `NativeAPI` Not supported pleaseUse `Client SDK` performCall\n\n```js\nwx.cloud.init({\n  env: \"{%ENV_ID%}\"\n});\n```",
            "index": 1,
            "title": "NativeAPI Initialize",
            "content": []
          },
          {
            "markdown": "**Install**\n\nUse Client SDK before please firstInstall SDK\n\ninMini Game `package.json` theinDirectory（usuallygamerootDirectory）execute：\n\n```bash\nnpm i @cloudbase/wx-cloud-client-sdk --save\n```\n\nInstallDoneafter，inWeChatClick in developer tools **tool → Build npm**。\n\n**Initialize**\n\n```js\nconst { init } = require(\"@cloudbase/wx-cloud-client-sdk\");\n\nwx.cloud.init({\n  env: \"{%ENV_ID%}\"\n});\n\nconst cloudbase = init(wx.cloud);\n```",
            "index": 2,
            "title": "Client SDK Initialize",
            "content": []
          }
        ]
      },
      {
        "index": 2,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "markdown": "pleaseUse `Client SDK` performCall",
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\n// Query {%TABLE_NAME%} table first 10 records\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n\nconsole.log(\"QueryResult:\", data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\n// Add {%TABLE_NAME%} table data\nconst { data, error } = await cloudbase.rdb().from(\"{%TABLE_NAME%}\").insert({\n  title: \"Example Title\"\n});\n\nconsole.log(\"AddResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\n// Update {%TABLE_NAME%} table id as <DataID> Data\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({\n    title: \"UpdateafterTitle\"\n  })\n  .eq(\"id\", \"<DataID>\");\n\nconsole.log(\"UpdateResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\n// If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Example Title\" });\n\nconsole.log(\"AddUpdateResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```js\n// Delete {%TABLE_NAME%} table id as <DataID> Data\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", \"<DataID>\");\n\nconsole.log(\"DeleteResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Query {%TABLE_NAME%} table first 10 records\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n\nconsole.log(res.data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Add {%TABLE_NAME%} table data\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({\n  data: {\n    title: \"Example Title\",\n    content: \"ExampleContent\"\n  }\n});\n\nconsole.log(res);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Update {%TABLE_NAME%} table id as <DataID> Data\nconst res = await db\n  .collection(\"{%TABLE_NAME%}\")\n  .doc(\"<DataID>\")\n  .update({\n    data: {\n      title: \"UpdateafterTitle\"\n    }\n  });\n\nconsole.log(res.stats.updated);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Delete {%TABLE_NAME%} table id as <DataID> Data\nconst res = await db.collection(\"{%TABLE_NAME%}\").doc(\"<DataID>\").remove();\n\nconsole.log(res.stats.removed);\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "pleaseUse `Client SDK` performCall",
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\n// Query {%TABLE_NAME%} Data Modelbefore10recordsData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\n\nconsole.log(res.data.records);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\n// Add {%TABLE_NAME%} Data ModelData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: {\n    title: \"Example Title\",\n    content: \"ExampleContent\"\n  }\n});\n\nconsole.log(res.data);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\n// Update {%TABLE_NAME%} Data Model _id as <DataID> Data\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: {\n    title: \"UpdateafterTitle\"\n  },\n  filter: {\n    where: {\n      _id: {\n        $eq: \"<DataID>\"\n      }\n    }\n  }\n});\n\nconsole.log(res.data);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\n// Delete {%TABLE_NAME%} Data Model _id as <DataID> Data\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: {\n    where: {\n      _id: {\n        $eq: \"<DataID>\"\n      }\n    }\n  }\n});\n\nconsole.log(res.data);\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "```js\n// Call {%FUNCTION_NAME%} Cloud Function\nconst res = await wx.cloud.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {} // Cloud Functioninput parameters\n});\n\nconsole.log(res.result);\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function",
            "content": []
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\n// Mini GamecanUse canvas Generate ImageorUseother methodsGetfilePath\nconst filePath = \"localfilePath\"; // for exampleUse canvas.toTempFilePath Get\n\nconst res = await wx.cloud.uploadFile({\n  cloudPath: \"images/\" + Date.now() + \".png\", // Path to upload in cloud\n  filePath: filePath // Mini GametemporaryfilePath\n});\n\nconsole.log(res.fileID);\n```",
                "index": 1,
                "title": "Upload File"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.getTempFileURL({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\n\nconsole.log(res.fileList);\n// fileListExample\n// [{\n//    fileID: \"cloud://xxx.png\", // file ID\n//    tempFileURL: \"https://xxx.png\", // temporaryfilenetworkURL\n//    maxAge: 120 * 60 * 1000, // Validperiod\n// }]\n```",
                "index": 2,
                "title": "Get File URL"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.downloadFile({\n  fileID: \"cloud://xxx.png\" // File fileID\n});\n\nconsole.log(res.tempFilePath); // ReturntemporaryfilePath\n```",
                "index": 3,
                "title": "Download File"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.deleteFile({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\n\nconsole.log(res.fileList);\n```",
                "index": 4,
                "title": "Delete File"
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst res = await wx.cloud.extend.AI.createModel(\n  \"{%AI_MODEL_NAME%}\"\n).streamText({\n  data: {\n    model: \"{%AI_SUB_MODEL_NAME%}\",\n    messages: [\n      {\n        role: \"user\",\n        content: \"Hello\"\n      }\n    ]\n  }\n});\n\nfor await (let event of res.eventStream) {\n  if (event.data === \"[DONE]\") {\n    break;\n  }\n  const data = JSON.parse(event.data);\n\n  // WhenUse deepseek-r1 when，model willGeneratereasoning chainContent\n  const think = data?.choices?.[0]?.delta?.reasoning_content;\n  if (think) {\n    console.log(think);\n  }\n\n  // Print generated text content\n  const text = data?.choices?.[0]?.delta?.content;\n  if (text) {\n    console.log(text);\n  }\n}\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation"
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```js\n// CallCloud FunctionGenerate Image\nwx.cloud.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: {\n    prompt: \"A cute cat playing in the sunshine\"\n  },\n  success: res => {\n    const result = res.result;\n    if (result.success) {\n      console.log(\"Image URL:\", result.imageUrl);\n      console.log(\"Optimized prompt:\", result.revised_prompt);\n      console.log(\"Note: Image URLValidis valid for24hours\");\n      \n      // inMini GamecanUseImage URLperformaftersubsequentProcess\n      // for exampleLoadtoSpriteorCanvas\n    } else {\n      console.error(\"Generation failed:\", result.code, result.message);\n    }\n  },\n  fail: err => {\n    console.error(\"Call failed:\", err);\n  }\n});\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation"
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst res = await wx.cloud.extend.AI.bot.sendMessage({\n  data: {\n    botId: '{%AGENT_ID%}',\n    // Refer to frontend-backend communication protocol for input structure：\n    //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n    threadId: '550e8400-e29b-41d4-a716-446655440000',\n    runId: 'run_001',\n    messages: [{ id: 'msg-1', role: 'user', content: 'Hello' }],\n    tools: [],\n    context: [],\n    state: {},\n    forwardedProps: {},\n  },\n});\n\nfor await (const event of res.eventStream) {\n  if (event.data === '[DONE]') {\n    break;\n  }\n  const data = JSON.parse(event.data);\n\n  // WhenUse deepseek-r1 when，model willGeneratereasoning chainContent\n  const think = data.reasoning_content;\n  if (think) {\n    console.log(think);\n  }\n\n  // Print output content\n  const content = data.content;\n  if (content) {\n    console.log(content);\n  }\n}\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.extend.AI.bot.sendMessage({\n  data: {\n    botId: \"{%AGENT_ID%}\",\n    msg: \"Hello\"\n  }\n});\n\nfor await (const event of res.eventStream) {\n  if (event.data === \"[DONE]\") {\n    break;\n  }\n  const data = JSON.parse(event.data);\n\n  // WhenUse deepseek-r1 when，model willGeneratereasoning chainContent\n  const think = data.reasoning_content;\n  if (think) {\n    console.log(think);\n  }\n\n  // Print output content\n  const content = data.content;\n  if (content) {\n    console.log(content);\n  }\n}\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          }
        ]
      }
    ],
    "_id": "3474fddf69a92871004225d163781d6f",
    "_openid": "anon",
    "createdAt": 1769767067406,
    "updatedAt": 1775130883079
  },
  {
    "category": "Framework Integration,ORMs,Prisma",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 41,
    "hasTemplate": false,
    "docsUrl": "https://prisma.org.cn/docs/getting-started/prisma-orm/quickstart/mysql",
    "content": [
      {
        "docsUrl": "",
        "markdown": "Use `Prisma` operate **MySQL Database**\n\nAdd the following code to your **Prisma** project",
        "title": "Modify Environment Variables",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```\nDATABASE_URL=mysql://{%DATABASE_URL%}\n```",
            "index": 2,
            "id": "mysqlString",
            "title": ".env"
          },
          {
            "markdown": "```prisma\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"mysql\"\n  url      = env(\"DATABASE_URL\")\n}\n```",
            "index": 1,
            "id": "",
            "title": "prisma/schema.prisma"
          }
        ]
      }
    ],
    "_id": "36e9b7bb697c28d40038bc570d8854a8",
    "_openid": "anon",
    "createdAt": 1769744596500,
    "updatedAt": 1769766694387
  },
  {
    "category": "Framework Integration,Mobile Frameworks,Android Kotlin",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 31,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/http-api/basic/overview",
    "content": [
      {
        "markdown": "Use **HTTP Request** in **Android Kotlin** Callvarious CloudBase capabilities\n\nin `build.gradle` (Module) Add dependencies：\n\n```gradle\ndependencies {\n    implementation 'com.squareup.okhttp3:okhttp:4.12.0'\n    implementation 'com.google.code.gson:gson:2.10.1'\n    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'\n}\n```",
        "index": 1,
        "title": "Install Dependencies",
        "content": []
      },
      {
        "markdown": "Add the following code to your **Android Kotlin** project",
        "index": 2,
        "title": "Initialize Configuration",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```kotlin\npackage com.example.cloudbase\n\nimport com.google.gson.Gson\nimport com.google.gson.reflect.TypeToken\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.withContext\nimport okhttp3.MediaType.Companion.toMediaType\nimport okhttp3.OkHttpClient\nimport okhttp3.Request\nimport okhttp3.RequestBody.Companion.toRequestBody\nimport java.util.concurrent.TimeUnit\n\nclass CloudBaseClient(\n    private val envId: String,\n    private var accessToken: String\n) {\n    private val baseUrl = \"https://$envId.api.tcloudbasegateway.com\"\n    private val gson = Gson()\n\n    private val client = OkHttpClient.Builder()\n        .connectTimeout(30, TimeUnit.SECONDS)\n        .readTimeout(30, TimeUnit.SECONDS)\n        .writeTimeout(30, TimeUnit.SECONDS)\n        .build()\n\n    /**\n     * UpdateAccess token\n     *\n     * @param newToken new access token\n     */\n    fun updateAccessToken(newToken: String) {\n        this.accessToken = newToken\n        println(\"Access token has beenUpdate\")\n    }\n\n    /**\n     * Unified HTTP request method\n     *\n     * @param method Request method (GET, POST, PUT, PATCH, DELETE)\n     * @param path APIPath (such as /v1/rdb/rest/table_name)\n     * @param body Request body data\n     * @param customHeaders Customheaders\n     *\n     * @return ResponseDataornull\n     */\n    suspend fun <T> request(\n        method: String,\n        path: String,\n        body: Any? = null,\n        customHeaders: Map<String, String> = emptyMap(),\n        typeToken: TypeToken<T>? = null\n    ): T? = withContext(Dispatchers.IO) {\n        val url = \"$baseUrl$path\"\n\n        val requestBuilder = Request.Builder()\n            .url(url)\n            .header(\"Content-Type\", \"application/json\")\n            .header(\"Accept\", \"application/json\")\n            .header(\"Authorization\", \"Bearer $accessToken\")\n\n        // AddCustomheaders\n        customHeaders.forEach { (key, value) ->\n            requestBuilder.header(key, value)\n        }\n\n        // SetRequest methodandbody\n        when (method.uppercase()) {\n            \"GET\" -> requestBuilder.get()\n            \"POST\", \"PUT\", \"PATCH\", \"DELETE\" -> {\n                val jsonBody = if (body != null) {\n                    gson.toJson(body).toRequestBody(\"application/json\".toMediaType())\n                } else {\n                    \"{}\".toRequestBody(\"application/json\".toMediaType())\n                }\n                when (method.uppercase()) {\n                    \"POST\" -> requestBuilder.post(jsonBody)\n                    \"PUT\" -> requestBuilder.put(jsonBody)\n                    \"PATCH\" -> requestBuilder.patch(jsonBody)\n                    \"DELETE\" -> requestBuilder.delete(jsonBody)\n                }\n            }\n        }\n\n        try {\n            val response = client.newCall(requestBuilder.build()).execute()\n\n            if (response.isSuccessful) {\n                val responseBody = response.body?.string()\n\n                // IfResponseis empty，Returntruerepresentssuccessful\n                if (responseBody.isNullOrEmpty()) {\n                    @Suppress(\"UNCHECKED_CAST\")\n                    return@withContext true as? T\n                }\n\n                return@withContext if (typeToken != null) {\n                    gson.fromJson(responseBody, typeToken.type)\n                } else {\n                    @Suppress(\"UNCHECKED_CAST\")\n                    gson.fromJson(responseBody, Any::class.java) as? T\n                }\n            } else {\n                println(\"Requestfailed: ${response.code} ${response.body?.string()}\")\n                return@withContext null\n            }\n        } catch (e: Exception) {\n            println(\"Requestfailed: ${e.message}\")\n            e.printStackTrace()\n            return@withContext null\n        }\n    }\n}\n\n// ConfigurationfileorInitializewhenCreateinstance\n// val cloudbase = CloudBaseClient(\n//     envId = \"your-env-id\",\n//     accessToken = \"your-access-token\"\n// )\n```",
            "index": 1,
            "title": "CloudBaseClient.kt"
          },
          {
            "markdown": "in `local.properties` orConfigurationfileAdd：\n\n> 💡Note: For user permissions, refer to the \"Authentication\" module to obtain access_token\n\n```properties\n# Environment ID\nCLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Anonymous access token\nCLOUDBASE_ACCESS_TOKEN={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": "Configurationfile"
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```kotlin\nsuspend fun getPgData(cloudbase: CloudBaseClient, tableName: String): List<Map<String, Any>>? {\n    // Query PG database\n    val data = cloudbase.request<List<Map<String, Any>>>(\n        method = \"GET\",\n        path = \"/v1/rdb/rest/$tableName?select=*&limit=10\",\n        typeToken = object : TypeToken<List<Map<String, Any>>>() {}\n    )\n\n    if (data != null) {\n        println(\"Query succeeded: $data\")\n    }\n    return data ?: emptyList()\n}\n\n// Usage example\n// lifecycleScope.launch {\n//     val result = getPgData(cloudbase, \"{%TABLE_NAME%}\")\n//     println(result)\n// }\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```kotlin\nsuspend fun addPgData(cloudbase: CloudBaseClient, tableName: String, data: Map<String, Any>): Map<String, Any>? {\n    // Insert data into {%TABLE_NAME%}\n    val result = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/v1/rdb/rest/$tableName\",\n        body = data,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (result != null) {\n        println(\"Insert succeeded: $result\")\n    }\n    return result\n}\n\n// Usage example\n// lifecycleScope.launch {\n//     val result = addPgData(cloudbase, \"{%TABLE_NAME%}\", mapOf(\"title\" to \"Example title\"))\n//     println(result)\n// }\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```kotlin\nsuspend fun updatePgData(cloudbase: CloudBaseClient, tableName: String, dataId: String, data: Map<String, Any>): Any? {\n    // Update record in {%TABLE_NAME%}\n    val result = cloudbase.request<Any>(\n        method = \"PATCH\",\n        path = \"/v1/rdb/rest/$tableName?id=eq.$dataId\",\n        body = data\n    )\n\n    if (result != null) {\n        println(\"Update success: $result\")\n    }\n    return result\n}\n\n// Usage example\n// lifecycleScope.launch {\n//     val result = updatePgData(cloudbase, \"{%TABLE_NAME%}\", \"<record_id>\", mapOf(\"title\" to \"New title\"))\n//     println(result)\n// }\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```kotlin\nsuspend fun upsertPgData(cloudbase: CloudBaseClient, tableName: String, data: Map<String, Any>): Any? {\n    // Update record in {%TABLE_NAME%}\n    val result = cloudbase.request<Any>(\n        method = \"POST\",\n        path = \"/v1/rdb/rest/$tableName\",\n        body = data\n    )\n\n    if (result != null) {\n        println(\"Upsert succeeded: $result\")\n    }\n    return result\n}\n\n// Usage example\n// lifecycleScope.launch {\n//     val result = upsertPgData(cloudbase, \"{%TABLE_NAME%}\", mapOf(\"id\" to 1, \"title\" to \"Example title\"))\n//     println(result)\n// }\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```kotlin\nsuspend fun deletePgData(cloudbase: CloudBaseClient, tableName: String, dataId: String): Boolean {\n    // Delete record from {%TABLE_NAME%}\n    val result = cloudbase.request<Any>(\n        method = \"DELETE\",\n        path = \"/v1/rdb/rest/$tableName?id=eq.$dataId\"\n    )\n\n    if (result != null) {\n        println(\"Delete success\")\n        return true\n    }\n    return false\n}\n\n// Usage example\n// lifecycleScope.launch {\n//     val result = deletePgData(cloudbase, \"{%TABLE_NAME%}\", \"<record_id>\")\n//     println(result)\n// }\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```kotlin\nimport com.google.gson.reflect.TypeToken\n\nsuspend fun getMysqlData(cloudbase: CloudBaseClient, tableName: String): List<Map<String, Any>>? {\n    // Query MySQL database data\n    val data = cloudbase.request<List<Map<String, Any>>>(\n        method = \"GET\",\n        path = \"/v1/rdb/rest/$tableName?limit=10\",\n        typeToken = object : TypeToken<List<Map<String, Any>>>() {}\n    )\n\n    if (data != null) {\n        println(\"Querysuccessful: $data\")\n    }\n    return data ?: emptyList()\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = getMysqlData(cloudbase, \"{%TABLE_NAME%}\")\n//     println(result)\n// }\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun addMysqlData(cloudbase: CloudBaseClient, tableName: String, data: Map<String, Any>): Map<String, Any>? {\n    // Add MySQL database data\n    val result = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/v1/rdb/rest/$tableName\",\n        body = data,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (result != null) {\n        println(\"Insert successful: $result\")\n    }\n    return result\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = addMysqlData(cloudbase, \"{%TABLE_NAME%}\", mapOf(\"title\" to \"Example Title\"))\n//     println(result)\n// }\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun updateMysqlData(cloudbase: CloudBaseClient, tableName: String, dataId: String, data: Map<String, Any>): Any? {\n    // Update MySQL database data\n    val result = cloudbase.request<Any>(\n        method = \"PATCH\",\n        path = \"/v1/rdb/rest/$tableName?id=eq.$dataId\",\n        body = data\n    )\n\n    if (result != null) {\n        println(\"Update successful: $result\")\n    }\n    return result\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = updateMysqlData(cloudbase, \"{%TABLE_NAME%}\", \"<data id>\", mapOf(\"title\" to \"New Title\"))\n//     println(result)\n// }\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun deleteMysqlData(cloudbase: CloudBaseClient, tableName: String, dataId: String): Boolean {\n    // Delete MySQL database data\n    val result = cloudbase.request<Any>(\n        method = \"DELETE\",\n        path = \"/v1/rdb/rest/$tableName?id=eq.$dataId\"\n    )\n\n    if (result != null) {\n        println(\"Delete successful\")\n        return true\n    }\n    return false\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = deleteMysqlData(cloudbase, \"{%TABLE_NAME%}\", \"<data id>\")\n//     println(result)\n// }\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```kotlin\nimport com.google.gson.reflect.TypeToken\n\nsuspend fun getModelData(cloudbase: CloudBaseClient, modelName: String, envType: String = \"prod\"): List<Map<String, Any>> {\n    // QueryData ModelData\n    val payload = mapOf(\n        \"pageSize\" to 10,\n        \"pageNumber\" to 1,\n        \"getCount\" to true\n    )\n\n    val result = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/v1/model/$envType/$modelName/list\",\n        body = payload,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (result != null) {\n        val records = (result[\"data\"] as? Map<*, *>)?.get(\"records\") as? List<Map<String, Any>> ?: emptyList()\n        println(\"Querysuccessful: $records\")\n        return records\n    }\n    return emptyList()\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val records = getModelData(cloudbase, \"{%TABLE_NAME%}\")\n//     println(records)\n// }\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun addModelData(cloudbase: CloudBaseClient, modelName: String, data: Map<String, Any>, envType: String = \"prod\"): Map<String, Any>? {\n    // AddData ModelData\n    val result = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/v1/model/$envType/$modelName/create\",\n        body = mapOf(\"data\" to data),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (result != null) {\n        val docId = (result[\"data\"] as? Map<*, *>)?.get(\"id\")\n        println(\"Insert successful! id: $docId\")\n    }\n    return result\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = addModelData(cloudbase, \"{%TABLE_NAME%}\", mapOf(\"title\" to \"Example Title\"))\n//     println(result)\n// }\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun updateModelData(cloudbase: CloudBaseClient, modelName: String, dataId: String, data: Map<String, Any>, envType: String = \"prod\"): Boolean {\n    // UpdateData ModelData\n    val payload = mapOf(\n        \"data\" to data,\n        \"filter\" to mapOf(\n            \"where\" to mapOf(\n                \"_id\" to mapOf(\"\\$eq\" to dataId)\n            )\n        )\n    )\n\n    val result = cloudbase.request<Any>(\n        method = \"PUT\",\n        path = \"/v1/model/$envType/$modelName/update\",\n        body = payload\n    )\n\n    if (result != null) {\n        println(\"Update successful!\")\n        return true\n    }\n    return false\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = updateModelData(cloudbase, \"{%TABLE_NAME%}\", \"<data id>\", mapOf(\"title\" to \"New Title\"))\n//     println(result)\n// }\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun deleteModelData(cloudbase: CloudBaseClient, modelName: String, dataId: String, envType: String = \"prod\"): Boolean {\n    // DeleteData ModelData\n    val payload = mapOf(\n        \"filter\" to mapOf(\n            \"where\" to mapOf(\n                \"_id\" to mapOf(\"\\$eq\" to dataId)\n            )\n        )\n    )\n\n    val result = cloudbase.request<Any>(\n        method = \"POST\",\n        path = \"/v1/model/$envType/$modelName/delete\",\n        body = payload\n    )\n\n    if (result != null) {\n        println(\"Delete successful!\")\n        return true\n    }\n    return false\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = deleteModelData(cloudbase, \"{%TABLE_NAME%}\", \"<data id>\")\n//     println(result)\n// }\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```kotlin\nsuspend fun callFunction(cloudbase: CloudBaseClient, functionName: String, data: Map<String, Any>? = null): Map<String, Any>? {\n    // CallCloud Function\n    val result = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/v1/functions/$functionName\",\n        body = data ?: emptyMap<String, Any>(),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (result != null) {\n        println(\"Cloud function call result: $result\")\n    }\n    return result\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = callFunction(cloudbase, \"{%FUNCTION_NAME%}\")\n//     println(result)\n// }\n```",
            "index": 3,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```kotlin\nsuspend fun callContainer(cloudbase: CloudBaseClient, serviceName: String, path: String = \"\", method: String = \"GET\", data: Map<String, Any>? = null): Any? {\n    // CallCloud Runservice\n    val fullPath = \"/v1/cloudrun/$serviceName/$path\".trimEnd('/')\n    val result = cloudbase.request<Any>(\n        method = method.uppercase(),\n        path = fullPath,\n        body = data\n    )\n\n    if (result != null) {\n        println(\"Cloud RunCallResult: $result\")\n    }\n    return result\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = callContainer(cloudbase, \"{%SERVICE_NAME%}\")\n//     println(result)\n// }\n```",
            "index": 4,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```kotlin\nimport okhttp3.OkHttpClient\nimport okhttp3.Request\nimport okhttp3.RequestBody.Companion.toRequestBody\nimport java.io.File\n\nsuspend fun uploadFile(cloudbase: CloudBaseClient, filePath: String, objectId: String? = null): Map<String, String>? = withContext(Dispatchers.IO) {\n    // Upload FiletoCloud Storage\n    val file = File(filePath)\n\n    if (!file.exists()) {\n        println(\"filedoes not exist: $filePath\")\n        return@withContext null\n    }\n\n    val finalObjectId = objectId ?: \"uploads/${System.currentTimeMillis()}-${file.name}\"\n\n    // 1. Get upload info\n    val uploadInfo = cloudbase.request<List<Map<String, Any>>>(\n        method = \"POST\",\n        path = \"/v1/storages/get-objects-upload-info\",\n        body = listOf(mapOf(\"objectId\" to finalObjectId)),\n        typeToken = object : TypeToken<List<Map<String, Any>>>() {}\n    )\n\n    if (uploadInfo.isNullOrEmpty()) {\n        return@withContext null\n    }\n\n    val info = uploadInfo[0]\n    val uploadUrl = info[\"uploadUrl\"] as String\n\n    try {\n        // 2. Upload File\n        val fileData = file.readBytes()\n        val uploadHeaders = mapOf(\n            \"Authorization\" to (info[\"authorization\"] as String),\n            \"X-Cos-Security-Token\" to (info[\"token\"] as String),\n            \"X-Cos-Meta-Fileid\" to (info[\"cloudObjectMeta\"] as String)\n        )\n\n        val requestBuilder = Request.Builder()\n            .url(uploadUrl)\n            .put(fileData.toRequestBody())\n\n        uploadHeaders.forEach { (key, value) ->\n            requestBuilder.header(key, value)\n        }\n\n        val client = OkHttpClient()\n        val uploadResponse = client.newCall(requestBuilder.build()).execute()\n\n        if (uploadResponse.isSuccessful) {\n            val result = mapOf(\n                \"cloudObjectId\" to (info[\"cloudObjectId\"] as String),\n                \"downloadUrl\" to (info[\"downloadUrl\"] as String),\n                \"objectId\" to finalObjectId\n            )\n\n            println(\"fileUpload successful:\")\n            println(\"- Object ID: ${result[\"objectId\"]}\")\n            println(\"- DownloadURL: ${result[\"downloadUrl\"]}\")\n\n            return@withContext result\n        }\n\n        println(\"fileUploadfailed: ${uploadResponse.code}\")\n        return@withContext null\n    } catch (e: Exception) {\n        println(\"fileUploadfailed: ${e.message}\")\n        e.printStackTrace()\n        return@withContext null\n    }\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = uploadFile(cloudbase, \"/path/to/example.jpg\")\n//     println(result)\n// }\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun getFileUrl(cloudbase: CloudBaseClient, cloudObjectId: String): String? {\n    // GetCloud Storagefiletemporary accessURL\n    val result = cloudbase.request<List<Map<String, Any>>>(\n        method = \"POST\",\n        path = \"/v1/storages/get-objects-download-info\",\n        body = listOf(mapOf(\"cloudObjectId\" to cloudObjectId)),\n        typeToken = object : TypeToken<List<Map<String, Any>>>() {}\n    )\n\n    if (!result.isNullOrEmpty()) {\n        val downloadUrl = result[0][\"downloadUrl\"] as? String\n        println(\"fileURL: $downloadUrl\")\n        return downloadUrl\n    }\n    return null\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val fileUrl = getFileUrl(cloudbase, \"cloud://xxx.png\")\n//     println(fileUrl)\n// }\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```kotlin\nimport okhttp3.OkHttpClient\nimport okhttp3.Request\nimport java.io.File\n\nsuspend fun downloadFile(cloudbase: CloudBaseClient, cloudObjectId: String, savePath: String = \"./\"): Boolean = withContext(Dispatchers.IO) {\n    // DownloadCloud Storagefiletolocal\n    // 1. GetDownloadURL\n    val result = cloudbase.request<List<Map<String, Any>>>(\n        method = \"POST\",\n        path = \"/v1/storages/get-objects-download-info\",\n        body = listOf(mapOf(\"cloudObjectId\" to cloudObjectId)),\n        typeToken = object : TypeToken<List<Map<String, Any>>>() {}\n    )\n\n    if (result.isNullOrEmpty()) {\n        return@withContext false\n    }\n\n    val downloadUrl = result[0][\"downloadUrl\"] as String\n\n    try {\n        // 2. fromURLExtractfilename\n        val filename = downloadUrl.split(\"/\").last().split(\"?\").first()\n\n        // 3. Determine full path\n        val fullPath = if (File(savePath).isDirectory || savePath.endsWith(\"/\")) {\n            \"$savePath/$filename\"\n        } else {\n            savePath\n        }\n\n        // 4. Download File\n        val client = OkHttpClient()\n        val request = Request.Builder().url(downloadUrl).build()\n        val fileResponse = client.newCall(request).execute()\n\n        if (fileResponse.isSuccessful) {\n            // 5. Save to local\n            val file = File(fullPath)\n            file.parentFile?.mkdirs()\n            file.writeBytes(fileResponse.body!!.bytes())\n\n            println(\"Downloadsuccessful! filesaved to: $fullPath\")\n            return@withContext true\n        }\n\n        println(\"Downloadfailed: ${fileResponse.code}\")\n        return@withContext false\n    } catch (e: Exception) {\n        println(\"Downloadfailed: ${e.message}\")\n        e.printStackTrace()\n        return@withContext false\n    }\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     // Downloadto specified directory\n//     downloadFile(cloudbase, \"cloud://xxx.png\", \"/sdcard/Download/\")\n//\n//     // Downloadand rename\n//     downloadFile(cloudbase, \"cloud://xxx.png\", \"/sdcard/Download/my-image.png\")\n// }\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun deleteFile(cloudbase: CloudBaseClient, cloudObjectIds: Any): Boolean {\n    // DeleteCloud Storagefile\n    val ids = when (cloudObjectIds) {\n        is String -> listOf(cloudObjectIds)\n        is List<*> -> cloudObjectIds.filterIsInstance<String>()\n        else -> {\n            println(\"Parameter type error\")\n            return false\n        }\n    }\n\n    val data = ids.map { mapOf(\"cloudObjectId\" to it) }\n    val result = cloudbase.request<Any>(\n        method = \"POST\",\n        path = \"/v1/storages/delete-objects\",\n        body = data\n    )\n\n    if (result != null) {\n        println(\"Delete successful!\")\n        return true\n    }\n    return false\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = deleteFile(cloudbase, \"cloud://xxx.png\")\n//     println(result)\n// }\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```kotlin\nimport okhttp3.OkHttpClient\nimport okhttp3.Request\nimport okhttp3.RequestBody.Companion.toRequestBody\nimport okhttp3.MediaType.Companion.toMediaType\nimport com.google.gson.Gson\n\nsuspend fun streamText(cloudbase: CloudBaseClient, model: String, subModel: String, messages: List<Map<String, String>>): String? = withContext(Dispatchers.IO) {\n    // streamingtextthisGenerate\n    val payload = mapOf(\n        \"model\" to subModel,\n        \"messages\" to messages,\n        \"stream\" to true\n    )\n\n    val url = \"${cloudbase.baseUrl}/v1/ai/$model/chat/completions\"\n    val gson = Gson()\n\n    val requestBody = gson.toJson(payload).toRequestBody(\"application/json\".toMediaType())\n\n    val request = Request.Builder()\n        .url(url)\n        .header(\"Content-Type\", \"application/json\")\n        .header(\"Accept\", \"text/event-stream\")\n        .header(\"Authorization\", \"Bearer ${cloudbase.accessToken}\")\n        .post(requestBody)\n        .build()\n\n    try {\n        val client = OkHttpClient()\n        val response = client.newCall(request).execute()\n\n        if (response.isSuccessful) {\n            println(\"AI Streaming response:\")\n            var fullContent = \"\"\n\n            response.body?.source()?.use { source ->\n                while (!source.exhausted()) {\n                    val line = source.readUtf8Line() ?: continue\n\n                    if (line.startsWith(\"data: \")) {\n                        val dataStr = line.substring(6)\n                        if (dataStr.trim() != \"[DONE]\") {\n                            try {\n                                val chunkData = gson.fromJson(dataStr, Map::class.java)\n                                val choices = chunkData[\"choices\"] as? List<*>\n                                val delta = (choices?.get(0) as? Map<*, *>)?.get(\"delta\") as? Map<*, *>\n                                val content = delta?.get(\"content\") as? String ?: \"\"\n\n                                if (content.isNotEmpty()) {\n                                    print(content)\n                                    fullContent += content\n                                }\n                            } catch (e: Exception) {\n                                // Ignore JSON parsing error\n                            }\n                        }\n                    }\n                }\n            }\n\n            println()\n            return@withContext fullContent\n        } else {\n            println(\"AI Call failed: ${response.code}\")\n            return@withContext null\n        }\n    } catch (e: Exception) {\n        println(\"AI Call failed: ${e.message}\")\n        e.printStackTrace()\n        return@withContext null\n    }\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val response = streamText(\n//         cloudbase,\n//         \"{%AI_MODEL_NAME%}\",\n//         \"{%AI_SUB_MODEL_NAME%}\",\n//         listOf(\n//             mapOf(\"role\" to \"system\", \"content\" to \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create\"),\n//             mapOf(\"role\" to \"user\", \"content\" to \"Spring\")\n//         )\n//     )\n//     println(\"\\nComplete response: $response\")\n// }\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```kotlin\nimport com.google.gson.Gson\n\nsuspend fun generateImage(cloudbase: CloudBaseClient, prompt: String): Map<String, Any>? = withContext(Dispatchers.IO) {\n    /// Call image generation cloud function\n    val result = cloudbase.request(\n        \"POST\",\n        \"/v1/functions/<YOUR_FUNCTION_NAME>/invoke\",\n        mapOf(\"prompt\" to prompt)\n    )\n\n    if (result != null) {\n        val success = result[\"success\"] as? Boolean ?: false\n        \n        if (success) {\n            // Generation successful\n            println(\"Generation successful!\")\n            println(\"Image URL: ${result[\"imageUrl\"]}\")\n            println(\"Optimized prompt: ${result[\"revised_prompt\"]}\")\n\n            // Use image\n            // Note: Image URL is valid for 24 hours, please save or transfer promptly\n            return@withContext result\n        } else {\n            // Generation failed\n            println(\"Generation failed: ${result[\"code\"]} ${result[\"message\"]}\")\n            return@withContext null\n        }\n    }\n    return@withContext null\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = generateImage(cloudbase, \"A cute cat playing in the sunshine\")\n//     if (result != null) {\n//         println(\"Image URL: ${result[\"imageUrl\"]}\")\n//     }\n// }\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```kotlin\n/**\n * Android Kotlin Call Agent Example (AG-UI Protocol)\n * Protocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n */\nimport okhttp3.OkHttpClient\nimport okhttp3.Request\nimport okhttp3.RequestBody.Companion.toRequestBody\nimport okhttp3.MediaType.Companion.toMediaType\nimport com.google.gson.Gson\n\nsuspend fun chatWithAgentStream(cloudbase: CloudBaseClient, botId: String, userMessage: String): String? = withContext(Dispatchers.IO) {\n    // Build message list (AG-UI protocol format)\n    val messages = listOf(\n        mapOf(\n            \"id\" to \"msg_001\",\n            \"role\" to \"user\",\n            \"content\" to userMessage\n        )\n    )\n\n    // AG-UI Protocol request parameters\n    val payload = mapOf(\n        \"messages\" to messages,                                    // Required: Message list\n        \"threadId\" to \"550e8400-e29b-41d4-a716-446655440000\",     // Optional: Session ID for multi-turn conversation\n        \"runId\" to \"run_001\",                                      // Optional: Run ID for execution tracking\n        \"tools\" to emptyList<Any>(),                               // Optional: Frontend tool definitions\n        \"context\" to emptyList<Any>(),                             // Optional: Context information\n        \"forwardedProps\" to emptyMap<String, Any>()                // Optional: Pass-through parameters\n    )\n\n    val url = \"${cloudbase.baseUrl}/v1/aibot/bots/$botId/send-message\"\n    val gson = Gson()\n\n    val requestBody = gson.toJson(payload).toRequestBody(\"application/json\".toMediaType())\n\n    val request = Request.Builder()\n        .url(url)\n        .header(\"Content-Type\", \"application/json\")\n        .header(\"Accept\", \"text/event-stream\")\n        .header(\"Authorization\", \"Bearer ${cloudbase.accessToken}\")\n        .post(requestBody)\n        .build()\n\n    try {\n        val client = OkHttpClient()\n        val response = client.newCall(request).execute()\n\n        if (response.isSuccessful) {\n            println(\"AI Streaming response:\")\n            var fullContent = \"\"\n            var buffer = \"\"\n\n            response.body?.source()?.use { source ->\n                while (!source.exhausted()) {\n                    buffer += source.readUtf8Line() ?: \"\"\n                    buffer += \"\\n\"\n\n                    while (buffer.contains(\"\\n\")) {\n                        val newlineIndex = buffer.indexOf(\"\\n\")\n                        val line = buffer.substring(0, newlineIndex).trim()\n                        buffer = buffer.substring(newlineIndex + 1)\n\n                        if (line.startsWith(\"data: \")) {\n                            val dataStr = line.substring(6).trim()\n                            if (dataStr.isNotEmpty() && dataStr != \"[DONE]\") {\n                                try {\n                                    val chunkData = gson.fromJson(dataStr, Map::class.java)\n                                    val content = chunkData[\"content\"] as? String\n                                        ?: ((chunkData[\"choices\"] as? List<*>)?.get(0) as? Map<*, *>)?.let {\n                                            (it[\"delta\"] as? Map<*, *>)?.get(\"content\") as? String\n                                                ?: (it[\"message\"] as? Map<*, *>)?.get(\"content\") as? String\n                                        } ?: \"\"\n\n                                    if (content.isNotEmpty()) {\n                                        print(content)\n                                        fullContent += content\n                                    }\n                                } catch (e: Exception) {\n                                    // Ignore JSON parsing error\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n\n            println()\n            return@withContext fullContent\n        } else {\n            println(\"AI Call failed: ${response.code}\")\n            return@withContext null\n        }\n    } catch (e: Exception) {\n        println(\"AI Call failed: ${e.message}\")\n        e.printStackTrace()\n        return@withContext null\n    }\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val response = chatWithAgentStream(cloudbase, \"{%AGENT_ID%}\", \"Who are you\")\n//     println(\"\\nComplete response: $response\")\n// }\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```kotlin\nimport okhttp3.OkHttpClient\nimport okhttp3.Request\nimport okhttp3.RequestBody.Companion.toRequestBody\nimport okhttp3.MediaType.Companion.toMediaType\nimport com.google.gson.Gson\n\nsuspend fun chatWithAgentStream(cloudbase: CloudBaseClient, botId: String, msg: String, history: List<Map<String, String>>? = null): String? = withContext(Dispatchers.IO) {\n    // streamingCallAgent\n    val payload = mapOf(\n        \"history\" to (history ?: emptyList<Map<String, String>>()),\n        \"msg\" to msg\n    )\n\n    val url = \"${cloudbase.baseUrl}/v1/aibot/bots/$botId/send-message\"\n    val gson = Gson()\n\n    val requestBody = gson.toJson(payload).toRequestBody(\"application/json\".toMediaType())\n\n    val request = Request.Builder()\n        .url(url)\n        .header(\"Content-Type\", \"application/json\")\n        .header(\"Accept\", \"text/event-stream\")\n        .header(\"Authorization\", \"Bearer ${cloudbase.accessToken}\")\n        .post(requestBody)\n        .build()\n\n    try {\n        val client = OkHttpClient()\n        val response = client.newCall(request).execute()\n\n        if (response.isSuccessful) {\n            println(\"AI Streaming response:\")\n            var fullContent = \"\"\n            var buffer = \"\"\n\n            response.body?.source()?.use { source ->\n                while (!source.exhausted()) {\n                    buffer += source.readUtf8Line() ?: \"\"\n                    buffer += \"\\n\"\n\n                    while (buffer.contains(\"\\n\")) {\n                        val newlineIndex = buffer.indexOf(\"\\n\")\n                        val line = buffer.substring(0, newlineIndex).trim()\n                        buffer = buffer.substring(newlineIndex + 1)\n\n                        if (line.startsWith(\"data: \")) {\n                            val dataStr = line.substring(6).trim()\n                            if (dataStr.isNotEmpty() && dataStr != \"[DONE]\") {\n                                try {\n                                    val chunkData = gson.fromJson(dataStr, Map::class.java)\n                                    val content = chunkData[\"content\"] as? String\n                                        ?: ((chunkData[\"choices\"] as? List<*>)?.get(0) as? Map<*, *>)?.let {\n                                            (it[\"delta\"] as? Map<*, *>)?.get(\"content\") as? String\n                                                ?: (it[\"message\"] as? Map<*, *>)?.get(\"content\") as? String\n                                        } ?: \"\"\n\n                                    if (content.isNotEmpty()) {\n                                        print(content)\n                                        fullContent += content\n                                    }\n                                } catch (e: Exception) {\n                                    // Ignore JSON parsing error\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n\n            println()\n            return@withContext fullContent\n        } else {\n            println(\"AI Call failed: ${response.code}\")\n            return@withContext null\n        }\n    } catch (e: Exception) {\n        println(\"AI Call failed: ${e.message}\")\n        e.printStackTrace()\n        return@withContext null\n    }\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val response = chatWithAgentStream(cloudbase, \"{%AGENT_ID%}\", \"Who are you\")\n//     println(\"\\nComplete response: $response\")\n// }\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 8,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```kotlin\nsuspend fun signUpWithPhoneCode(cloudbase: CloudBaseClient, phoneNumber: String, verificationCode: String, username: String? = null, password: String? = null, captchaToken: String? = null): Map<String, Any>? {\n    // Step1: SendSMSVerification code\n    val sendBody = mutableMapOf<String, Any>(\n        \"phone_number\" to if (phoneNumber.startsWith(\"+86\")) phoneNumber else \"+86$phoneNumber\",\n        \"target\" to \"NON_USER\"  // \"NON_USER\" - Accountdoes not existthenSend; \"ANY\" - No restriction\n    )\n\n    val sendHeaders = captchaToken?.let { mapOf(\"x-captcha-token\" to it) } ?: emptyMap()\n\n    val sendResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification\",\n        body = sendBody,\n        customHeaders = sendHeaders,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (sendResult == null) {\n        println(\"Send Codefailed\")\n        return null\n    }\n\n    val verificationId = sendResult[\"verification_id\"] as? String ?: return null\n    println(\"Verification codeSendsuccessful! ID: $verificationId\")\n\n    // Step2: Verify the code\n    val verifyResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification/verify\",\n        body = mapOf(\n            \"verification_id\" to verificationId,\n            \"verification_code\" to verificationCode\n        ),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (verifyResult == null) {\n        println(\"Verification codeError\")\n        return null\n    }\n\n    val verificationToken = verifyResult[\"verification_token\"] as? String ?: return null\n    println(\"Verifysuccessful!\")\n\n    // Step3: UseVerifytokenRegister\n    val signUpBody = mutableMapOf<String, Any>(\n        \"phone_number\" to if (phoneNumber.startsWith(\"+86\")) phoneNumber else \"+86$phoneNumber\",\n        \"verification_token\" to verificationToken\n    )\n\n    // Optional：AddUsernameandPassword\n    username?.let { signUpBody[\"username\"] = it }\n    password?.let { signUpBody[\"password\"] = it }\n\n    val signUpResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/signup\",\n        body = signUpBody,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (signUpResult != null) {\n        val accessToken = signUpResult[\"access_token\"] as? String\n        val userId = signUpResult[\"sub\"] as? String\n\n        println(\"Registration successful! User ID: $userId\")\n        println(\"Access token: ${accessToken?.take(20)}...\")\n\n        // UpdateAccess token\n        accessToken?.let { cloudbase.updateAccessToken(it) }\n        return signUpResult\n    }\n\n    println(\"Registration failed\")\n    return null\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = signUpWithPhoneCode(cloudbase, \"13800138000\", \"123456\", \"myusername\", \"mypassword\")\n//     if (result != null) {\n//         println(\"Phone numberRegistration successful\")\n//     }\n// }\n```",
                "index": 1,
                "title": "SMS Code Registration",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun signUpWithEmailCode(cloudbase: CloudBaseClient, email: String, verificationCode: String, username: String? = null, password: String? = null, captchaToken: String? = null): Map<String, Any>? {\n    // Step1: SendEmailVerification code\n    val sendBody = mutableMapOf<String, Any>(\n        \"email\" to email,\n        \"target\" to \"NON_USER\"  // \"NON_USER\" - Accountdoes not existthenSend; \"ANY\" - No restriction\n    )\n\n    val sendHeaders = captchaToken?.let { mapOf(\"x-captcha-token\" to it) } ?: emptyMap()\n\n    val sendResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification\",\n        body = sendBody,\n        customHeaders = sendHeaders,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (sendResult == null) {\n        println(\"Send Codefailed\")\n        return null\n    }\n\n    val verificationId = sendResult[\"verification_id\"] as? String ?: return null\n    println(\"Verification codeSendsuccessful! ID: $verificationId\")\n\n    // Step2: Verify the code\n    val verifyResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification/verify\",\n        body = mapOf(\n            \"verification_id\" to verificationId,\n            \"verification_code\" to verificationCode\n        ),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (verifyResult == null) {\n        println(\"Verification codeError\")\n        return null\n    }\n\n    val verificationToken = verifyResult[\"verification_token\"] as? String ?: return null\n    println(\"Verifysuccessful!\")\n\n    // Step3: UseVerifytokenRegister\n    val signUpBody = mutableMapOf<String, Any>(\n        \"email\" to email,\n        \"verification_token\" to verificationToken\n    )\n\n    // Optional：AddUsernameandPassword\n    username?.let { signUpBody[\"username\"] = it }\n    password?.let { signUpBody[\"password\"] = it }\n\n    val signUpResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/signup\",\n        body = signUpBody,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (signUpResult != null) {\n        val accessToken = signUpResult[\"access_token\"] as? String\n        val userId = signUpResult[\"sub\"] as? String\n\n        println(\"Registration successful! User ID: $userId\")\n        println(\"Access token: ${accessToken?.take(20)}...\")\n\n        // UpdateAccess token\n        accessToken?.let { cloudbase.updateAccessToken(it) }\n        return signUpResult\n    }\n\n    println(\"Registration failed\")\n    return null\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = signUpWithEmailCode(cloudbase, \"user@example.com\", \"123456\", \"myusername\", \"mypassword\")\n//     if (result != null) {\n//         println(\"EmailRegistration successful\")\n//     }\n// }\n```",
                "index": 2,
                "title": "Email Code Registration",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun signIn(cloudbase: CloudBaseClient, username: String, password: String): Map<String, Any>? {\n    // Username Password Login\n    val result = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/signin\",\n        body = mapOf(\"username\" to username, \"password\" to password),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (result != null) {\n        val accessToken = result[\"access_token\"] as? String\n        val refreshToken = result[\"refresh_token\"] as? String\n        val userId = result[\"sub\"] as? String\n\n        println(\"Login successful! User ID: $userId\")\n        println(\"Access token: ${accessToken?.take(20)}...\")\n\n        // UpdateAccess token\n        accessToken?.let { cloudbase.updateAccessToken(it) }\n        return result\n    }\n    return null\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = signIn(cloudbase, \"your_username\", \"your_password\")\n//     println(result)\n// }\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun loginWithPhoneCode(cloudbase: CloudBaseClient, phoneNumber: String, verificationCode: String, captchaToken: String? = null): Boolean {\n    // Step1: SendSMSVerification code\n    val sendBody = mutableMapOf<String, Any>(\n        \"phone_number\" to if (phoneNumber.startsWith(\"+86\")) phoneNumber else \"+86$phoneNumber\",\n        \"target\" to \"ANY\"  // \"ANY\" - No restriction，Noneregardless of userYesNoexistsallSend; \"USER\" - AccountmustexiststhenSend\n    )\n\n    val sendHeaders = captchaToken?.let { mapOf(\"x-captcha-token\" to it) } ?: emptyMap()\n\n    val sendResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification\",\n        body = sendBody,\n        customHeaders = sendHeaders,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (sendResult == null) {\n        println(\"Send Codefailed\")\n        return false\n    }\n\n    val verificationId = sendResult[\"verification_id\"] as? String ?: return false\n    println(\"Verification codeSendsuccessful! ID: $verificationId\")\n\n    // Step2: Verify the code\n    val verifyResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification/verify\",\n        body = mapOf(\n            \"verification_id\" to verificationId,\n            \"verification_code\" to verificationCode\n        ),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (verifyResult == null) {\n        println(\"Verification codeError\")\n        return false\n    }\n\n    val verificationToken = verifyResult[\"verification_token\"] as? String ?: return false\n    println(\"Verifysuccessful!\")\n\n    // Step3: UseVerifytokenLogin\n    val loginResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/signin\",\n        body = mapOf(\n            \"phone_number\" to if (phoneNumber.startsWith(\"+86\")) phoneNumber else \"+86$phoneNumber\",\n            \"verification_token\" to verificationToken\n        ),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (loginResult != null) {\n        val accessToken = loginResult[\"access_token\"] as? String\n        println(\"Login successful!\")\n        accessToken?.let { cloudbase.updateAccessToken(it) }\n        return true\n    }\n\n    println(\"Login failed\")\n    return false\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val success = loginWithPhoneCode(cloudbase, \"13800138000\", \"123456\")\n//     if (success) {\n//         println(\"Phone numberLogin successful\")\n//     }\n// }\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun loginWithEmailCode(cloudbase: CloudBaseClient, email: String, verificationCode: String, captchaToken: String? = null): Boolean {\n    // Step1: SendEmailVerification code\n    val sendBody = mutableMapOf<String, Any>(\n        \"email\" to email,\n        \"target\" to \"ANY\"  // \"ANY\" - No restriction，Noneregardless of userYesNoexistsallSend; \"USER\" - AccountmustexiststhenSend\n    )\n\n    val sendHeaders = captchaToken?.let { mapOf(\"x-captcha-token\" to it) } ?: emptyMap()\n\n    val sendResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification\",\n        body = sendBody,\n        customHeaders = sendHeaders,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (sendResult == null) {\n        println(\"Send Codefailed\")\n        return false\n    }\n\n    val verificationId = sendResult[\"verification_id\"] as? String ?: return false\n    println(\"Verification codeSendsuccessful! ID: $verificationId\")\n\n    // Step2: Verify the code\n    val verifyResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification/verify\",\n        body = mapOf(\n            \"verification_id\" to verificationId,\n            \"verification_code\" to verificationCode\n        ),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (verifyResult == null) {\n        println(\"Verification codeError\")\n        return false\n    }\n\n    val verificationToken = verifyResult[\"verification_token\"] as? String ?: return false\n    println(\"Verifysuccessful!\")\n\n    // Step3: UseVerifytokenLogin\n    val loginResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/signin\",\n        body = mapOf(\n            \"email\" to email,\n            \"verification_token\" to verificationToken\n        ),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (loginResult != null) {\n        val accessToken = loginResult[\"access_token\"] as? String\n        println(\"Login successful!\")\n        accessToken?.let { cloudbase.updateAccessToken(it) }\n        return true\n    }\n\n    println(\"Login failed\")\n    return false\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val success = loginWithEmailCode(cloudbase, \"user@example.com\", \"123456\")\n//     if (success) {\n//         println(\"EmailLogin successful\")\n//     }\n// }\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login",
                "content": []
              }
            ]
          }
        ]
      }
    ],
    "_id": "36e9b7bb697c28d80038bc8c56f06f02",
    "_openid": "anon",
    "createdAt": 1769744600669,
    "updatedAt": 1769766698595
  },
  {
    "category": "Framework Integration,Backend Frameworks,Node.js",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 20,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/api-reference/server/node-sdk/initialization",
    "content": [
      {
        "markdown": "`@cloudbase/node-sdk` allows you toin Node.js serverUse JavaScript/TypeScript access CloudBase services and resources。",
        "index": 1,
        "title": "Install SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```bash\nnpm i @cloudbase/node-sdk dotenv\n```",
            "index": 1,
            "title": "npm"
          },
          {
            "markdown": "```bash\nyarn add @cloudbase/node-sdk dotenv\n```",
            "index": 2,
            "title": "yarn"
          },
          {
            "markdown": "```bash\npnpm add @cloudbase/node-sdk dotenv\n```",
            "index": 3,
            "title": "pnpm"
          }
        ]
      },
      {
        "markdown": "Add the following code to your Node.js project",
        "index": 2,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nconst cloudbaseSDK = require(\"@cloudbase/node-sdk\");\nrequire(\"dotenv\").config();\n\nconst cloudbase = cloudbaseSDK.init({\n  env: process.env.CLOUDBASE_ENV_ID,\n  secretId: process.env.CLOUDBASE_SECRETID,\n  secretKey: process.env.CLOUDBASE_SECRETKEY\n});\n\nmodule.exports = { cloudbase };\n```",
            "index": 1,
            "title": "./utils/cloudbase.js"
          },
          {
            "markdown": "<div class=\"tea-alert tea-alert--brand\" style=\"padding:9px calc(var(--tea-space-100)*4)\">\n<div class=\"tea-alert__info\">\nplease go to <a target=\"_blank\"  class=\"tea-link-external\"  style =\"text-decoration:underline\" href=\"https://console.cloud.tencent.com/cam/capi\">Tencent Cloud Console/APIkey management</a> GenerateAPIkey\n</div>\n</div>\n\n```properties\n# Environment ID\nCLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Tencent CloudAPIkeyID\nCLOUDBASE_SECRET_ID={%SECRET_ID%}\n\n# Tencent CloudAPIkeyKey\nCLOUDBASE_SECRET_KEY={%SECRET_KEY%}\n```",
            "index": 2,
            "title": ".env"
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\n// Query {%TABLE_NAME%} table (limit 10 records)\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n\nconsole.log(\"Query result:\", data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\n// Insert a record into {%TABLE_NAME%} table\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"New Post\", status: \"draft\" })\n  .select();\n\nconsole.log(\"Insert result:\", data);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\n// Update record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ status: \"published\" })\n  .eq(\"id\", 1)\n  .select();\n\nconsole.log(\"Update result:\", data);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\n// Upsert: update on conflict, otherwise insert\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Post Title\", status: \"published\" }, { onConflict: \"id\" })\n  .select();\n\nconsole.log(\"Upsert result:\", data);\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\n// Delete record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", 1);\n\nconsole.log(\"Delete completed:\", error);\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function getData() {\n  // Query {%TABLE_NAME%} table first 10 records\n  const { data, error } = await cloudbase\n    .rdb()\n    .from(\"{%TABLE_NAME%}\")\n    .select(\"*\")\n    .limit(10);\n\n  if (!error) {\n    console.log(\"Querysuccessful:\", data);\n    return data;\n  } else {\n    console.error(\"Queryfailed:\", error);\n  }\n}\n\ngetData();\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function addData() {\n  // Add {%TABLE_NAME%} table data\n  const { data, error } = await cloudbase\n    .rdb()\n    .from(\"{%TABLE_NAME%}\")\n    .insert({ title: \"Example Title\" });\n\n  if (!error) {\n    console.log(\"Insert successful:\", data);\n  } else {\n    console.error(\"Insert failed:\", error);\n  }\n}\n\naddData();\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function updateData() {\n  // Update {%TABLE_NAME%} table id with specified value\n  const { data, error } = await cloudbase\n    .rdb()\n    .from(\"{%TABLE_NAME%}\")\n    .update({ title: \"New Title\" })\n    .eq(\"id\", \"<data id>\");\n\n  if (!error) {\n    console.log(\"Update successful:\", data);\n  } else {\n    console.error(\"Update failed:\", error);\n  }\n}\n\nupdateData();\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function upsertData() {\n  // If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\n  const { data, error } = await cloudbase\n    .rdb()\n    .from(\"{%TABLE_NAME%}\")\n    .upsert({ id: 1, title: \"Example Title\" });\n\n  if (!error) {\n    console.log(\"Operation successful:\", data);\n  } else {\n    console.error(\"Operation failed:\", error);\n  }\n}\n\nupsertData();\n```",
                "index": 4,
                "title": "Upsert Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function deleteData() {\n  // Delete {%TABLE_NAME%} table id with specified value\n  const { data, error } = await cloudbase\n    .rdb()\n    .from(\"{%TABLE_NAME%}\")\n    .delete()\n    .eq(\"id\", \"<data id>\");\n\n  if (!error) {\n    console.log(\"Delete successful:\", data);\n  } else {\n    console.error(\"Delete failed:\", error);\n  }\n}\n\ndeleteData();\n```",
                "index": 5,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function getData() {\n  // Query {%TABLE_NAME%} table first 10 records\n  const db = cloudbase.database();\n  const res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n\n  console.log(\"Querysuccessful:\", res.data);\n  return res.data;\n}\n\ngetData();\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function addData() {\n  try {\n    // Add {%TABLE_NAME%} table data\n    const db = cloudbase.database();\n    const res = await db\n      .collection(\"{%TABLE_NAME%}\")\n      .add({ title: \"Example Title\" });\n\n    console.log(`Insert successful! id: ${res.id}`);\n  } catch (error) {\n    console.error(\"Insert failed:\", error);\n  }\n}\n\naddData();\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function updateData() {\n  try {\n    // Update {%TABLE_NAME%} table id with specified value\n    const db = cloudbase.database();\n    await db\n      .collection(\"{%TABLE_NAME%}\")\n      .doc(\"<data id>\")\n      .update({ title: \"New Title\" });\n\n    console.log(\"Update successful!\");\n  } catch (error) {\n    console.error(\"Update failed:\", error);\n  }\n}\n\nupdateData();\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function deleteData() {\n  try {\n    // Delete {%TABLE_NAME%} table id with specified value\n    const db = cloudbase.database();\n    await db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").remove();\n\n    console.log(\"Delete successful!\");\n  } catch (error) {\n    console.error(\"Delete failed:\", error);\n  }\n}\n\ndeleteData();\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function getData() {\n  // Query {%TABLE_NAME%} Data Modelbefore10recordsData\n  const res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n    pageNumber: 1,\n    pagesize: 10\n  });\n\n  console.log(\"Querysuccessful:\", res.data?.records);\n  return res.data?.records;\n}\n\ngetData();\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function addData() {\n  try {\n    // Add {%TABLE_NAME%} Data ModelData\n    const res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n      data: { title: \"Example Title\" }\n    });\n\n    console.log(`Insert successful! id: ${res.data.id}`);\n  } catch (error) {\n    console.error(\"Insert failed:\", error);\n  }\n}\n\naddData();\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function updateData() {\n  try {\n    // Update {%TABLE_NAME%} Data Model _id with specified value\n    await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n      data: { title: \"New Title\" },\n      filter: { where: { _id: { $eq: \"<data id>\" } } }\n    });\n\n    console.log(\"Update successful!\");\n  } catch (error) {\n    console.error(\"Update failed:\", error);\n  }\n}\n\nupdateData();\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function deleteData() {\n  try {\n    // Delete {%TABLE_NAME%} Data Model _id with specified value\n    await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n      filter: { where: { _id: { $eq: \"<data id>\" } } }\n    });\n\n    console.log(\"Delete successful!\");\n  } catch (error) {\n    console.error(\"Delete failed:\", error);\n  }\n}\n\ndeleteData();\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function callFunction() {\n  // Call {%FUNCTION_NAME%} Cloud Function\n  const res = await cloudbase.callFunction({\n    name: \"{%FUNCTION_NAME%}\",\n    data: {}\n  });\n\n  console.log(\"Cloud FunctionReturn:\", res.result);\n  return res.result;\n}\n\ncallFunction();\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function callRun() {\n  // Call {%SERVICE_NAME%} Cloud Runservice\n  const res = await cloudbase.callContainer({\n    name: \"{%SERVICE_NAME%}\"\n    method: 'POST',\n    path: '/',\n    header:{\n      'Content-Type': 'application/json; charset=utf-8'\n    },\n    data: {},\n  });\n}\n\ncallRun();\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 6,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\nconst fs = require(\"fs\");\n\nasync function uploadFile() {\n  const filePath = \"./example.png\"; // localfilePath\n  const cloudPath = `images/${Date.now()}-example.png`; // Path to upload in cloud\n\n  const res = await cloudbase.uploadFile({\n    cloudPath: cloudPath,\n    fileContent: fs.createReadStream(filePath)\n  });\n\n  console.log(\"Upload successful:\", res.fileID);\n  return res.fileID;\n}\n\nuploadFile();\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function getFileUrl() {\n  const res = await cloudbase.getTempFileURL({\n    fileList: [\"cloud://xxx.png\"] // File fileID list\n  });\n\n  console.log(\"fileURL:\", res.fileList[0].tempFileURL);\n  return res.fileList[0].tempFileURL;\n}\n\ngetFileUrl();\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\nconst fs = require(\"fs\");\n\nasync function downloadFile() {\n  const res = await cloudbase.downloadFile({\n    fileID: \"cloud://xxx.png\" // File fileID\n  });\n\n  // willfileSave to local\n  fs.writeFileSync(\"./downloaded-file.png\", res.fileContent);\n  console.log(\"Downloadsuccessful!\");\n}\n\ndownloadFile();\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function deleteFile() {\n  const res = await cloudbase.deleteFile({\n    fileList: [\"cloud://xxx.png\"] // File fileID list\n  });\n\n  if (res.fileList[0].code === \"SUCCESS\") {\n    console.log(\"Delete successful!\");\n  } else {\n    console.error(\"Delete failed:\", res.fileList);\n  }\n}\n\ndeleteFile();\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function callAIModel(input) {\n  const ai = cloudbase.ai();\n  const model = ai.createModel(\"{%AI_MODEL_NAME%}\");\n  await auth.signInAnonymously();\n\n  try {\n    console.log(\"currentlyinGeneratepoem...\");\n    const res = await model.streamText({\n      model: \"{%AI_SUB_MODEL_NAME%}\",\n      messages: [\n        {\n          role: \"system\",\n          content:\n            \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\"\n        },\n        { role: \"user\", content: input }\n      ]\n    });\n\n    let response = \"\";\n    for await (let str of res.textStream) {\n      process.stdout.write(str);\n      response += str;\n    }\n    console.log(\"\\nGenerateDone！\");\n    return response;\n  } catch (err) {\n    console.error(\"poemGeneration failed:\", err);\n    return null;\n  }\n}\n\n// CallExample\ncallAIModel(\"Spring\");\n```",
                "index": 1,
                "title": "SDKCall",
                "content": []
              },
              {
                "markdown": "<div class=\"tea-alert tea-alert--brand\" style=\"padding:9px calc(var(--tea-space-100)*4)\">\n<div class=\"tea-alert__info\">\ngo to <a target=\"_blank\" class=\"tea-link-external\" style=\"text-decoration:underline\" href=\"https://tcb.cloud.tencent.com/dev#/env/apikey\">EnvironmentConfiguration</a> Getserver API Key。\n</div>\n</div>\n\n**Install Dependencies**\n\n```bash\nnpm i @langchain/openai\n```\n\n**Usage Example：**\n\n```js\nconst { ChatOpenAI } = require(\"@langchain/openai\");\n\nconst model = new ChatOpenAI({\n  modelName: \"{%AI_SUB_MODEL_NAME%}\",\n  apiKey: \"<CLOUDBASE_API_KEY>\",\n  configuration: {\n    baseURL: \"https://{%ENV_ID%}.api.tcloudbasegateway.com/v1/ai/{%AI_MODEL_NAME%}/v1\"\n  }\n});\n\nasync function main() {\n  const response = await model.invoke(\"Hello\");\n  console.log(\"AIanswer:\", response.content);\n}\n\nmain();\n```",
                "index": 2,
                "title": "LangChain",
                "content": []
              },
              {
                "markdown": "<div class=\"tea-alert tea-alert--brand\" style=\"padding:9px calc(var(--tea-space-100)*4)\">\n<div class=\"tea-alert__info\">\ngo to <a target=\"_blank\" class=\"tea-link-external\" style=\"text-decoration:underline\" href=\"https://tcb.cloud.tencent.com/dev#/env/apikey\">EnvironmentConfiguration</a> Getserver API Key。\n</div>\n</div>\n\n**Install Dependencies**\n\n```bash\nnpm i openai\n```\n\n**Usage Example：**\n\n```js\nconst OpenAI = require(\"openai\");\n\nconst client = new OpenAI({\n  apiKey: \"<CLOUDBASE_API_KEY>\",\n  baseURL: \"https://{%ENV_ID%}.api.tcloudbasegateway.com/v1/ai/{%AI_MODEL_NAME%}/v1\"\n});\n\nasync function main() {\n  const completion = await client.chat.completions.create({\n    model: \"{%AI_SUB_MODEL_NAME%}\",\n    messages: [\n      { role: \"user\", content: \"hi\" }\n    ],\n    temperature: 0.3,\n    stream: true\n  });\n\n  for await (const chunk of completion) {\n    console.log(chunk);\n  }\n}\n\nmain();\n```",
                "index": 3,
                "title": "OpenAI SDK",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function generateImage() {\n  // Call image generation cloud function\n  const res = await cloudbase.callFunction({\n    name: \"<YOUR_FUNCTION_NAME>\",\n    data: {\n      prompt: \"A cute cat playing in the sunshine\"\n    }\n  });\n\n  const result = res.result;\n\n  if (result.success) {\n    // Generation successful\n    console.log(\"Generation successful!\");\n    console.log(\"Image URL:\", result.imageUrl);\n    console.log(\"Optimized prompt:\", result.revised_prompt);\n\n    // Use image\n    // Note: Image URL is valid for 24 hours, please save or transfer promptly\n  } else {\n    // Generation failed\n    console.error(\"Generation failed:\", result.code, result.message);\n  }\n}\n\ngenerateImage();\n```",
                "index": 4,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst { cloudbase } = require('./utils/cloudbase');\n\nasync function callAgent(input) {\n  const ai = cloudbase.ai();\n  await auth.signInAnonymously();\n\n  try {\n    console.log('currentlyinGenerateanswer...');\n    const res = await ai.bot.sendMessage({\n      botId: '{%AGENT_ID%}', // to replacefor yourAgentId\n      // Refer to frontend-backend communication protocol for input structure：\n      //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n      threadId: '550e8400-e29b-41d4-a716-446655440000',\n      runId: 'run_001',\n      messages: [\n        {\n          id: 'msg_001',\n          role: 'user',\n          content: 'Hello',\n        },\n      ],\n      tools: [],\n      context: [],\n      state: {},\n      forwardedProps: {},\n    });\n\n    let response = '';\n    for await (let str of res.textStream) {\n      process.stdout.write(str);\n      response += str;\n    }\n    console.log('\\nGenerateDone！');\n    return response;\n  } catch (err) {\n    console.error('Generation failed:', err);\n    return null;\n  }\n}\n\n// CallExample\ncallAgent('Who are you');\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function callAgent(input) {\n  const ai = cloudbase.ai();\n  await auth.signInAnonymously();\n\n  try {\n    console.log(\"currentlyinGenerateanswer...\");\n    const res = await ai.bot.sendMessage({\n      botId: \"{%AGENT_ID%}\", // to replacefor yourAgentId\n      msg: input\n    });\n\n    let response = \"\";\n    for await (let str of res.textStream) {\n      process.stdout.write(str);\n      response += str;\n    }\n    console.log(\"\\nGenerateDone！\");\n    return response;\n  } catch (err) {\n    console.error(\"Generation failed:\", err);\n    return null;\n  }\n}\n\n// CallExample\ncallAgent(\"Who are you\");\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          }
        ]
      }
    ],
    "_id": "36e9b7bb697c28da0038bcad209e0175",
    "_openid": "anon",
    "createdAt": 1769744602618,
    "updatedAt": 1770105393504
  },
  {
    "category": "CloudBase MCP,Google Antigravity",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 104,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/antigravity",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.agent/rules/`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Antigravity\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "4584478b69a9286e0042197b67416221",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "Framework Integration,Web Frameworks,UniApp",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 12,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/api-reference/webv2/adapter/uniapp-adapter",
    "content": [
      {
        "markdown": "`@cloudbase/js-sdk` Combine with `@cloudbase/adapter-uni-app` allows you toin uni-app project",
        "index": 1,
        "title": "Install SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```bash\nnpm i @cloudbase/js-sdk @cloudbase/adapter-uni-app\n```",
            "index": 1,
            "title": "npm",
            "content": []
          },
          {
            "markdown": "```bash\nyarn add @cloudbase/js-sdk @cloudbase/adapter-uni-app\n```",
            "index": 2,
            "title": "yarn",
            "content": []
          },
          {
            "markdown": "```bash\npnpm add @cloudbase/js-sdk @cloudbase/adapter-uni-app\n```",
            "index": 3,
            "title": "pnpm",
            "content": []
          }
        ]
      },
      {
        "markdown": "Add the following code to your uni-app project",
        "index": 2,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nimport cloudbaseSDK from \"@cloudbase/js-sdk\";\nimport adapter from \"@cloudbase/adapter-uni-app\";\n\n// passed inConfigurationoption\nconst options = {\n  uni: uni // passed in uni object，for imageVerification codeFunction\n};\n\ncloudbaseSDK.useAdapters(adapter, options);\n\nconst cloudbase = cloudbaseSDK.init({\n  // Environment ID\n  env: \"{%ENV_ID%}\",\n  // region\n  region: \"{%REGION%}\",\n  // Anonymous access token\n  accessKey: \"{%PUBLISHABLE_KEY%}\"\n});\n\nexport default cloudbase;\n```",
            "index": 1,
            "title": "./utils/cloudbase.js",
            "content": []
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nimport { cloudbase } from \"@/utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table (limit 10 records)\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n\nconsole.log(\"Query result:\", data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nimport { cloudbase } from \"@/utils/cloudbase\";\n\n// Insert a record into {%TABLE_NAME%} table\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"New Post\", status: \"draft\" })\n  .select();\n\nconsole.log(\"Insert result:\", data);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nimport { cloudbase } from \"@/utils/cloudbase\";\n\n// Update record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ status: \"published\" })\n  .eq(\"id\", 1)\n  .select();\n\nconsole.log(\"Update result:\", data);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nimport { cloudbase } from \"@/utils/cloudbase\";\n\n// Upsert: update on conflict, otherwise insert\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Post Title\", status: \"published\" }, { onConflict: \"id\" })\n  .select();\n\nconsole.log(\"Upsert result:\", data);\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```js\nimport { cloudbase } from \"@/utils/cloudbase\";\n\n// Delete record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", 1);\n\nconsole.log(\"Delete completed:\", error);\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table first 10 records\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\nconsole.log(res.data);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"getData\">Query Data</button>\n    <view v-if=\"dataList.length > 0\">\n      <view v-for=\"(item, index) in dataList\" :key=\"index\" class=\"data-item\">\n        <text>{{ JSON.stringify(item) }}</text>\n      </view>\n    </view>\n    <text v-else>temporarilyNoneData</text>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataList: []\n    };\n  },\n  methods: {\n    // Query Data\n    async getData() {\n      try {\n        const { data, error } = await cloudbase\n          .database()\n          .from(\"{%TABLE_NAME%}\")\n          .select(\"*\")\n          .limit(10);\n\n        if (!error) {\n          this.dataList = data;\n          uni.showToast({\n            title: \"Querysuccessful\",\n            icon: \"success\"\n          });\n        } else {\n          uni.showToast({\n            title: \"Queryfailed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        uni.showToast({\n          title: \"Queryfailed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} table data\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({ title: \"Example Title\" });\nconsole.log(`Insert successful! id: ${res.id}`);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Title：</text>\n      <input v-model=\"title\" placeholder=\"Please enterTitle\" />\n    </view>\n    <button :disabled=\"!title\" @click=\"addData\">Insert Data</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      title: \"\"\n    };\n  },\n  methods: {\n    // Insert Data\n    async addData() {\n      try {\n        const { data, error } = await cloudbase\n          .database()\n          .from(\"{%TABLE_NAME%}\")\n          .insert({ title: this.title });\n\n        if (!error) {\n          uni.showToast({\n            title: \"Insert successful\",\n            icon: \"success\"\n          });\n          this.title = \"\";\n        } else {\n          uni.showToast({\n            title: \"Insert failed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        uni.showToast({\n          title: \"Insert failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} table id with specified value\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ title: \"New Title\" })\n  .eq(\"id\", \"<data id>\");\nif (!error) {\n  console.log(\"Update successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>DataID：</text>\n      <input v-model=\"dataId\" placeholder=\"Please enterDataID\" />\n    </view>\n    <view>\n      <text>New Title：</text>\n      <input v-model=\"newTitle\" placeholder=\"Please enterNew Title\" />\n    </view>\n    <button :disabled=\"!dataId || !newTitle\" @click=\"updateData\">\n      Update Data\n    </button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataId: \"\",\n      newTitle: \"\"\n    };\n  },\n  methods: {\n    // Update Data\n    async updateData() {\n      try {\n        const { data, error } = await cloudbase\n          .database()\n          .from(\"{%TABLE_NAME%}\")\n          .update({ title: this.newTitle })\n          .eq(\"id\", this.dataId);\n\n        if (!error) {\n          uni.showToast({\n            title: \"Update successful\",\n            icon: \"success\"\n          });\n          this.dataId = \"\";\n          this.newTitle = \"\";\n        } else {\n          uni.showToast({\n            title: \"Update failed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        uni.showToast({\n          title: \"Update failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Example Title\" });\nif (!error) {\n  console.log(\"Operation successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>ID：</text>\n      <input v-model=\"id\" type=\"number\" placeholder=\"Please enterID\" />\n    </view>\n    <view>\n      <text>Title：</text>\n      <input v-model=\"title\" placeholder=\"Please enterTitle\" />\n    </view>\n    <button :disabled=\"!id || !title\" @click=\"upsertData\">UpdateorCreate</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      id: \"\",\n      title: \"\"\n    };\n  },\n  methods: {\n    // Upsert Data\n    async upsertData() {\n      try {\n        const { data, error } = await cloudbase\n          .database()\n          .from(\"{%TABLE_NAME%}\")\n          .upsert({ id: parseInt(this.id), title: this.title });\n\n        if (!error) {\n          uni.showToast({\n            title: \"Operation successful\",\n            icon: \"success\"\n          });\n          this.id = \"\";\n          this.title = \"\";\n        } else {\n          uni.showToast({\n            title: \"Operation failed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        uni.showToast({\n          title: \"Operation failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} table id with specified value\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", \"<data id>\");\nif (!error) {\n  console.log(\"Delete successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>DataID：</text>\n      <input v-model=\"dataId\" placeholder=\"Please entershouldDeleteDataID\" />\n    </view>\n    <button :disabled=\"!dataId\" @click=\"deleteData\">Delete Data</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataId: \"\"\n    };\n  },\n  methods: {\n    // Delete Data\n    async deleteData() {\n      try {\n        const { data, error } = await cloudbase\n          .database()\n          .from(\"{%TABLE_NAME%}\")\n          .delete()\n          .eq(\"id\", this.dataId);\n\n        if (!error) {\n          uni.showToast({\n            title: \"Delete successful\",\n            icon: \"success\"\n          });\n          this.dataId = \"\";\n        } else {\n          uni.showToast({\n            title: \"Delete failed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        uni.showToast({\n          title: \"Delete failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table first 10 records\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\nconsole.log(res.data);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"getData\">Query Data</button>\n    <view v-if=\"dataList.length > 0\">\n      <view v-for=\"(item, index) in dataList\" :key=\"index\" class=\"data-item\">\n        <text>{{ JSON.stringify(item) }}</text>\n      </view>\n    </view>\n    <text v-else>temporarilyNoneData</text>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataList: []\n    };\n  },\n  methods: {\n    // Query Data\n    async getData() {\n      try {\n        const db = cloudbase.database();\n        const res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n\n        this.dataList = res.data;\n        uni.showToast({\n          title: \"Querysuccessful\",\n          icon: \"success\"\n        });\n      } catch (error) {\n        uni.showToast({\n          title: \"Queryfailed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} table data\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({ title: \"Example Title\" });\nconsole.log(`Insert successful! id: ${res.id}`);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Title：</text>\n      <input v-model=\"title\" placeholder=\"Please enterTitle\" />\n    </view>\n    <button :disabled=\"!title\" @click=\"addData\">Insert Data</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      title: \"\"\n    };\n  },\n  methods: {\n    // Insert Data\n    async addData() {\n      try {\n        const db = cloudbase.database();\n        const res = await db\n          .collection(\"{%TABLE_NAME%}\")\n          .add({ title: this.title });\n\n        uni.showToast({\n          title: `Insert successful! id: ${res.id}`,\n          icon: \"success\"\n        });\n        this.title = \"\";\n      } catch (error) {\n        uni.showToast({\n          title: \"Insert failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} table id with specified value\nconst db = cloudbase.database();\nawait db\n  .collection(\"{%TABLE_NAME%}\")\n  .doc(\"<data id>\")\n  .update({ title: \"New Title\" });\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>DataID：</text>\n      <input v-model=\"dataId\" placeholder=\"Please enterDataID\" />\n    </view>\n    <view>\n      <text>New Title：</text>\n      <input v-model=\"newTitle\" placeholder=\"Please enterNew Title\" />\n    </view>\n    <button :disabled=\"!dataId || !newTitle\" @click=\"updateData\">\n      Update Data\n    </button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataId: \"\",\n      newTitle: \"\"\n    };\n  },\n  methods: {\n    // Update Data\n    async updateData() {\n      try {\n        const db = cloudbase.database();\n        await db\n          .collection(\"{%TABLE_NAME%}\")\n          .doc(this.dataId)\n          .update({ title: this.newTitle });\n\n        uni.showToast({\n          title: \"Update successful\",\n          icon: \"success\"\n        });\n        this.dataId = \"\";\n        this.newTitle = \"\";\n      } catch (error) {\n        uni.showToast({\n          title: \"Update failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} table id with specified value\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").remove();\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>DataID：</text>\n      <input v-model=\"dataId\" placeholder=\"Please entershouldDeleteDataID\" />\n    </view>\n    <button :disabled=\"!dataId\" @click=\"deleteData\">Delete Data</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataId: \"\"\n    };\n  },\n  methods: {\n    // Delete Data\n    async deleteData() {\n      try {\n        const db = cloudbase.database();\n        await db.collection(\"{%TABLE_NAME%}\").doc(this.dataId).remove();\n\n        uni.showToast({\n          title: \"Delete successful\",\n          icon: \"success\"\n        });\n        this.dataId = \"\";\n      } catch (error) {\n        uni.showToast({\n          title: \"Delete failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} Data Modelbefore10recordsData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\nconsole.log(res.data?.records);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"getData\">Query Data</button>\n    <view v-if=\"dataList.length > 0\">\n      <view v-for=\"(item, index) in dataList\" :key=\"index\" class=\"data-item\">\n        <text>{{ JSON.stringify(item) }}</text>\n      </view>\n    </view>\n    <text v-else>temporarilyNoneData</text>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataList: []\n    };\n  },\n  methods: {\n    // Query Data\n    async getData() {\n      try {\n        const res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n          pageNumber: 1,\n          pagesize: 10\n        });\n\n        this.dataList = res.data?.records || [];\n        uni.showToast({\n          title: \"Querysuccessful\",\n          icon: \"success\"\n        });\n      } catch (error) {\n        uni.showToast({\n          title: \"Queryfailed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} Data ModelData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: { title: \"Example Title\" }\n});\nconsole.log(`Insert successful! id: ${res.data.id}`);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Title：</text>\n      <input v-model=\"title\" placeholder=\"Please enterTitle\" />\n    </view>\n    <button :disabled=\"!title\" @click=\"addData\">Insert Data</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      title: \"\"\n    };\n  },\n  methods: {\n    // Insert Data\n    async addData() {\n      try {\n        const res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n          data: { title: this.title }\n        });\n\n        uni.showToast({\n          title: `Insert successful! id: ${res.data.id}`,\n          icon: \"success\"\n        });\n        this.title = \"\";\n      } catch (error) {\n        uni.showToast({\n          title: \"Insert failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} Data Model _id with specified value\nawait cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: { title: \"New Title\" },\n  filter: { where: { _id: { $eq: \"<data id>\" } } }\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>DataID：</text>\n      <input v-model=\"dataId\" placeholder=\"Please enterDataID\" />\n    </view>\n    <view>\n      <text>New Title：</text>\n      <input v-model=\"newTitle\" placeholder=\"Please enterNew Title\" />\n    </view>\n    <button :disabled=\"!dataId || !newTitle\" @click=\"updateData\">\n      Update Data\n    </button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataId: \"\",\n      newTitle: \"\"\n    };\n  },\n  methods: {\n    // Update Data\n    async updateData() {\n      try {\n        await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n          data: { title: this.newTitle },\n          filter: { where: { _id: { $eq: this.dataId } } }\n        });\n\n        uni.showToast({\n          title: \"Update successful\",\n          icon: \"success\"\n        });\n        this.dataId = \"\";\n        this.newTitle = \"\";\n      } catch (error) {\n        uni.showToast({\n          title: \"Update failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} Data Model _id with specified value\nawait cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: { where: { _id: { $eq: \"<data id>\" } } }\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>DataID：</text>\n      <input v-model=\"dataId\" placeholder=\"Please entershouldDeleteDataID\" />\n    </view>\n    <button :disabled=\"!dataId\" @click=\"deleteData\">Delete Data</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      dataId: \"\"\n    };\n  },\n  methods: {\n    // Delete Data\n    async deleteData() {\n      try {\n        await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n          filter: { where: { _id: { $eq: this.dataId } } }\n        });\n\n        uni.showToast({\n          title: \"Delete successful\",\n          icon: \"success\"\n        });\n        this.dataId = \"\";\n      } catch (error) {\n        uni.showToast({\n          title: \"Delete failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Call {%FUNCTION_NAME%} Cloud Function\nconst res = await cloudbase.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {}\n});\nconsole.log(res.result);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"callFunction\">CallCloud Function</button>\n    <view v-if=\"result\">\n      <text>Return result：</text>\n      <text>{{ JSON.stringify(result) }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      result: null\n    };\n  },\n  methods: {\n    // CallCloud Function\n    async callFunction() {\n      try {\n        const res = await cloudbase.callFunction({\n          name: \"{%FUNCTION_NAME%}\",\n          data: {}\n        });\n\n        this.result = res.result;\n        uni.showToast({\n          title: \"Callsuccessful\",\n          icon: \"success\"\n        });\n      } catch (error) {\n        uni.showToast({\n          title: \"Call failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function",
            "content": []
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call {%SERVICE_NAME%} Cloud Runservice\nconst res = await cloudbase.callContainer({\n  name: \"{%SERVICE_NAME%}\"\n  method: 'POST',\n  path: '/',\n  header:{\n    'Content-Type': 'application/json; charset=utf-8'\n  },\n  data: {},\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"callRun\">CallCloud Run</button>\n    <view v-if=\"result\">\n      <text>Return result：</text>\n      <text>{{ JSON.stringify(result) }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      result: null\n    };\n  },\n  methods: {\n    // CallCloud Run\n    async callRun() {\n      try {\n        // Call {%SERVICE_NAME%} Cloud Runservice\n        const res = await cloudbase.callContainer({\n          name: \"{%SERVICE_NAME%}\"\n          method: 'POST',\n          path: '/',\n          header:{\n            'Content-Type': 'application/json; charset=utf-8'\n          },\n          data: {},\n        });\n\n        this.result = res;\n        uni.showToast({\n          title: \"Callsuccessful\",\n          icon: \"success\"\n        });\n      } catch (error) {\n        uni.showToast({\n          title: \"Call failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run",
            "content": []
          },
          {
            "index": 6,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.uploadFile({\n  cloudPath: `images/${Date.now()}-${file.name}`, // Path to upload in cloud\n  filePath: file\n});\nconsole.log(res.fileID);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"uploadFile\">SelectandUploadImage</button>\n    <view v-if=\"fileId\">\n      <text>Upload successful！</text>\n      <text>fileID: {{ fileId }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      fileId: \"\"\n    };\n  },\n  methods: {\n    // Upload File\n    async uploadFile() {\n      uni.chooseImage({\n        count: 1,\n        success: async chooseImageRes => {\n          try {\n            uni.showLoading({\n              title: \"Upload...\"\n            });\n\n            const tempFilePath = chooseImageRes.tempFilePaths[0];\n            const cloudPath = `images/${Date.now()}-${Math.random()}.png`;\n\n            const res = await cloudbase.uploadFile({\n              cloudPath: cloudPath,\n              filePath: tempFilePath\n            });\n\n            this.fileId = res.fileID;\n            uni.hideLoading();\n            uni.showToast({\n              title: \"Upload successful\",\n              icon: \"success\"\n            });\n          } catch (error) {\n            uni.hideLoading();\n            uni.showToast({\n              title: \"Uploadfailed：\" + error.message,\n              icon: \"none\"\n            });\n          }\n        }\n      });\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "title": "Upload File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.getTempFileURL({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\nconsole.log(res.fileList[0].tempFileURL);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>fileID：</text>\n      <input v-model=\"fileId\" placeholder=\"Please enterfileID (cloud://xxx.png)\" />\n    </view>\n    <button :disabled=\"!fileId\" @click=\"getFileUrl\">Get File URL</button>\n    <view v-if=\"fileUrl\">\n      <text>fileURL：</text>\n      <text>{{ fileUrl }}</text>\n      <image :src=\"fileUrl\" mode=\"aspectFit\"></image>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      fileId: \"\",\n      fileUrl: \"\"\n    };\n  },\n  methods: {\n    // Get File URL\n    async getFileUrl() {\n      try {\n        const res = await cloudbase.getTempFileURL({\n          fileList: [this.fileId]\n        });\n\n        this.fileUrl = res.fileList[0].tempFileURL;\n        uni.showToast({\n          title: \"Getsuccessful\",\n          icon: \"success\"\n        });\n      } catch (error) {\n        uni.showToast({\n          title: \"Getfailed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Get File URL"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nawait cloudbase.downloadFile({\n  fileID: \"cloud://xxx.png\" // File fileID\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>fileID：</text>\n      <input v-model=\"fileId\" placeholder=\"Please enterfileID (cloud://xxx.png)\" />\n    </view>\n    <button :disabled=\"!fileId\" @click=\"downloadFile\">Download File</button>\n    <view v-if=\"localPath\">\n      <text>Downloadsuccessful！</text>\n      <text>localPath: {{ localPath }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      fileId: \"\",\n      localPath: \"\"\n    };\n  },\n  methods: {\n    // Download File\n    async downloadFile() {\n      try {\n        uni.showLoading({\n          title: \"Download...\"\n        });\n\n        const res = await cloudbase.downloadFile({\n          fileID: this.fileId\n        });\n\n        this.localPath = res.tempFilePath;\n        uni.hideLoading();\n        uni.showToast({\n          title: \"Downloadsuccessful\",\n          icon: \"success\"\n        });\n      } catch (error) {\n        uni.hideLoading();\n        uni.showToast({\n          title: \"Downloadfailed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Download File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.deleteFile({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\nif (res.fileList[0].code === \"SUCCESS\") {\n  console.log(\"Delete successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>fileID：</text>\n      <input v-model=\"fileId\" placeholder=\"Please enterfileID (cloud://xxx.png)\" />\n    </view>\n    <button :disabled=\"!fileId\" @click=\"deleteFile\">Delete File</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      fileId: \"\"\n    };\n  },\n  methods: {\n    // Delete File\n    async deleteFile() {\n      try {\n        const res = await cloudbase.deleteFile({\n          fileList: [this.fileId]\n        });\n\n        if (res.fileList[0].code === \"SUCCESS\") {\n          uni.showToast({\n            title: \"Delete successful\",\n            icon: \"success\"\n          });\n          this.fileId = \"\";\n        } else {\n          uni.showToast({\n            title: \"Delete failed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        uni.showToast({\n          title: \"Delete failed：\" + error.message,\n          icon: \"none\"\n        });\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Delete File"
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase\n  .ai()\n  .createModel(\"{%AI_MODEL_NAME%}\")\n  .streamText({\n    model: \"{%AI_SUB_MODEL_NAME%}\",\n    messages: [{ role: \"user\", content: \"Hello\" }]\n  });\n\nfor await (let data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data?.choices?.[0]?.delta?.reasoning_content;\n  if (think) console.log(think);\n\n  // Print generated text content\n  const text = data?.choices?.[0]?.delta?.content;\n  if (text) console.log(text);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Inputtopic：</text>\n      <input v-model=\"input\" placeholder=\"Please entertopic，such as：Spring\" />\n    </view>\n    <button :disabled=\"!input || isGenerating\" @click=\"callAIModel\">\n      GenerateContent\n    </button>\n    <view v-if=\"response\">\n      <text>GenerateResult：</text>\n      <text>{{ response }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      input: \"\",\n      response: \"\",\n      isGenerating: false\n    };\n  },\n  methods: {\n    // CallAI Model\n    async callAIModel() {\n      this.isGenerating = true;\n      this.response = \"\";\n\n      try {\n        // EnsurealreadyLogin\n        const loginState = await cloudbase.auth().getLoginState();\n        if (!loginState) {\n          await cloudbase.auth().signInAnonymously();\n        }\n\n        uni.showLoading({\n          title: \"Generating...\"\n        });\n\n        const res = await cloudbase\n          .ai()\n          .createModel(\"<YOUR_AI_MODEL_NAME>\")\n          .streamText({\n            model: \"<YOUR_AI_SUB_MODEL_NAME>\",\n            messages: [{ role: \"user\", content: this.input }]\n          });\n\n        for await (let str of res.textStream) {\n          this.response += str;\n        }\n\n        uni.hideLoading();\n        uni.showToast({\n          title: \"GenerateDone\",\n          icon: \"success\"\n        });\n      } catch (err) {\n        uni.hideLoading();\n        uni.showToast({\n          title: \"Generation failed：\" + err.message,\n          icon: \"none\"\n        });\n      } finally {\n        this.isGenerating = false;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation"
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call image generation cloud function\nconst res = await cloudbase.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: {\n    prompt: \"A cute cat playing in the sunshine\"\n  }\n});\n\nconst result = res.result;\n\nif (result.success) {\n  // Generation successful\n  console.log(\"Generation successful!\");\n  console.log(\"Image URL:\", result.imageUrl);\n  console.log(\"Optimized prompt:\", result.revised_prompt);\n\n  // Use image\n  // Note: Image URL is valid for 24 hours, please save or transfer promptly\n} else {\n  // Generation failed\n  console.error(\"Generation failed:\", result.code, result.message);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>ImageDescription：</text>\n      <input v-model=\"prompt\" placeholder=\"Enter image description\" />\n    </view>\n    <button :disabled=\"!prompt || loading\" @click=\"generateImage\">\n      {{ loading ? \"Generating...\" : \"Generate Image\" }}\n    </button>\n    <view v-if=\"message\">\n      <text :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\">\n        {{ message }}\n      </text>\n    </view>\n    <view v-if=\"imageUrl\">\n      <image :src=\"imageUrl\" mode=\"aspectFit\" style=\"width: 100%\"></image>\n      <text style=\"font-size: 12px; color: #666\">\n        Note: Image URL is valid for 24 hours, please save promptly\n      </text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      prompt: \"\",\n      imageUrl: \"\",\n      message: \"\",\n      loading: false\n    };\n  },\n  methods: {\n    // Generate Image\n    async generateImage() {\n      this.loading = true;\n      this.message = \"\";\n      this.imageUrl = \"\";\n\n      try {\n        uni.showLoading({\n          title: \"Generating...\"\n        });\n\n        // Call image generation cloud function\n        const res = await cloudbase.callFunction({\n          name: \"<YOUR_FUNCTION_NAME>\",\n          data: {\n            prompt: this.prompt\n          }\n        });\n\n        const result = res.result;\n\n        if (result.success) {\n          this.imageUrl = result.imageUrl;\n          this.message = \"Generation successful！\";\n          uni.hideLoading();\n          uni.showToast({\n            title: \"Generation successful\",\n            icon: \"success\"\n          });\n        } else {\n          this.message = `Generation failed：${result.message}`;\n          uni.hideLoading();\n          uni.showToast({\n            title: \"Generation failed\",\n            icon: \"none\"\n          });\n        }\n      } catch (error) {\n        this.message = \"Call failed：\" + error.message;\n        uni.hideLoading();\n        uni.showToast({\n          title: \"Call failed\",\n          icon: \"none\"\n        });\n      } finally {\n        this.loading = false;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation"
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from './utils/cloudbase';\n\nconst res = await cloudbase.ai().bot.sendMessage({\n  botId: '{%AGENT_ID%}',\n  // Refer to frontend-backend communication protocol for input structure：\n  //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n  threadId: '550e8400-e29b-41d4-a716-446655440000',\n  runId: 'run_001',\n  messages: [\n    {\n      id: 'msg_001',\n      role: 'user',\n      content: 'Hello',\n    },\n  ],\n  tools: [],\n  context: [],\n  state: {},\n  forwardedProps: {},\n});\n\nfor await (const data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data.reasoning_content;\n  if (think) console.log(think);\n\n  // Print output content\n  const content = data.content;\n  if (content) console.log(content);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Inputquestion：</text>\n      <input v-model=\"input\" placeholder=\"Please enterquestion，such as：Who are you\" />\n    </view>\n    <button :disabled=\"!input || isGenerating\" @click=\"callAgent\">\n      SendMessage\n    </button>\n    <view v-if=\"response\">\n      <text>answer：</text>\n      <text>{{ response }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      input: \"\",\n      response: \"\",\n      isGenerating: false\n    };\n  },\n  methods: {\n    // CallAgent\n    async callAgent() {\n      this.isGenerating = true;\n      this.response = \"\";\n\n      try {\n        // EnsurealreadyLogin\n        const loginState = await cloudbase.auth().getLoginState();\n        if (!loginState) {\n          await cloudbase.auth().signInAnonymously();\n        }\n\n        uni.showLoading({\n          title: \"Generating...\"\n        });\n\n        const res = await cloudbase.ai().bot.sendMessage({\n          botId: \"{%AGENT_ID%}\",\n          // Refer to frontend-backend communication protocol for input structure：\n          //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n          threadId: '550e8400-e29b-41d4-a716-446655440000',\n          runId: 'run_001',\n          messages: [\n            {\n              id: 'msg_001',\n              role: 'user',\n              content: 'Hello',\n            },\n          ],\n          tools: [],\n          context: [],\n          state: {},\n          forwardedProps: {},\n        });\n\n        for await (const data of res.dataStream) {\n          // Print reasoning content if available\n          const think = data.reasoning_content;\n          if (think) this.response += think;\n\n          // Print output content\n          const content = data.content;\n          if (content) this.response += content;\n        }\n\n        uni.hideLoading();\n        uni.showToast({\n          title: \"GenerateDone\",\n          icon: \"success\"\n        });\n      } catch (err) {\n        uni.hideLoading();\n        uni.showToast({\n          title: \"Generation failed：\" + err.message,\n          icon: \"none\"\n        });\n      } finally {\n        this.isGenerating = false;\n      }\n    }\n  }\n};\n</script>\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.ai().bot.sendMessage({\n  botId: \"{%AGENT_ID%}\",\n  msg: \"Hello\"\n});\n\nfor await (const data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data.reasoning_content;\n  if (think) console.log(think);\n\n  // Print output content\n  const content = data.content;\n  if (content) console.log(content);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Inputquestion：</text>\n      <input v-model=\"input\" placeholder=\"Please enterquestion，such as：Who are you\" />\n    </view>\n    <button :disabled=\"!input || isGenerating\" @click=\"callAgent\">\n      SendMessage\n    </button>\n    <view v-if=\"response\">\n      <text>answer：</text>\n      <text>{{ response }}</text>\n    </view>\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      input: \"\",\n      response: \"\",\n      isGenerating: false\n    };\n  },\n  methods: {\n    // CallAgent\n    async callAgent() {\n      this.isGenerating = true;\n      this.response = \"\";\n\n      try {\n        // EnsurealreadyLogin\n        const loginState = await cloudbase.auth().getLoginState();\n        if (!loginState) {\n          await cloudbase.auth().signInAnonymously();\n        }\n\n        uni.showLoading({\n          title: \"Generating...\"\n        });\n\n        const res = await cloudbase.ai().bot.sendMessage({\n          botId: \"{%AGENT_ID%}\",\n          msg: \"Hello\"\n        });\n\n        for await (const data of res.dataStream) {\n          // Print reasoning content if available\n          const think = data.reasoning_content;\n          if (think) this.response += think;\n\n          // Print output content\n          const content = data.content;\n          if (content) this.response += content;\n        }\n\n        uni.hideLoading();\n        uni.showToast({\n          title: \"GenerateDone\",\n          icon: \"success\"\n        });\n      } catch (err) {\n        uni.hideLoading();\n        uni.showToast({\n          title: \"Generation failed：\" + err.message,\n          icon: \"none\"\n        });\n      } finally {\n        this.isGenerating = false;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 9,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "Use **SMS Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMSVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: phone });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  phone_number: `+86 ${phone}`,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${phone.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Phone number：</text>\n      <input v-model=\"phone\" placeholder=\"13800000000\" />\n    </view>\n    <view>\n      <text>Verification code：</text>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button :disabled=\"!phone\" @click=\"sendCode\">Send Code</button>\n    </view>\n    <button :disabled=\"!verificationId || !code\" @click=\"register\">Register</button>\n    <text\n      v-if=\"message\"\n      :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\"\n      >{{ message }}</text\n    >\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      phone: \"\",\n      code: \"\",\n      verificationId: \"\",\n      message: \"\"\n    };\n  },\n  methods: {\n    // Send Code\n    async sendCode() {\n      try {\n        const auth = cloudbase.auth();\n        const res = await auth.getVerification({ phone_number: this.phone });\n        this.verificationId = res.verification_id;\n        this.message = \"Verification code sent！\";\n      } catch (error) {\n        this.message = \"Send failed：\" + error.message;\n      }\n    },\n\n    // Register\n    async register() {\n      try {\n        const auth = cloudbase.auth();\n        // Verify the code\n        const verifyRes = await auth.verify({\n          verification_id: this.verificationId,\n          verification_code: this.code\n        });\n        // Register (auto-login if user exists)\n        await auth.signUp({\n          phone_number: `+86 ${this.phone}`,\n          verification_code: this.code,\n          verification_token: verifyRes.verification_token,\n          name: `user_${this.phone.slice(-4)}`,\n          password: \"admin@123\"\n        });\n        this.message = \"Registration successful！\";\n      } catch (error) {\n        this.message = \"Registration failed：\" + error.message;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 1,
                "title": "SMS Code Registration"
              },
              {
                "markdown": "Use **Email Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  email,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${email.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Email：</text>\n      <input v-model=\"email\" placeholder=\"example@email.com\" />\n    </view>\n    <view>\n      <text>Verification code：</text>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button :disabled=\"!email\" @click=\"sendCode\">Send Code</button>\n    </view>\n    <button :disabled=\"!verificationId || !code\" @click=\"register\">Register</button>\n    <text\n      v-if=\"message\"\n      :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\"\n      >{{ message }}</text\n    >\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      email: \"\",\n      code: \"\",\n      verificationId: \"\",\n      message: \"\"\n    };\n  },\n  methods: {\n    // Send Code\n    async sendCode() {\n      try {\n        const auth = cloudbase.auth();\n        const res = await auth.getVerification({ email: this.email });\n        this.verificationId = res.verification_id;\n        this.message = \"Verification code sent！\";\n      } catch (error) {\n        this.message = \"Send failed：\" + error.message;\n      }\n    },\n\n    // Register\n    async register() {\n      try {\n        const auth = cloudbase.auth();\n        // Verify the code\n        const verifyRes = await auth.verify({\n          verification_id: this.verificationId,\n          verification_code: this.code\n        });\n        // Register (auto-login if user exists)\n        await auth.signUp({\n          email: this.email,\n          verification_code: this.code,\n          verification_token: verifyRes.verification_token,\n          name: `user_${this.email.slice(-4)}`,\n          password: \"admin@123\"\n        });\n        this.message = \"Registration successful！\";\n      } catch (error) {\n        this.message = \"Registration failed：\" + error.message;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Email Code Registration"
              },
              {
                "markdown": "Use **Username Password Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **UsernamePasswordLogin**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\nawait auth.signIn({\n  username, // Can be username, phone or email\n  password\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Account：</text>\n      <input v-model=\"username\" placeholder=\"Username/Phone/Email\" />\n      <text>Note: Add country code for phone login +86</text>\n    </view>\n    <view>\n      <text>Password：</text>\n      <input type=\"password\" v-model=\"password\" placeholder=\"Enter password\" />\n    </view>\n    <button :disabled=\"!username || !password\" @click=\"login\">Login</button>\n    <text\n      v-if=\"message\"\n      :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\"\n      >{{ message }}</text\n    >\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      username: \"\",\n      password: \"\",\n      message: \"\"\n    };\n  },\n  methods: {\n    // Login\n    async login() {\n      try {\n        const auth = cloudbase.auth();\n        await auth.signIn({\n          username: this.username, // Can be username, phone or email\n          password: this.password\n        });\n        this.message = \"Login successful！\";\n      } catch (error) {\n        this.message = \"Login failed：\" + error.message;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login"
              },
              {
                "markdown": "Use **SMS Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMS Verification Login**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n\n// Login\nawait auth.signInWithSms({\n  verificationInfo: res,\n  verificationCode: code,\n  phoneNum: `+86 ${phone}`\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Phone number：</text>\n      <input v-model=\"phone\" placeholder=\"13800000000\" />\n    </view>\n    <view>\n      <text>Verification code：</text>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button @click=\"sendCode\" :disabled=\"!phone\">Send Code</button>\n    </view>\n    <button @click=\"login\" :disabled=\"!verificationInfo || !code\">Login</button>\n    <text\n      v-if=\"message\"\n      :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\"\n      >{{ message }}</text\n    >\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      phone: \"\",\n      code: \"\",\n      verificationInfo: null,\n      message: \"\"\n    };\n  },\n  methods: {\n    // Send Code\n    async sendCode() {\n      try {\n        const auth = cloudbase.auth();\n        const res = await auth.getVerification({\n          phone_number: `+86 ${this.phone}`\n        });\n        this.verificationInfo = res;\n        this.message = \"Verification code sent！\";\n      } catch (error) {\n        this.message = \"Send failed：\" + error.message;\n      }\n    },\n\n    // Login\n    async login() {\n      try {\n        const auth = cloudbase.auth();\n        await auth.signInWithSms({\n          verificationInfo: this.verificationInfo,\n          verificationCode: this.code,\n          phoneNum: `+86 ${this.phone}`\n        });\n        this.message = \"Login successful！\";\n      } catch (error) {\n        this.message = \"Login failed：\" + error.message;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login"
              },
              {
                "markdown": "Use **Email Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Login\nawait auth.signInWithEmail({\n  verificationInfo: res,\n  verificationCode: code,\n  email\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <view>\n      <text>Email：</text>\n      <input v-model=\"email\" placeholder=\"example@email.com\" />\n    </view>\n    <view>\n      <text>Verification code：</text>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button @click=\"sendCode\" :disabled=\"!email\">Send Code</button>\n    </view>\n    <button @click=\"login\" :disabled=\"!verificationInfo || !code\">Login</button>\n    <text\n      v-if=\"message\"\n      :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\"\n      >{{ message }}</text\n    >\n  </view>\n</template>\n\n<script>\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default {\n  data() {\n    return {\n      email: \"\",\n      code: \"\",\n      verificationInfo: null,\n      message: \"\"\n    };\n  },\n  methods: {\n    // Send Code\n    async sendCode() {\n      try {\n        const auth = cloudbase.auth();\n        const res = await auth.getVerification({ email: this.email });\n        this.verificationInfo = res;\n        this.message = \"Verification code sent！\";\n      } catch (error) {\n        this.message = \"Send failed：\" + error.message;\n      }\n    },\n\n    // Login\n    async login() {\n      try {\n        const auth = cloudbase.auth();\n        await auth.signInWithEmail({\n          verificationInfo: this.verificationInfo,\n          verificationCode: this.code,\n          email: this.email\n        });\n        this.message = \"Login successful！\";\n      } catch (error) {\n        this.message = \"Login failed：\" + error.message;\n      }\n    }\n  }\n};\n</script>\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Phone numberAuthorizeLogin\nconst loginResult = await auth.signInWithPhoneAuth(code);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button open-type=\"getPhoneNumber\" @getphonenumber=\"handleGetPhoneNumber\">\n      WeChatMini ProgramLogin\n    </button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from './utils/cloudbase';\n\nexport default {\n  data() {\n    return {}\n  },\n  methods: {\n    async handleGetPhoneNumber(event) {\n      if(!event.detail.code) {\n        console.error('GetPhone numberfailed:', event.detail.errMsg);\n        uni.showToast({\n          title: 'GetPhone numberfailed',\n          icon: 'none'\n        });\n        return\n      }\n      console.log('Gettodynamic token(code):', event.detail.code);\n      uni.showLoading({\n        title: 'Login...'\n      });\n      try {\n        // Phone numberAuthorizeLogin\n        const auth = cloudbase.auth();\n        const loginResult = await auth.signInWithPhoneAuth( event.detail.code );\n        console.log('Phone numberAuthorizeLoginResult:', loginResult);\n        uni.hideLoading();\n        uni.showToast({\n          title: 'Login successful',\n          icon: 'success'\n        });\n      } catch (error: any) {\n        // ProcessLogin failed\n        console.error('Phone numberAuthorizeLogin failed:', error);\n        uni.showToast({\n          title: error.message || 'Login failed',\n          icon: 'none'\n        });\n      } finally {\n        uni.hideLoading();\n      }\n    }\n  }\n}\n</script>\n```",
                "index": 6,
                "title": "Mini ProgramPhone numberLogin"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// WeChat OpenID Login\nconst loginResult = await auth.signInWithOpenId();\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <view>\n    <button @click=\"openIdLogin\">WeChatMini ProgramLogin</button>\n  </view>\n</template>\n\n<script>\nimport cloudbase from './utils/cloudbase';\n\nexport default {\n  data() {\n    return {}\n  },\n  methods: {\n    async openIdLogin() {\n      uni.showLoading({\n        title: 'currentlyinLogin...'\n      });\n\n      try {\n        const auth = cloudbase.auth();\n        const loginResult = await auth.signInWithOpenId();\n        console.log('WeChat OpenID Login successful:', loginResult);\n        uni.hideLoading();\n\n        uni.showToast({\n          title: 'Login successful',\n          icon: 'success'\n        });\n      } catch (error: any) {\n        uni.hideLoading();\n        console.error('WeChat OpenID Login failed:', error);\n        uni.showToast({\n          title: error.message || 'Login failed，pleaseRetry',\n          icon: 'none'\n        });\n      }\n    }\n  }\n}\n</script>\n```",
                "index": 7,
                "title": "WeChat OpenID Login"
              }
            ]
          }
        ]
      }
    ],
    "_id": "5f3bcef3697c80850041139469d71951",
    "_openid": "anon",
    "createdAt": 1769767045876,
    "updatedAt": 1769767045876
  },
  {
    "category": "Framework Integration,Mobile Frameworks,React Native",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 33,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/api-reference/webv2/adapter",
    "content": [
      {
        "markdown": "`@cloudbase/js-sdk` Combine with `@cloudbase/adapter-rn` allows you toin React Native project",
        "index": 1,
        "title": "Install SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```bash\nnpm i @cloudbase/js-sdk @cloudbase/adapter-rn\n```",
            "index": 1,
            "title": "npm"
          },
          {
            "markdown": "```bash\nyarn add @cloudbase/js-sdk @cloudbase/adapter-rn\n```",
            "index": 2,
            "title": "yarn"
          },
          {
            "markdown": "```bash\npnpm add @cloudbase/js-sdk @cloudbase/adapter-rn\n```\n\niOS needInstallNativeDependency：\n\n```bash\ncd ios && pod install && cd ..\n```",
            "index": 3,
            "title": "pnpm"
          }
        ]
      },
      {
        "markdown": "Add the following code to your React Native project",
        "index": 2,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nimport cloudbaseSDK from \"@cloudbase/js-sdk\";\nimport adapter from \"@cloudbase/adapter-rn\";\n\ncloudbaseSDK.useAdapters(adapter);\n\nconst cloudbase = cloudbaseSDK.init({\n  // Environment ID\n  env: \"{%ENV_ID%}\",\n  // region\n  region: \"{%REGION%}\",\n  // Anonymous access token\n  accessKey: \"{%PUBLISHABLE_KEY%}\"\n});\n\nexport default cloudbase;\n```",
            "index": 1,
            "title": "src/utils/cloudbase.js"
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table (limit 10 records)\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n\nconsole.log(\"Query result:\", data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Insert a record into {%TABLE_NAME%} table\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"New Post\", status: \"draft\" })\n  .select();\n\nconsole.log(\"Insert result:\", data);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Update record by id in {%TABLE_NAME%}\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ status: \"published\" })\n  .eq(\"id\", 1)\n  .select();\n\nconsole.log(\"Update result:\", data);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Upsert: update on conflict, otherwise insert\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Post Title\", status: \"published\" }, { onConflict: \"id\" })\n  .select();\n\nconsole.log(\"Upsert result:\", data);\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```js\nimport cloudbase from \"./utils/cloudbase\";\n\n// Delete record by id in {%TABLE_NAME%}\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", 1);\n\nconsole.log(\"Delete completed:\", error);\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, Button, FlatList, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function QueryData() {\n  const [dataList, setDataList] = useState([]);\n\n  // Query Data\n  const getData = async () => {\n    try {\n      const { data, error } = await cloudbase\n        .database()\n        .from(\"{%TABLE_NAME%}\")\n        .select(\"*\")\n        .limit(10);\n\n      if (!error) {\n        setDataList(data);\n        Alert.alert(\"successful\", \"Querysuccessful\");\n      } else {\n        Alert.alert(\"failed\", \"Queryfailed\");\n      }\n    } catch (error) {\n      Alert.alert(\"Error\", `Queryfailed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"Query Data\" onPress={getData} />\n      {dataList.length > 0 ? (\n        <FlatList\n          data={dataList}\n          keyExtractor={(item, index) => index.toString()}\n          renderItem={({ item }) => (\n            <View style={styles.item}>\n              <Text>{JSON.stringify(item)}</Text>\n            </View>\n          )}\n        />\n      ) : (\n        <Text>temporarilyNoneData</Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  item: {\n    padding: 10,\n    marginVertical: 5,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title });\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function AddData() {\n  const [title, setTitle] = useState(\"\");\n\n  // Insert Data\n  const addData = async () => {\n    try {\n      const { data, error } = await cloudbase\n        .database()\n        .from(\"{%TABLE_NAME%}\")\n        .insert({ title });\n\n      if (!error) {\n        Alert.alert(\"successful\", \"Insert successful\");\n        setTitle(\"\");\n      } else {\n        Alert.alert(\"failed\", \"Insert failed\");\n      }\n    } catch (error) {\n      Alert.alert(\"Error\", `Insert failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={title}\n        onChangeText={setTitle}\n        placeholder=\"Please enterTitle\"\n      />\n      <Button title=\"Insert Data\" onPress={addData} disabled={!title} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ title: newTitle })\n  .eq(\"id\", dataId);\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function UpdateData() {\n  const [dataId, setDataId] = useState(\"\");\n  const [newTitle, setNewTitle] = useState(\"\");\n\n  // Update Data\n  const updateData = async () => {\n    try {\n      const { data, error } = await cloudbase\n        .database()\n        .from(\"{%TABLE_NAME%}\")\n        .update({ title: newTitle })\n        .eq(\"id\", dataId);\n\n      if (!error) {\n        Alert.alert(\"successful\", \"Update successful\");\n        setDataId(\"\");\n        setNewTitle(\"\");\n      } else {\n        Alert.alert(\"failed\", \"Update failed\");\n      }\n    } catch (error) {\n      Alert.alert(\"Error\", `Update failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>DataID：</Text>\n      <TextInput\n        style={styles.input}\n        value={dataId}\n        onChangeText={setDataId}\n        placeholder=\"Please enterDataID\"\n      />\n      <Text>New Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={newTitle}\n        onChangeText={setNewTitle}\n        placeholder=\"Please enterNew Title\"\n      />\n      <Button\n        title=\"Update Data\"\n        onPress={updateData}\n        disabled={!dataId || !newTitle}\n      />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: parseInt(id), title });\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function UpsertData() {\n  const [id, setId] = useState(\"\");\n  const [title, setTitle] = useState(\"\");\n\n  // Upsert Data\n  const upsertData = async () => {\n    try {\n      const { data, error } = await cloudbase\n        .database()\n        .from(\"{%TABLE_NAME%}\")\n        .upsert({ id: parseInt(id), title });\n\n      if (!error) {\n        Alert.alert(\"successful\", \"Operation successful\");\n        setId(\"\");\n        setTitle(\"\");\n      } else {\n        Alert.alert(\"failed\", \"Operation failed\");\n      }\n    } catch (error) {\n      Alert.alert(\"Error\", `Operation failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>ID：</Text>\n      <TextInput\n        style={styles.input}\n        value={id}\n        onChangeText={setId}\n        placeholder=\"Please enterID\"\n        keyboardType=\"numeric\"\n      />\n      <Text>Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={title}\n        onChangeText={setTitle}\n        placeholder=\"Please enterTitle\"\n      />\n      <Button\n        title=\"UpdateorCreate\"\n        onPress={upsertData}\n        disabled={!id || !title}\n      />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 4,
                "title": "Upsert Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", dataId);\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function DeleteData() {\n  const [dataId, setDataId] = useState(\"\");\n\n  // Delete Data\n  const deleteData = async () => {\n    try {\n      const { data, error } = await cloudbase\n        .database()\n        .from(\"{%TABLE_NAME%}\")\n        .delete()\n        .eq(\"id\", dataId);\n\n      if (!error) {\n        Alert.alert(\"successful\", \"Delete successful\");\n        setDataId(\"\");\n      } else {\n        Alert.alert(\"failed\", \"Delete failed\");\n      }\n    } catch (error) {\n      Alert.alert(\"Error\", `Delete failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>DataID：</Text>\n      <TextInput\n        style={styles.input}\n        value={dataId}\n        onChangeText={setDataId}\n        placeholder=\"Please entershouldDeleteDataID\"\n      />\n      <Button title=\"Delete Data\" onPress={deleteData} disabled={!dataId} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 5,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, Button, FlatList, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function QueryDocData() {\n  const [dataList, setDataList] = useState([]);\n\n  // Query Data\n  const getData = async () => {\n    try {\n      const db = cloudbase.database();\n      const res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n\n      setDataList(res.data);\n      Alert.alert(\"successful\", \"Querysuccessful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Queryfailed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"Query Data\" onPress={getData} />\n      {dataList.length > 0 ? (\n        <FlatList\n          data={dataList}\n          keyExtractor={(item, index) => index.toString()}\n          renderItem={({ item }) => (\n            <View style={styles.item}>\n              <Text>{JSON.stringify(item)}</Text>\n            </View>\n          )}\n        />\n      ) : (\n        <Text>temporarilyNoneData</Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  item: {\n    padding: 10,\n    marginVertical: 5,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({ title });\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function AddDocData() {\n  const [title, setTitle] = useState(\"\");\n\n  // Insert Data\n  const addData = async () => {\n    try {\n      const db = cloudbase.database();\n      const res = await db.collection(\"{%TABLE_NAME%}\").add({ title });\n\n      Alert.alert(\"successful\", `Insert successful! id: ${res.id}`);\n      setTitle(\"\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Insert failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={title}\n        onChangeText={setTitle}\n        placeholder=\"Please enterTitle\"\n      />\n      <Button title=\"Insert Data\" onPress={addData} disabled={!title} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(dataId).update({ title: newTitle });\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function UpdateDocData() {\n  const [dataId, setDataId] = useState(\"\");\n  const [newTitle, setNewTitle] = useState(\"\");\n\n  // Update Data\n  const updateData = async () => {\n    try {\n      const db = cloudbase.database();\n      await db\n        .collection(\"{%TABLE_NAME%}\")\n        .doc(dataId)\n        .update({ title: newTitle });\n\n      Alert.alert(\"successful\", \"Update successful\");\n      setDataId(\"\");\n      setNewTitle(\"\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Update failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>DataID：</Text>\n      <TextInput\n        style={styles.input}\n        value={dataId}\n        onChangeText={setDataId}\n        placeholder=\"Please enterDataID\"\n      />\n      <Text>New Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={newTitle}\n        onChangeText={setNewTitle}\n        placeholder=\"Please enterNew Title\"\n      />\n      <Button\n        title=\"Update Data\"\n        onPress={updateData}\n        disabled={!dataId || !newTitle}\n      />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(dataId).remove();\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function DeleteDocData() {\n  const [dataId, setDataId] = useState(\"\");\n\n  // Delete Data\n  const deleteData = async () => {\n    try {\n      const db = cloudbase.database();\n      await db.collection(\"{%TABLE_NAME%}\").doc(dataId).remove();\n\n      Alert.alert(\"successful\", \"Delete successful\");\n      setDataId(\"\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Delete failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>DataID：</Text>\n      <TextInput\n        style={styles.input}\n        value={dataId}\n        onChangeText={setDataId}\n        placeholder=\"Please entershouldDeleteDataID\"\n      />\n      <Button title=\"Delete Data\" onPress={deleteData} disabled={!dataId} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, Button, FlatList, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function QueryModelData() {\n  const [dataList, setDataList] = useState([]);\n\n  // Query Data\n  const getData = async () => {\n    try {\n      const res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n        pageNumber: 1,\n        pagesize: 10\n      });\n\n      setDataList(res.data?.records || []);\n      Alert.alert(\"successful\", \"Querysuccessful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Queryfailed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"Query Data\" onPress={getData} />\n      {dataList.length > 0 ? (\n        <FlatList\n          data={dataList}\n          keyExtractor={(item, index) => index.toString()}\n          renderItem={({ item }) => (\n            <View style={styles.item}>\n              <Text>{JSON.stringify(item)}</Text>\n            </View>\n          )}\n        />\n      ) : (\n        <Text>temporarilyNoneData</Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  item: {\n    padding: 10,\n    marginVertical: 5,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: { title }\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function AddModelData() {\n  const [title, setTitle] = useState(\"\");\n\n  // Insert Data\n  const addData = async () => {\n    try {\n      const res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n        data: { title }\n      });\n\n      Alert.alert(\"successful\", `Insert successful! id: ${res.data.id}`);\n      setTitle(\"\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Insert failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={title}\n        onChangeText={setTitle}\n        placeholder=\"Please enterTitle\"\n      />\n      <Button title=\"Insert Data\" onPress={addData} disabled={!title} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nawait cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: { title: newTitle },\n  filter: { where: { _id: { $eq: dataId } } }\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function UpdateModelData() {\n  const [dataId, setDataId] = useState(\"\");\n  const [newTitle, setNewTitle] = useState(\"\");\n\n  // Update Data\n  const updateData = async () => {\n    try {\n      await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n        data: { title: newTitle },\n        filter: { where: { _id: { $eq: dataId } } }\n      });\n\n      Alert.alert(\"successful\", \"Update successful\");\n      setDataId(\"\");\n      setNewTitle(\"\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Update failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>DataID：</Text>\n      <TextInput\n        style={styles.input}\n        value={dataId}\n        onChangeText={setDataId}\n        placeholder=\"Please enterDataID\"\n      />\n      <Text>New Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={newTitle}\n        onChangeText={setNewTitle}\n        placeholder=\"Please enterNew Title\"\n      />\n      <Button\n        title=\"Update Data\"\n        onPress={updateData}\n        disabled={!dataId || !newTitle}\n      />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nawait cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: { where: { _id: { $eq: dataId } } }\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function DeleteModelData() {\n  const [dataId, setDataId] = useState(\"\");\n\n  // Delete Data\n  const deleteData = async () => {\n    try {\n      await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n        filter: { where: { _id: { $eq: dataId } } }\n      });\n\n      Alert.alert(\"successful\", \"Delete successful\");\n      setDataId(\"\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Delete failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>DataID：</Text>\n      <TextInput\n        style={styles.input}\n        value={dataId}\n        onChangeText={setDataId}\n        placeholder=\"Please entershouldDeleteDataID\"\n      />\n      <Button title=\"Delete Data\" onPress={deleteData} disabled={!dataId} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {}\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function CallFunction() {\n  const [result, setResult] = useState(null);\n\n  // CallCloud Function\n  const callFunction = async () => {\n    try {\n      const res = await cloudbase.callFunction({\n        name: \"{%FUNCTION_NAME%}\",\n        data: {}\n      });\n\n      setResult(res.result);\n      Alert.alert(\"successful\", \"Callsuccessful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Call failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"CallCloud Function\" onPress={callFunction} />\n      {result && (\n        <View style={styles.resultContainer}>\n          <Text>Return result：</Text>\n          <Text>{JSON.stringify(result)}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call {%SERVICE_NAME%} Cloud Runservice\nconst res = await cloudbase.callContainer({\n  name: \"{%SERVICE_NAME%}\"\n  method: 'POST',\n  path: '/',\n  header:{\n    'Content-Type': 'application/json; charset=utf-8'\n  },\n  data: {},\n});\n```\n\n**Full Example：**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function CallRun() {\n  const [result, setResult] = useState(null);\n\n  // CallCloud Run\n  const callRun = async () => {\n    try {\n      // Call {%SERVICE_NAME%} Cloud Runservice\n      const res = await cloudbase.callContainer({\n        name: \"{%SERVICE_NAME%}\"\n        method: 'POST',\n        path: '/',\n        header:{\n          'Content-Type': 'application/json; charset=utf-8'\n        },\n        data: {},\n      });\n\n      setResult(res);\n      Alert.alert(\"successful\", \"Callsuccessful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Call failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"CallCloud Run\" onPress={callRun} />\n      {result && (\n        <View style={styles.resultContainer}>\n          <Text>Return result：</Text>\n          <Text>{JSON.stringify(result)}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 6,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.uploadFile({\n  cloudPath: cloudPath,\n  filePath: asset.uri\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, Button, StyleSheet, Alert } from \"react-native\";\nimport { launchImageLibrary } from \"react-native-image-picker\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function UploadFile() {\n  const [fileId, setFileId] = useState(\"\");\n\n  // Upload File\n  const uploadFile = async () => {\n    try {\n      const result = await launchImageLibrary({\n        mediaType: \"photo\",\n        quality: 0.8\n      });\n\n      if (result.didCancel) {\n        return;\n      }\n\n      if (result.errorCode) {\n        Alert.alert(\"Error\", \"SelectImagefailed\");\n        return;\n      }\n\n      const asset = result.assets[0];\n      const fileExtension = asset.fileName?.split(\".\").pop() || \"jpg\";\n      const cloudPath = `images/${Date.now()}-${Math.random()}.${fileExtension}`;\n\n      const res = await cloudbase.uploadFile({\n        cloudPath: cloudPath,\n        filePath: asset.uri\n      });\n\n      setFileId(res.fileID);\n      Alert.alert(\"successful\", \"Upload successful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Uploadfailed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"SelectandUploadImage\" onPress={uploadFile} />\n      {fileId && (\n        <View style={styles.resultContainer}>\n          <Text>Upload successful！</Text>\n          <Text>fileID: {fileId}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.getTempFileURL({\n  fileList: [fileId]\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport {\n  View,\n  Text,\n  TextInput,\n  Button,\n  Image,\n  StyleSheet,\n  Alert\n} from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function GetFileUrl() {\n  const [fileId, setFileId] = useState(\"\");\n  const [fileUrl, setFileUrl] = useState(\"\");\n\n  // Get File URL\n  const getFileUrl = async () => {\n    try {\n      const res = await cloudbase.getTempFileURL({\n        fileList: [fileId]\n      });\n\n      setFileUrl(res.fileList[0].tempFileURL);\n      Alert.alert(\"successful\", \"Getsuccessful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Getfailed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>fileID：</Text>\n      <TextInput\n        style={styles.input}\n        value={fileId}\n        onChangeText={setFileId}\n        placeholder=\"Please enterfileID (cloud://xxx.png)\"\n      />\n      <Button title=\"Get File URL\" onPress={getFileUrl} disabled={!fileId} />\n      {fileUrl && (\n        <View style={styles.resultContainer}>\n          <Text>fileURL：</Text>\n          <Text>{fileUrl}</Text>\n          <Image\n            source={{ uri: fileUrl }}\n            style={styles.image}\n            resizeMode=\"contain\"\n          />\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  },\n  image: {\n    width: \"100%\",\n    height: 200,\n    marginTop: 10\n  }\n});\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.downloadFile({\n  fileID: fileId\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function DownloadFile() {\n  const [fileId, setFileId] = useState(\"\");\n  const [localPath, setLocalPath] = useState(\"\");\n\n  // Download File\n  const downloadFile = async () => {\n    try {\n      const res = await cloudbase.downloadFile({\n        fileID: fileId\n      });\n\n      setLocalPath(res.tempFilePath);\n      Alert.alert(\"successful\", \"Downloadsuccessful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Downloadfailed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>fileID：</Text>\n      <TextInput\n        style={styles.input}\n        value={fileId}\n        onChangeText={setFileId}\n        placeholder=\"Please enterfileID (cloud://xxx.png)\"\n      />\n      <Button title=\"Download File\" onPress={downloadFile} disabled={!fileId} />\n      {localPath && (\n        <View style={styles.resultContainer}>\n          <Text>Downloadsuccessful！</Text>\n          <Text>localPath: {localPath}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.deleteFile({\n  fileList: [fileId]\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function DeleteFile() {\n  const [fileId, setFileId] = useState(\"\");\n\n  // Delete File\n  const deleteFile = async () => {\n    try {\n      const res = await cloudbase.deleteFile({\n        fileList: [fileId]\n      });\n\n      if (res.fileList[0].code === \"SUCCESS\") {\n        Alert.alert(\"successful\", \"Delete successful\");\n        setFileId(\"\");\n      } else {\n        Alert.alert(\"failed\", \"Delete failed\");\n      }\n    } catch (error) {\n      Alert.alert(\"Error\", `Delete failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>fileID：</Text>\n      <TextInput\n        style={styles.input}\n        value={fileId}\n        onChangeText={setFileId}\n        placeholder=\"Please enterfileID (cloud://xxx.png)\"\n      />\n      <Button title=\"Delete File\" onPress={deleteFile} disabled={!fileId} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst ai = cloudbase.ai();\nconst model = ai.createModel(\"{%AI_MODEL_NAME%}\");\n\n// EnsurealreadyLogin\nconst loginState = await cloudbase.auth().getLoginState();\nif (!loginState) {\n  await cloudbase.auth().signInAnonymously();\n}\n\nconst res = await model.streamText({\n  model: \"{%AI_SUB_MODEL_NAME%}\",\n  messages: [\n    {\n      role: \"system\",\n      content:\n        \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\"\n    },\n    { role: \"user\", content: input }\n  ]\n});\n\nfor await (let str of res.textStream) {\n  // ProcessStreaming response\n}\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport {\n  View,\n  Text,\n  TextInput,\n  Button,\n  StyleSheet,\n  Alert,\n  ActivityIndicator\n} from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function CallAIModel() {\n  const [input, setInput] = useState(\"\");\n  const [response, setResponse] = useState(\"\");\n  const [isGenerating, setIsGenerating] = useState(false);\n\n  // CallAI Model\n  const callAIModel = async () => {\n    setIsGenerating(true);\n    setResponse(\"\");\n\n    try {\n      const ai = cloudbase.ai();\n      const model = ai.createModel(\"{%AI_MODEL_NAME%}\");\n\n      // EnsurealreadyLogin\n      const loginState = await cloudbase.auth().getLoginState();\n      if (!loginState) {\n        await cloudbase.auth().signInAnonymously();\n      }\n\n      const res = await model.streamText({\n        model: \"{%AI_SUB_MODEL_NAME%}\",\n        messages: [\n          {\n            role: \"system\",\n            content:\n              \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\"\n          },\n          { role: \"user\", content: input }\n        ]\n      });\n\n      for await (let str of res.textStream) {\n        setResponse(prev => prev + str);\n      }\n\n      Alert.alert(\"successful\", \"GenerateDone\");\n    } catch (err) {\n      Alert.alert(\"Error\", `Generation failed: ${err.message}`);\n    } finally {\n      setIsGenerating(false);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Inputtopic：</Text>\n      <TextInput\n        style={styles.input}\n        value={input}\n        onChangeText={setInput}\n        placeholder=\"Please entertopic，such as：Spring\"\n      />\n      <Button\n        title=\"GenerateContent\"\n        onPress={callAIModel}\n        disabled={!input || isGenerating}\n      />\n      {isGenerating && <ActivityIndicator size=\"large\" style={styles.loader} />}\n      {response && (\n        <View style={styles.resultContainer}>\n          <Text>GenerateResult：</Text>\n          <Text>{response}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  loader: {\n    marginVertical: 20\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: { prompt: \"A cute cat playing in the sunshine\" }\n});\n\nif (res.result.success) {\n  console.log(\"Image URL:\", res.result.imageUrl);\n  console.log(\"Optimized prompt:\", res.result.revised_prompt);\n} else {\n  console.error(\"Generation failed:\", res.result.code, res.result.message);\n}\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport {\n  View,\n  Text,\n  TextInput,\n  Button,\n  Image,\n  StyleSheet,\n  Alert,\n  ActivityIndicator\n} from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function GenerateImage() {\n  const [prompt, setPrompt] = useState(\"\");\n  const [imageUrl, setImageUrl] = useState(\"\");\n  const [revisedPrompt, setRevisedPrompt] = useState(\"\");\n  const [isGenerating, setIsGenerating] = useState(false);\n\n  // Generate Image\n  const generateImage = async () => {\n    setIsGenerating(true);\n    setImageUrl(\"\");\n    setRevisedPrompt(\"\");\n\n    try {\n      const res = await cloudbase.callFunction({\n        name: \"<YOUR_FUNCTION_NAME>\",\n        data: { prompt }\n      });\n\n      if (res.result.success) {\n        setImageUrl(res.result.imageUrl);\n        setRevisedPrompt(res.result.revised_prompt || \"\");\n        Alert.alert(\"successful\", \"ImageGeneration successful\");\n      } else {\n        Alert.alert(\n          \"failed\",\n          `Generation failed: ${res.result.code} - ${res.result.message}`\n        );\n      }\n    } catch (err) {\n      Alert.alert(\"Error\", `Generation failed: ${err.message}`);\n    } finally {\n      setIsGenerating(false);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>InputDescription：</Text>\n      <TextInput\n        style={styles.input}\n        value={prompt}\n        onChangeText={setPrompt}\n        placeholder=\"for example：A cute cat playing in the sunshine\"\n        multiline\n      />\n      <Button\n        title=\"Generate Image\"\n        onPress={generateImage}\n        disabled={!prompt || isGenerating}\n      />\n      {isGenerating && <ActivityIndicator size=\"large\" style={styles.loader} />}\n      {imageUrl && (\n        <View style={styles.resultContainer}>\n          <Text style={styles.label}>GenerateResult：</Text>\n          <Image\n            source={{ uri: imageUrl }}\n            style={styles.image}\n            resizeMode=\"contain\"\n          />\n          {revisedPrompt && (\n            <View style={styles.promptContainer}>\n              <Text style={styles.label}>Optimized prompt：</Text>\n              <Text>{revisedPrompt}</Text>\n            </View>\n          )}\n          <Text style={styles.note}>Note：Image URLValidis valid for24hours</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    minHeight: 80,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    paddingVertical: 10,\n    borderRadius: 5,\n    textAlignVertical: \"top\"\n  },\n  loader: {\n    marginVertical: 20\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  },\n  label: {\n    fontWeight: \"bold\",\n    marginBottom: 5\n  },\n  image: {\n    width: \"100%\",\n    height: 300,\n    marginVertical: 10\n  },\n  promptContainer: {\n    marginTop: 10\n  },\n  note: {\n    marginTop: 10,\n    fontSize: 12,\n    color: \"#666\",\n    fontStyle: \"italic\"\n  }\n});\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\n/**\n * React Native Call Agent Example (AG-UI Protocol)\n * Protocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n */\nimport cloudbase from './utils/cloudbase';\n\n// EnsurealreadyLogin\nconst loginState = await cloudbase.auth().getLoginState();\nif (!loginState) {\n  await cloudbase.auth().signInAnonymously();\n}\n\nconst ai = cloudbase.ai();\n\n// Build message list (AG-UI protocol format)\nconst messages = [\n  {\n    id: 'msg_001',\n    role: 'user',\n    content: input,\n  },\n];\n\n// AG-UI Protocol request parameters\nconst res = await ai.bot.sendMessage({\n  botId: '{%AGENT_ID%}',\n  data: {\n    messages,                                            // Required: Message list\n    threadId: '550e8400-e29b-41d4-a716-446655440000',   // Optional: Session ID for multi-turn conversation\n    runId: 'run_001',                                    // Optional: Run ID for execution tracking\n    tools: [],                                           // Optional: Frontend tool definitions\n    context: [],                                         // Optional: Context information\n    forwardedProps: {},                                  // Optional: Pass-through parameters\n  },\n});\n\n// ProcessStreaming response\nfor await (const str of res.textStream) {\n  console.log(str);\n}\n\n```\n\n**Full Example:**\n\n```jsx\n/**\n * React Native Call Agent Full Example（AG-UI Protocol)\n * Protocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n */\nimport React, { useState } from 'react';\nimport { View, Text, TextInput, Button, StyleSheet, Alert, ActivityIndicator } from 'react-native';\nimport cloudbase from './utils/cloudbase';\n\nexport default function CallAgent() {\n  const [input, setInput] = useState('');\n  const [response, setResponse] = useState('');\n  const [isGenerating, setIsGenerating] = useState(false);\n\n  // CallAgent（AG-UI Protocol)\n  const callAgent = async () => {\n    setIsGenerating(true);\n    setResponse('');\n\n    try {\n      const ai = cloudbase.ai();\n\n      // EnsurealreadyLogin\n      const loginState = await cloudbase.auth().getLoginState();\n      if (!loginState) {\n        await cloudbase.auth().signInAnonymously();\n      }\n\n      // Build message list (AG-UI protocol format)\n      const messages = [\n        {\n          id: 'msg_001',\n          role: 'user',\n          content: input,\n        },\n      ];\n\n      // AG-UI Protocol request parameters\n      const res = await ai.bot.sendMessage({\n        botId: '{%AGENT_ID%}',\n        data: {\n          messages,                                            // Required: Message list\n          threadId: '550e8400-e29b-41d4-a716-446655440000',   // Optional: Session ID for multi-turn conversation\n          runId: 'run_001',                                    // Optional: Run ID for execution tracking\n          tools: [],                                           // Optional: Frontend tool definitions\n          context: [],                                         // Optional: Context information\n          forwardedProps: {},                                  // Optional: Pass-through parameters\n        },\n      });\n\n      // ProcessStreaming response\n      for await (const str of res.textStream) {\n        setResponse((prev) => prev + str);\n      }\n\n      Alert.alert('successful', 'GenerateDone');\n    } catch (err) {\n      Alert.alert('Error', `Generation failed: ${err.message}`);\n    } finally {\n      setIsGenerating(false);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Inputquestion：</Text>\n      <TextInput style={styles.input} value={input} onChangeText={setInput} placeholder=\"Please enterquestion，such as：Who are you\" />\n      <Button title=\"SendMessage\" onPress={callAgent} disabled={!input || isGenerating} />\n      {isGenerating && <ActivityIndicator size=\"large\" style={styles.loader} />}\n      {response && (\n        <View style={styles.resultContainer}>\n          <Text>answer：</Text>\n          <Text>{response}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20,\n  },\n  input: {\n    height: 40,\n    borderColor: '#ccc',\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5,\n  },\n  loader: {\n    marginVertical: 20,\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: '#f9f9f9',\n    borderRadius: 5,\n  },\n});\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst ai = cloudbase.ai();\n\n// EnsurealreadyLogin\nconst loginState = await cloudbase.auth().getLoginState();\nif (!loginState) {\n  await cloudbase.auth().signInAnonymously();\n}\n\nconst res = await ai.bot.sendMessage({\n  botId: \"{%AGENT_ID%}\",\n  msg: input\n});\n\nfor await (let str of res.textStream) {\n  // ProcessStreaming response\n}\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport {\n  View,\n  Text,\n  TextInput,\n  Button,\n  StyleSheet,\n  Alert,\n  ActivityIndicator\n} from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function CallAgent() {\n  const [input, setInput] = useState(\"\");\n  const [response, setResponse] = useState(\"\");\n  const [isGenerating, setIsGenerating] = useState(false);\n\n  // CallAgent\n  const callAgent = async () => {\n    setIsGenerating(true);\n    setResponse(\"\");\n\n    try {\n      const ai = cloudbase.ai();\n\n      // EnsurealreadyLogin\n      const loginState = await cloudbase.auth().getLoginState();\n      if (!loginState) {\n        await cloudbase.auth().signInAnonymously();\n      }\n\n      const res = await ai.bot.sendMessage({\n        botId: \"{%AGENT_ID%}\",\n        msg: input\n      });\n\n      for await (let str of res.textStream) {\n        setResponse(prev => prev + str);\n      }\n\n      Alert.alert(\"successful\", \"GenerateDone\");\n    } catch (err) {\n      Alert.alert(\"Error\", `Generation failed: ${err.message}`);\n    } finally {\n      setIsGenerating(false);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Inputquestion：</Text>\n      <TextInput\n        style={styles.input}\n        value={input}\n        onChangeText={setInput}\n        placeholder=\"Please enterquestion，such as：Who are you\"\n      />\n      <Button\n        title=\"SendMessage\"\n        onPress={callAgent}\n        disabled={!input || isGenerating}\n      />\n      {isGenerating && <ActivityIndicator size=\"large\" style={styles.loader} />}\n      {response && (\n        <View style={styles.resultContainer}>\n          <Text>answer：</Text>\n          <Text>{response}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  loader: {\n    marginVertical: 20\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 9,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "Use **SMS Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMSVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: phone });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  phone_number: `+86 ${phone}`,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${phone.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function SmsRegister() {\n  const [phone, setPhone] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationId, setVerificationId] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ phone_number: phone });\n      setVerificationId(res.verification_id);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(`Send failed: ${error.message}`);\n    }\n  };\n\n  // Register\n  const register = async () => {\n    try {\n      const auth = cloudbase.auth();\n      // Verify the code\n      const verifyRes = await auth.verify({\n        verification_id: verificationId,\n        verification_code: code\n      });\n      // Register (auto-login if user exists)\n      await auth.signUp({\n        phone_number: `+86 ${phone}`,\n        verification_code: code,\n        verification_token: verifyRes.verification_token,\n        name: `user_${phone.slice(-4)}`,\n        password: \"admin@123\"\n      });\n      setMessage(\"Registration successful！\");\n      Alert.alert(\"successful\", \"Registration successful\");\n    } catch (error) {\n      setMessage(`Registration failed: ${error.message}`);\n      Alert.alert(\"failed\", `Registration failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Phone number：</Text>\n      <TextInput\n        style={styles.input}\n        value={phone}\n        onChangeText={setPhone}\n        placeholder=\"13800000000\"\n        keyboardType=\"phone-pad\"\n      />\n      <Text>Verification code：</Text>\n      <View style={styles.row}>\n        <TextInput\n          style={[styles.input, styles.codeInput]}\n          value={code}\n          onChangeText={setCode}\n          placeholder=\"Verification code\"\n          keyboardType=\"numeric\"\n        />\n        <Button title=\"Send Code\" onPress={sendCode} disabled={!phone} />\n      </View>\n      <Button\n        title=\"Register\"\n        onPress={register}\n        disabled={!verificationId || !code}\n      />\n      {message && (\n        <Text\n          style={[\n            styles.message,\n            { color: message.includes(\"successful\") ? \"green\" : \"red\" }\n          ]}\n        >\n          {message}\n        </Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  row: {\n    flexDirection: \"row\",\n    alignItems: \"center\"\n  },\n  codeInput: {\n    flex: 1,\n    marginRight: 10\n  },\n  message: {\n    marginTop: 20,\n    textAlign: \"center\"\n  }\n});\n```",
                "index": 1,
                "title": "SMS Code Registration",
                "content": []
              },
              {
                "markdown": "Use **Email Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  email,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${email.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function EmailRegister() {\n  const [email, setEmail] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationId, setVerificationId] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ email });\n      setVerificationId(res.verification_id);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(`Send failed: ${error.message}`);\n    }\n  };\n\n  // Register\n  const register = async () => {\n    try {\n      const auth = cloudbase.auth();\n      // Verify the code\n      const verifyRes = await auth.verify({\n        verification_id: verificationId,\n        verification_code: code\n      });\n      // Register (auto-login if user exists)\n      await auth.signUp({\n        email,\n        verification_code: code,\n        verification_token: verifyRes.verification_token,\n        name: `user_${email.slice(-4)}`,\n        password: \"admin@123\"\n      });\n      setMessage(\"Registration successful！\");\n      Alert.alert(\"successful\", \"Registration successful\");\n    } catch (error) {\n      setMessage(`Registration failed: ${error.message}`);\n      Alert.alert(\"failed\", `Registration failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Email：</Text>\n      <TextInput\n        style={styles.input}\n        value={email}\n        onChangeText={setEmail}\n        placeholder=\"example@email.com\"\n        keyboardType=\"email-address\"\n      />\n      <Text>Verification code：</Text>\n      <View style={styles.row}>\n        <TextInput\n          style={[styles.input, styles.codeInput]}\n          value={code}\n          onChangeText={setCode}\n          placeholder=\"Verification code\"\n          keyboardType=\"numeric\"\n        />\n        <Button title=\"Send Code\" onPress={sendCode} disabled={!email} />\n      </View>\n      <Button\n        title=\"Register\"\n        onPress={register}\n        disabled={!verificationId || !code}\n      />\n      {message && (\n        <Text\n          style={[\n            styles.message,\n            { color: message.includes(\"successful\") ? \"green\" : \"red\" }\n          ]}\n        >\n          {message}\n        </Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  row: {\n    flexDirection: \"row\",\n    alignItems: \"center\"\n  },\n  codeInput: {\n    flex: 1,\n    marginRight: 10\n  },\n  message: {\n    marginTop: 20,\n    textAlign: \"center\"\n  }\n});\n```",
                "index": 2,
                "title": "Email Code Registration",
                "content": []
              },
              {
                "markdown": "Use **Username Password Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **UsernamePasswordLogin**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\nawait auth.signIn({\n  username, // Can be username, phone or email\n  password\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function PasswordLogin() {\n  const [username, setUsername] = useState(\"\");\n  const [password, setPassword] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  // Login\n  const login = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signIn({\n        username, // Can be username, phone or email\n        password\n      });\n      setMessage(\"Login successful！\");\n      Alert.alert(\"successful\", \"Login successful\");\n    } catch (error) {\n      setMessage(`Login failed: ${error.message}`);\n      Alert.alert(\"failed\", `Login failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Account：</Text>\n      <TextInput\n        style={styles.input}\n        value={username}\n        onChangeText={setUsername}\n        placeholder=\"Username/Phone/Email\"\n      />\n      <Text style={styles.note}>Note: Add country code for phone login +86</Text>\n      <Text>Password：</Text>\n      <TextInput\n        style={styles.input}\n        value={password}\n        onChangeText={setPassword}\n        placeholder=\"Enter password\"\n        secureTextEntry\n      />\n      <Button title=\"Login\" onPress={login} disabled={!username || !password} />\n      {message && (\n        <Text\n          style={[\n            styles.message,\n            { color: message.includes(\"successful\") ? \"green\" : \"red\" }\n          ]}\n        >\n          {message}\n        </Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  note: {\n    fontSize: 12,\n    color: \"#666\",\n    marginBottom: 10\n  },\n  message: {\n    marginTop: 20,\n    textAlign: \"center\"\n  }\n});\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login",
                "content": []
              },
              {
                "markdown": "Use **SMS Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMS Verification Login**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n\n// Login\nawait auth.signInWithSms({\n  verificationInfo: res,\n  verificationCode: code,\n  phoneNum: `+86 ${phone}`\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function SmsLogin() {\n  const [phone, setPhone] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationInfo, setVerificationInfo] = useState(null);\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n      setVerificationInfo(res);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(`Send failed: ${error.message}`);\n    }\n  };\n\n  // Login\n  const login = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInWithSms({\n        verificationInfo,\n        verificationCode: code,\n        phoneNum: `+86 ${phone}`\n      });\n      setMessage(\"Login successful！\");\n      Alert.alert(\"successful\", \"Login successful\");\n    } catch (error) {\n      setMessage(`Login failed: ${error.message}`);\n      Alert.alert(\"failed\", `Login failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Phone number：</Text>\n      <TextInput\n        style={styles.input}\n        value={phone}\n        onChangeText={setPhone}\n        placeholder=\"13800000000\"\n        keyboardType=\"phone-pad\"\n      />\n      <Text>Verification code：</Text>\n      <View style={styles.row}>\n        <TextInput\n          style={[styles.input, styles.codeInput]}\n          value={code}\n          onChangeText={setCode}\n          placeholder=\"Verification code\"\n          keyboardType=\"numeric\"\n        />\n        <Button title=\"Send Code\" onPress={sendCode} disabled={!phone} />\n      </View>\n      <Button\n        title=\"Login\"\n        onPress={login}\n        disabled={!verificationInfo || !code}\n      />\n      {message && (\n        <Text\n          style={[\n            styles.message,\n            { color: message.includes(\"successful\") ? \"green\" : \"red\" }\n          ]}\n        >\n          {message}\n        </Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  row: {\n    flexDirection: \"row\",\n    alignItems: \"center\"\n  },\n  codeInput: {\n    flex: 1,\n    marginRight: 10\n  },\n  message: {\n    marginTop: 20,\n    textAlign: \"center\"\n  }\n});\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login",
                "content": []
              },
              {
                "markdown": "Use **Email Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Login\nawait auth.signInWithEmail({\n  verificationInfo: res,\n  verificationCode: code,\n  email\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function EmailLogin() {\n  const [email, setEmail] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationInfo, setVerificationInfo] = useState(null);\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ email });\n      setVerificationInfo(res);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(`Send failed: ${error.message}`);\n    }\n  };\n\n  // Login\n  const login = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInWithEmail({\n        verificationInfo,\n        verificationCode: code,\n        email\n      });\n      setMessage(\"Login successful！\");\n      Alert.alert(\"successful\", \"Login successful\");\n    } catch (error) {\n      setMessage(`Login failed: ${error.message}`);\n      Alert.alert(\"failed\", `Login failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Email：</Text>\n      <TextInput\n        style={styles.input}\n        value={email}\n        onChangeText={setEmail}\n        placeholder=\"example@email.com\"\n        keyboardType=\"email-address\"\n      />\n      <Text>Verification code：</Text>\n      <View style={styles.row}>\n        <TextInput\n          style={[styles.input, styles.codeInput]}\n          value={code}\n          onChangeText={setCode}\n          placeholder=\"Verification code\"\n          keyboardType=\"numeric\"\n        />\n        <Button title=\"Send Code\" onPress={sendCode} disabled={!email} />\n      </View>\n      <Button\n        title=\"Login\"\n        onPress={login}\n        disabled={!verificationInfo || !code}\n      />\n      {message && (\n        <Text\n          style={[\n            styles.message,\n            { color: message.includes(\"successful\") ? \"green\" : \"red\" }\n          ]}\n        >\n          {message}\n        </Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  row: {\n    flexDirection: \"row\",\n    alignItems: \"center\"\n  },\n  codeInput: {\n    flex: 1,\n    marginRight: 10\n  },\n  message: {\n    marginTop: 20,\n    textAlign: \"center\"\n  }\n});\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\nawait auth.signInAnonymously();\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Button, Text, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function AnonymousLogin() {\n  const [message, setMessage] = useState(\"\");\n\n  // anonymousLogin\n  const anonymousLogin = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInAnonymously();\n      setMessage(\"anonymousLogin successful！\");\n      Alert.alert(\"successful\", \"anonymousLogin successful\");\n    } catch (error) {\n      setMessage(`Login failed: ${error.message}`);\n      Alert.alert(\"failed\", `Login failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"anonymousLogin\" onPress={anonymousLogin} />\n      {message && (\n        <Text\n          style={[\n            styles.message,\n            { color: message.includes(\"successful\") ? \"green\" : \"red\" }\n          ]}\n        >\n          {message}\n        </Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20,\n    justifyContent: \"center\"\n  },\n  message: {\n    marginTop: 20,\n    textAlign: \"center\"\n  }\n});\n```",
                "index": 6,
                "title": "anonymousLogin",
                "content": []
              }
            ]
          }
        ]
      }
    ],
    "_id": "61882c92697c28dc003eebd92a5000f5",
    "_openid": "anon",
    "createdAt": 1769744604736,
    "updatedAt": 1769766702609
  },
  {
    "category": "Framework Integration,Backend Frameworks,Go",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 22,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/http-api/basic/overview",
    "content": [
      {
        "markdown": "Use **HTTP Request** in **Go** Callvarious CloudBase capabilities\n\n```bash\ngo get github.com/joho/godotenv\n```",
        "index": 1,
        "title": "Install Dependencies",
        "content": []
      },
      {
        "markdown": "Add the following code to your **Go** project",
        "index": 2,
        "title": "Initialize Configuration",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```go\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/joho/godotenv\"\n)\n\ntype CloudBaseClient struct {\n\tEnvID       string\n\tAccessToken string\n\tBaseURL     string\n\tHTTPClient  *http.Client\n}\n\nfunc NewCloudBaseClient() *CloudBaseClient {\n\tgodotenv.Load()\n\n\tenvID := os.Getenv(\"CLOUDBASE_ENV_ID\")\n\taccessToken := os.Getenv(\"CLOUDBASE_ACCESS_TOKEN\")\n\n\treturn &CloudBaseClient{\n\t\tEnvID:       envID,\n\t\tAccessToken: accessToken,\n\t\tBaseURL:     fmt.Sprintf(\"https://%s.api.tcloudbasegateway.com\", envID),\n\t\tHTTPClient:  &http.Client{},\n\t}\n}\n\nfunc (c *CloudBaseClient) Request(method, path string, body interface{}, customHeaders map[string]string) (interface{}, error) {\n\turl := c.BaseURL + path\n\n\tvar reqBody io.Reader\n\tif body != nil {\n\t\tjsonData, err := json.Marshal(body)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"JSONSerializefailed: %w\", err)\n\t\t}\n\t\treqBody = bytes.NewBuffer(jsonData)\n\t}\n\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Create requestfailed: %w\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+c.AccessToken)\n\n\tfor key, value := range customHeaders {\n\t\treq.Header.Set(key, value)\n\t}\n\n\tresp, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Requestfailed: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\tbodyBytes, _ := io.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"Requestfailed，status code: %d, Response: %s\", resp.StatusCode, string(bodyBytes))\n\t}\n\n\tbodyBytes, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Read responsefailed: %w\", err)\n\t}\n\n\tif len(bodyBytes) == 0 {\n\t\treturn true, nil\n\t}\n\n\tvar result interface{}\n\tif err := json.Unmarshal(bodyBytes, &result); err != nil {\n\t\treturn nil, fmt.Errorf(\"JSONParsefailed: %w\", err)\n\t}\n\n\treturn result, nil\n}\n\nvar Cloudbase = NewCloudBaseClient()\n```",
            "index": 1,
            "title": "cloudbase_client.go"
          },
          {
            "markdown": "> 💡Note: If admin permission is needed, obtain the APIKey from the [CloudBase Platform/ApiKeymanagement page](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}&#/env/apikey) Get APIKey to replace CLOUDBASE_ACCESS_TOKEN\n\n```properties\n# Environment ID\nCLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Anonymous access token\nCLOUDBASE_ACCESS_TOKEN={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": ".env"
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```go\npackage main\n\nimport (\n    \"fmt\"\n    \"net/http\"\n)\n\nfunc getPgData(cloudbase *CloudBaseClient, tableName string) {\n    // Query {%TABLE_NAME%} table\n    path := fmt.Sprintf(\"/v1/rdb/rest/%s?select=*&limit=10\", tableName)\n    headers := map[string]string{\"Accept\": \"application/json\"}\n    data, err := cloudbase.Request(\"GET\", path, nil, headers)\n\n    if err != nil {\n        fmt.Println(\"Error:\", err)\n        return\n    }\n\n    fmt.Println(\"Query result:\", data)\n}\n\n// Usage example\n// func main() {\n//     cloudbase := &CloudBaseClient{ ... }\n//     getPgData(cloudbase, \"{%TABLE_NAME%}\")\n// }\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```go\npackage main\n\nimport (\n    \"fmt\"\n    \"net/http\"\n)\n\nfunc addPgData(cloudbase *CloudBaseClient, tableName string) {\n    // Insert data into {%TABLE_NAME%}\n    path := fmt.Sprintf(\"/v1/rdb/rest/%s\", tableName)\n    body := []byte(`{\"title\":\"New Post\",\"status\":\"draft\"}`)\n    headers := map[string]string{\"Content-Type\": \"application/json\", \"Prefer\": \"return=representation\"}\n    data, err := cloudbase.Request(\"POST\", path, body, headers)\n\n    if err != nil {\n        fmt.Println(\"Error:\", err)\n        return\n    }\n\n    fmt.Println(\"Insert result:\", data)\n}\n\n// Usage example\n// func main() {\n//     cloudbase := &CloudBaseClient{ ... }\n//     addPgData(cloudbase, \"{%TABLE_NAME%}\")\n// }\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```go\npackage main\n\nimport (\n    \"fmt\"\n    \"net/http\"\n)\n\nfunc updatePgData(cloudbase *CloudBaseClient, tableName string) {\n    // Update record in {%TABLE_NAME%}\n    path := fmt.Sprintf(\"/v1/rdb/rest/%s?id=eq.1\", tableName)\n    body := []byte(`{\"status\":\"published\"}`)\n    headers := map[string]string{\"Content-Type\": \"application/json\", \"Prefer\": \"return=representation\"}\n    data, err := cloudbase.Request(\"PATCH\", path, body, headers)\n\n    if err != nil {\n        fmt.Println(\"Error:\", err)\n        return\n    }\n\n    fmt.Println(\"Update result:\", data)\n}\n\n// Usage example\n// func main() {\n//     cloudbase := &CloudBaseClient{ ... }\n//     updatePgData(cloudbase, \"{%TABLE_NAME%}\")\n// }\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```go\npackage main\n\nimport (\n    \"fmt\"\n    \"net/http\"\n)\n\nfunc upsertPgData(cloudbase *CloudBaseClient, tableName string) {\n    // Update record in {%TABLE_NAME%}\n    path := fmt.Sprintf(\"/v1/rdb/rest/%s\", tableName)\n    body := []byte(`{\"id\":1,\"title\":\"Post Title\",\"status\":\"published\"}`)\n    headers := map[string]string{\"Content-Type\": \"application/json\", \"Prefer\": \"resolution=merge-duplicates,return=representation\"}\n    data, err := cloudbase.Request(\"POST\", path, body, headers)\n\n    if err != nil {\n        fmt.Println(\"Error:\", err)\n        return\n    }\n\n    fmt.Println(\"Upsert result:\", data)\n}\n\n// Usage example\n// func main() {\n//     cloudbase := &CloudBaseClient{ ... }\n//     upsertPgData(cloudbase, \"{%TABLE_NAME%}\")\n// }\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```go\npackage main\n\nimport (\n    \"fmt\"\n    \"net/http\"\n)\n\nfunc deletePgData(cloudbase *CloudBaseClient, tableName string) {\n    // Delete record from {%TABLE_NAME%}\n    path := fmt.Sprintf(\"/v1/rdb/rest/%s?id=eq.1\", tableName)\n    headers := map[string]string{\"Accept\": \"application/json\"}\n    data, err := cloudbase.Request(\"DELETE\", path, nil, headers)\n\n    if err != nil {\n        fmt.Println(\"Error:\", err)\n        return\n    }\n\n    fmt.Println(\"Delete completed:\", data)\n}\n\n// Usage example\n// func main() {\n//     cloudbase := &CloudBaseClient{ ... }\n//     deletePgData(cloudbase, \"{%TABLE_NAME%}\")\n// }\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc GetMySQLData(tableName string) (interface{}, error) {\n\tpath := fmt.Sprintf(\"/v1/rdb/rest/%s?limit=10\", tableName)\n\tdata, err := Cloudbase.Request(\"GET\", path, nil, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Querysuccessful:\", data)\n\treturn data, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := GetMySQLData(\"{%TABLE_NAME%}\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc AddMySQLData(tableName string, data map[string]interface{}) (interface{}, error) {\n\tpath := fmt.Sprintf(\"/v1/rdb/rest/%s\", tableName)\n\tresult, err := Cloudbase.Request(\"POST\", path, data, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Insert successful:\", result)\n\treturn result, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := AddMySQLData(\"{%TABLE_NAME%}\", map[string]interface{}{\n\t\t\"title\": \"Example Title\",\n\t})\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc UpdateMySQLData(tableName, dataID string, data map[string]interface{}) (interface{}, error) {\n\tpath := fmt.Sprintf(\"/v1/rdb/rest/%s?id=eq.%s\", tableName, dataID)\n\tresult, err := Cloudbase.Request(\"PATCH\", path, data, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Update successful:\", result)\n\treturn result, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := UpdateMySQLData(\"{%TABLE_NAME%}\", \"<data id>\", map[string]interface{}{\n\t\t\"title\": \"New Title\",\n\t})\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc DeleteMySQLData(tableName, dataID string) (bool, error) {\n\tpath := fmt.Sprintf(\"/v1/rdb/rest/%s?id=eq.%s\", tableName, dataID)\n\t_, err := Cloudbase.Request(\"DELETE\", path, nil, nil)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfmt.Println(\"Delete successful\")\n\treturn true, nil\n}\n\n// Usage Example\nfunc main() {\n\tsuccess, err := DeleteMySQLData(\"{%TABLE_NAME%}\", \"<data id>\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\tfmt.Println(\"DeleteResult:\", success)\n}\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc GetModelData(modelName, envType string) ([]interface{}, error) {\n\tif envType == \"\" {\n\t\tenvType = \"prod\"\n\t}\n\n\tpath := fmt.Sprintf(\"/v1/model/%s/%s/list\", envType, modelName)\n\tpayload := map[string]interface{}{\n\t\t\"pageSize\":   10,\n\t\t\"pageNumber\": 1,\n\t\t\"getCount\":   true,\n\t}\n\n\tresult, err := Cloudbase.Request(\"POST\", path, payload, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resultMap, ok := result.(map[string]interface{}); ok {\n\t\tif data, ok := resultMap[\"data\"].(map[string]interface{}); ok {\n\t\t\tif records, ok := data[\"records\"].([]interface{}); ok {\n\t\t\t\tfmt.Println(\"Querysuccessful:\", records)\n\t\t\t\treturn records, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn []interface{}{}, nil\n}\n\n// Usage Example\nfunc main() {\n\trecords, err := GetModelData(\"{%TABLE_NAME%}\", \"prod\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc AddModelData(modelName string, data map[string]interface{}, envType string) (interface{}, error) {\n\tif envType == \"\" {\n\t\tenvType = \"prod\"\n\t}\n\n\tpath := fmt.Sprintf(\"/v1/model/%s/%s/create\", envType, modelName)\n\tpayload := map[string]interface{}{\n\t\t\"data\": data,\n\t}\n\n\tresult, err := Cloudbase.Request(\"POST\", path, payload, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resultMap, ok := result.(map[string]interface{}); ok {\n\t\tif dataMap, ok := resultMap[\"data\"].(map[string]interface{}); ok {\n\t\t\tif docID, ok := dataMap[\"id\"].(string); ok {\n\t\t\t\tfmt.Printf(\"Insert successful! id: %s\\n\", docID)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := AddModelData(\"{%TABLE_NAME%}\", map[string]interface{}{\n\t\t\"title\": \"Example Title\",\n\t}, \"prod\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc UpdateModelData(modelName, dataID string, data map[string]interface{}, envType string) (bool, error) {\n\tif envType == \"\" {\n\t\tenvType = \"prod\"\n\t}\n\n\tpath := fmt.Sprintf(\"/v1/model/%s/%s/update\", envType, modelName)\n\tpayload := map[string]interface{}{\n\t\t\"data\": data,\n\t\t\"filter\": map[string]interface{}{\n\t\t\t\"where\": map[string]interface{}{\n\t\t\t\t\"_id\": map[string]interface{}{\n\t\t\t\t\t\"$eq\": dataID,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err := Cloudbase.Request(\"PUT\", path, payload, nil)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfmt.Println(\"Update successful!\")\n\treturn true, nil\n}\n\n// Usage Example\nfunc main() {\n\tsuccess, err := UpdateModelData(\"{%TABLE_NAME%}\", \"<data id>\", map[string]interface{}{\n\t\t\"title\": \"New Title\",\n\t}, \"prod\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc DeleteModelData(modelName, dataID, envType string) (bool, error) {\n\tif envType == \"\" {\n\t\tenvType = \"prod\"\n\t}\n\n\tpath := fmt.Sprintf(\"/v1/model/%s/%s/delete\", envType, modelName)\n\tpayload := map[string]interface{}{\n\t\t\"filter\": map[string]interface{}{\n\t\t\t\"where\": map[string]interface{}{\n\t\t\t\t\"_id\": map[string]interface{}{\n\t\t\t\t\t\"$eq\": dataID,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err := Cloudbase.Request(\"POST\", path, payload, nil)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfmt.Println(\"Delete successful!\")\n\treturn true, nil\n}\n\n// Usage Example\nfunc main() {\n\tsuccess, err := DeleteModelData(\"{%TABLE_NAME%}\", \"<data id>\", \"prod\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc CallFunction(functionName string, data map[string]interface{}) (interface{}, error) {\n\tif data == nil {\n\t\tdata = map[string]interface{}{}\n\t}\n\n\tpath := fmt.Sprintf(\"/v1/functions/%s\", functionName)\n\tresult, err := Cloudbase.Request(\"POST\", path, data, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Cloud function call result:\", result)\n\treturn result, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := CallFunction(\"{%FUNCTION_NAME%}\", nil)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
            "index": 3,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc CallContainer(serviceName, path, method string, data map[string]interface{}) (interface{}, error) {\n\tif method == \"\" {\n\t\tmethod = \"GET\"\n\t}\n\n\tfullPath := fmt.Sprintf(\"/v1/cloudrun/%s/%s\", serviceName, path)\n\tfullPath = strings.TrimSuffix(fullPath, \"/\")\n\n\tresult, err := Cloudbase.Request(strings.ToUpper(method), fullPath, data, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Cloud RunCallResult:\", result)\n\treturn result, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := CallContainer(\"{%SERVICE_NAME%}\", \"\", \"GET\", nil)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
            "index": 4,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\nfunc UploadFile(filePath, objectID string) (map[string]interface{}, error) {\n\tif objectID == \"\" {\n\t\tfilename := filepath.Base(filePath)\n\t\ttimestamp := time.Now().UnixMilli()\n\t\tobjectID = fmt.Sprintf(\"uploads/%d-%s\", timestamp, filename)\n\t}\n\n\tuploadInfo, err := Cloudbase.Request(\"POST\", \"/v1/storages/get-objects-upload-info\",\n\t\t[]map[string]interface{}{{\"objectId\": objectID}}, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinfoList, ok := uploadInfo.([]interface{})\n\tif !ok || len(infoList) == 0 {\n\t\treturn nil, fmt.Errorf(\"Get upload infofailed\")\n\t}\n\n\tinfo := infoList[0].(map[string]interface{})\n\tuploadURL := info[\"uploadUrl\"].(string)\n\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"filedoes not exist: %s\", filePath)\n\t}\n\tdefer file.Close()\n\n\tfileData, err := io.ReadAll(file)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Readfilefailed: %w\", err)\n\t}\n\n\treq, err := http.NewRequest(\"PUT\", uploadURL, bytes.NewReader(fileData))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"Authorization\", info[\"authorization\"].(string))\n\treq.Header.Set(\"X-Cos-Security-Token\", info[\"token\"].(string))\n\treq.Header.Set(\"X-Cos-Meta-Fileid\", info[\"cloudObjectMeta\"].(string))\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fileUploadfailed: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\treturn nil, fmt.Errorf(\"Uploadfailed，status code: %d\", resp.StatusCode)\n\t}\n\n\tresult := map[string]interface{}{\n\t\t\"cloudObjectId\": info[\"cloudObjectId\"],\n\t\t\"downloadUrl\":   info[\"downloadUrl\"],\n\t\t\"objectId\":      objectID,\n\t}\n\n\tfmt.Println(\"fileUpload successful:\")\n\tfmt.Printf(\"- Object ID: %s\\n\", result[\"objectId\"])\n\tfmt.Printf(\"- DownloadURL: %s\\n\", result[\"downloadUrl\"])\n\n\treturn result, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := UploadFile(\"./example.jpg\", \"\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc GetFileURL(cloudObjectID string) (string, error) {\n\tresult, err := Cloudbase.Request(\"POST\", \"/v1/storages/get-objects-download-info\",\n\t\t[]map[string]interface{}{{\"cloudObjectId\": cloudObjectID}}, nil)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif resultList, ok := result.([]interface{}); ok && len(resultList) > 0 {\n\t\tif info, ok := resultList[0].(map[string]interface{}); ok {\n\t\t\tif downloadURL, ok := info[\"downloadUrl\"].(string); ok {\n\t\t\t\tfmt.Println(\"fileURL:\", downloadURL)\n\t\t\t\treturn downloadURL, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"Get File URLfailed\")\n}\n\n// Usage Example\nfunc main() {\n\tfileURL, err := GetFileURL(\"cloud://xxx.png\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nfunc DownloadFile(cloudObjectID, savePath string) (bool, error) {\n\tif savePath == \"\" {\n\t\tsavePath = \"./\"\n\t}\n\n\tresult, err := Cloudbase.Request(\"POST\", \"/v1/storages/get-objects-download-info\",\n\t\t[]map[string]interface{}{{\"cloudObjectId\": cloudObjectID}}, nil)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif resultList, ok := result.([]interface{}); ok && len(resultList) > 0 {\n\t\tif info, ok := resultList[0].(map[string]interface{}); ok {\n\t\t\tdownloadURL := info[\"downloadUrl\"].(string)\n\n\t\t\tparts := strings.Split(downloadURL, \"/\")\n\t\t\tfilename := strings.Split(parts[len(parts)-1], \"?\")[0]\n\n\t\t\tfileInfo, err := os.Stat(savePath)\n\t\t\tvar fullPath string\n\t\t\tif err == nil && fileInfo.IsDir() || strings.HasSuffix(savePath, \"/\") {\n\t\t\t\tfullPath = filepath.Join(savePath, filename)\n\t\t\t} else {\n\t\t\t\tfullPath = savePath\n\t\t\t}\n\n\t\t\tresp, err := http.Get(downloadURL)\n\t\t\tif err != nil {\n\t\t\t\treturn false, fmt.Errorf(\"Downloadfailed: %w\", err)\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\n\t\t\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\t\t\treturn false, fmt.Errorf(\"Downloadfailed，status code: %d\", resp.StatusCode)\n\t\t\t}\n\n\t\t\toutFile, err := os.Create(fullPath)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tdefer outFile.Close()\n\n\t\t\t_, err = io.Copy(outFile, resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tfmt.Printf(\"Downloadsuccessful! filesaved to: %s\\n\", fullPath)\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, fmt.Errorf(\"Downloadfailed\")\n}\n\n// Usage Example\nfunc main() {\n\t// Downloadto current directory，Useoriginalfilename\n\tsuccess, err := DownloadFile(\"cloud://xxx.png\", \"\")\n\n\t// Downloadto specified directory\n\t// success, err := DownloadFile(\"cloud://xxx.png\", \"./downloads/\")\n\n\t// Downloadand rename\n\t// success, err := DownloadFile(\"cloud://xxx.png\", \"./my-image.png\")\n\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc DeleteFile(cloudObjectIDs interface{}) (bool, error) {\n\tvar data []map[string]interface{}\n\n\tswitch v := cloudObjectIDs.(type) {\n\tcase string:\n\t\tdata = []map[string]interface{}{{\"cloudObjectId\": v}}\n\tcase []string:\n\t\tfor _, id := range v {\n\t\t\tdata = append(data, map[string]interface{}{\"cloudObjectId\": id})\n\t\t}\n\tdefault:\n\t\treturn false, fmt.Errorf(\"Not supportedparameterType\")\n\t}\n\n\t_, err := Cloudbase.Request(\"POST\", \"/v1/storages/delete-objects\", data, nil)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfmt.Println(\"Delete successful!\")\n\treturn true, nil\n}\n\n// Usage Example\nfunc main() {\n\tsuccess, err := DeleteFile(\"cloud://xxx.png\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```go\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc StreamText(model, subModel string, messages []map[string]string) (string, error) {\n\tpayload := map[string]interface{}{\n\t\t\"model\":    subModel,\n\t\t\"messages\": messages,\n\t\t\"stream\":   true,\n\t}\n\n\tjsonData, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\turl := fmt.Sprintf(\"%s/v1/ai/%s/chat/completions\", Cloudbase.BaseURL, model)\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonData))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"text/event-stream\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+Cloudbase.AccessToken)\n\n\tresp, err := Cloudbase.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"AI Call failed: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tfmt.Println(\"AI Streaming response:\")\n\tfullContent := \"\"\n\tscanner := bufio.NewScanner(resp.Body)\n\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif strings.HasPrefix(line, \"data: \") {\n\t\t\tdataStr := strings.TrimPrefix(line, \"data: \")\n\t\t\tif strings.TrimSpace(dataStr) != \"[DONE]\" {\n\t\t\t\tvar chunkData map[string]interface{}\n\t\t\t\tif err := json.Unmarshal([]byte(dataStr), &chunkData); err == nil {\n\t\t\t\t\tif choices, ok := chunkData[\"choices\"].([]interface{}); ok && len(choices) > 0 {\n\t\t\t\t\t\tif choice, ok := choices[0].(map[string]interface{}); ok {\n\t\t\t\t\t\t\tif delta, ok := choice[\"delta\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\t\tif content, ok := delta[\"content\"].(string); ok {\n\t\t\t\t\t\t\t\t\tfmt.Print(content)\n\t\t\t\t\t\t\t\t\tfullContent += content\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println()\n\treturn fullContent, nil\n}\n\n// Usage Example\nfunc main() {\n\tresponse, err := StreamText(\n\t\t\"{%AI_MODEL_NAME%}\",\n\t\t\"{%AI_SUB_MODEL_NAME%}\",\n\t\t[]map[string]string{\n\t\t\t{\"role\": \"system\", \"content\": \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\"},\n\t\t\t{\"role\": \"user\", \"content\": \"Spring\"},\n\t\t},\n\t)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc GenerateImage(prompt string) (map[string]interface{}, error) {\n\t// PrepareCallparameter\n\tdata := map[string]interface{}{\n\t\t\"prompt\": prompt,\n\t}\n\n\t// CallCloud FunctionGenerate Image\n\tresult, err := Cloudbase.Request(\"POST\", \"/v1/functions/<YOUR_FUNCTION_NAME>\", data, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resultMap, ok := result.(map[string]interface{}); ok {\n\t\tif success, ok := resultMap[\"success\"].(bool); ok && success {\n\t\t\timageUrl := resultMap[\"imageUrl\"].(string)\n\t\t\trevisedPrompt := \"\"\n\t\t\tif rp, ok := resultMap[\"revised_prompt\"].(string); ok {\n\t\t\t\trevisedPrompt = rp\n\t\t\t}\n\n\t\t\tfmt.Println(\"Generation successful!\")\n\t\t\tfmt.Printf(\"Image URL: %s\\n\", imageUrl)\n\t\t\tfmt.Printf(\"Optimized prompt: %s\\n\", revisedPrompt)\n\t\t\tfmt.Println(\"Note: Image URLValidis valid for24hours\")\n\n\t\t\treturn resultMap, nil\n\t\t} else {\n\t\t\tcode := \"\"\n\t\t\tmessage := \"\"\n\t\t\tif c, ok := resultMap[\"code\"].(string); ok {\n\t\t\t\tcode = c\n\t\t\t}\n\t\t\tif m, ok := resultMap[\"message\"].(string); ok {\n\t\t\t\tmessage = m\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"Generation failed: %s - %s\", code, message)\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"Requestfailed\")\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := GenerateImage(\"A cute cat playing in the sunshine\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t} else {\n\t\tfmt.Println(\"ImageGenerateDone:\", result)\n\t}\n}\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```go\n/*\nGo Call Agent Example (AG-UI Protocol)\nProtocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n*/\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n)\n\n// Message AG-UI protocolMessagestructure\ntype Message struct {\n\tID      string `json:\"id\"`\n\tRole    string `json:\"role\"`\n\tContent string `json:\"content\"`\n}\n\n// AGUIRequest AG-UI protocolRequestbody\ntype AGUIRequest struct {\n\tMessages       []Message              `json:\"messages\"`                 // Required: Message list\n\tThreadID       string                 `json:\"threadId,omitempty\"`       // Optional: Session ID for multi-turn conversation\n\tRunID          string                 `json:\"runId,omitempty\"`          // Optional: Run ID for execution tracking\n\tTools          []interface{}          `json:\"tools,omitempty\"`          // Optional: Frontend tool definitions\n\tContext        []interface{}          `json:\"context,omitempty\"`        // Optional: Context information\n\tForwardedProps map[string]interface{} `json:\"forwardedProps,omitempty\"` // Optional: Pass-through parameters\n}\n\nfunc ChatWithAgentStream(botID, msg string, history []Message) (string, error) {\n\tif history == nil {\n\t\thistory = []Message{}\n\t}\n\n\turl := fmt.Sprintf(\"%s/v1/aibot/bots/%s/send-message\", Cloudbase.BaseURL, botID)\n\n\t// Build message list (AG-UI protocol format)\n\tmessages := make([]Message, 0, len(history)+1)\n\n\t// AddHistoryMessage\n\tmessages = append(messages, history...)\n\n\t// AddCurrentuserMessage\n\tmessages = append(messages, Message{\n\t\tID:      fmt.Sprintf(\"msg-%s\", uuid.New().String()),\n\t\tRole:    \"user\",\n\t\tContent: msg,\n\t})\n\n\t// AG-UI protocolRequestbody\n\tpayload := AGUIRequest{\n\t\tMessages:       messages,\n\t\tThreadID:       fmt.Sprintf(\"thread-%s\", uuid.New().String()),\n\t\tRunID:          fmt.Sprintf(\"run-%s\", uuid.New().String()),\n\t\tTools:          []interface{}{},\n\t\tContext:        []interface{}{},\n\t\tForwardedProps: map[string]interface{}{},\n\t}\n\n\tjsonData, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonData))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"text/event-stream\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+Cloudbase.AccessToken)\n\n\tclient := &http.Client{Timeout: 30 * time.Second}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"AI Call failed: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tfmt.Println(\"AI Streaming response:\")\n\tfullContent := \"\"\n\tscanner := bufio.NewScanner(resp.Body)\n\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\t\tif strings.HasPrefix(line, \"data: \") {\n\t\t\tdataStr := strings.TrimSpace(strings.TrimPrefix(line, \"data: \"))\n\t\t\tif dataStr != \"\" && dataStr != \"[DONE]\" {\n\t\t\t\tvar chunkData map[string]interface{}\n\t\t\t\tif err := json.Unmarshal([]byte(dataStr), &chunkData); err == nil {\n\t\t\t\t\tvar content string\n\t\t\t\t\tif c, ok := chunkData[\"content\"].(string); ok {\n\t\t\t\t\t\tcontent = c\n\t\t\t\t\t} else if choices, ok := chunkData[\"choices\"].([]interface{}); ok && len(choices) > 0 {\n\t\t\t\t\t\tif choice, ok := choices[0].(map[string]interface{}); ok {\n\t\t\t\t\t\t\tif delta, ok := choice[\"delta\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\t\tif c, ok := delta[\"content\"].(string); ok {\n\t\t\t\t\t\t\t\t\tcontent = c\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if message, ok := choice[\"message\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\t\tif c, ok := message[\"content\"].(string); ok {\n\t\t\t\t\t\t\t\t\tcontent = c\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif content != \"\" {\n\t\t\t\t\t\tfmt.Print(content)\n\t\t\t\t\t\tfullContent += content\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println()\n\treturn fullContent, nil\n}\n\n// Usage Example\nfunc main() {\n\tresponse, err := ChatWithAgentStream(\"{%AGENT_ID%}\", \"Who are you\", nil)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\t_ = response\n}\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```go\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc ChatWithAgentStream(botID, msg string, history []map[string]string) (string, error) {\n\tif history == nil {\n\t\thistory = []map[string]string{}\n\t}\n\n\turl := fmt.Sprintf(\"%s/v1/aibot/bots/%s/send-message\", Cloudbase.BaseURL, botID)\n\tpayload := map[string]interface{}{\n\t\t\"history\": history,\n\t\t\"msg\":     msg,\n\t}\n\n\tjsonData, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonData))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"text/event-stream\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+Cloudbase.AccessToken)\n\n\tclient := &http.Client{Timeout: 30 * time.Second}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"AI Call failed: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tfmt.Println(\"AI Streaming response:\")\n\tfullContent := \"\"\n\tscanner := bufio.NewScanner(resp.Body)\n\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\t\tif strings.HasPrefix(line, \"data: \") {\n\t\t\tdataStr := strings.TrimSpace(strings.TrimPrefix(line, \"data: \"))\n\t\t\tif dataStr != \"\" && dataStr != \"[DONE]\" {\n\t\t\t\tvar chunkData map[string]interface{}\n\t\t\t\tif err := json.Unmarshal([]byte(dataStr), &chunkData); err == nil {\n\t\t\t\t\tvar content string\n\t\t\t\t\tif c, ok := chunkData[\"content\"].(string); ok {\n\t\t\t\t\t\tcontent = c\n\t\t\t\t\t} else if choices, ok := chunkData[\"choices\"].([]interface{}); ok && len(choices) > 0 {\n\t\t\t\t\t\tif choice, ok := choices[0].(map[string]interface{}); ok {\n\t\t\t\t\t\t\tif delta, ok := choice[\"delta\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\t\tif c, ok := delta[\"content\"].(string); ok {\n\t\t\t\t\t\t\t\t\tcontent = c\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if message, ok := choice[\"message\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\t\tif c, ok := message[\"content\"].(string); ok {\n\t\t\t\t\t\t\t\t\tcontent = c\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif content != \"\" {\n\t\t\t\t\t\tfmt.Print(content)\n\t\t\t\t\t\tfullContent += content\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println()\n\treturn fullContent, nil\n}\n\n// Usage Example\nfunc main() {\n\tresponse, err := ChatWithAgentStream(\"{%AGENT_ID%}\", \"Who are you\", nil)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc SignIn(username, password string) (map[string]interface{}, error) {\n\tresult, err := Cloudbase.Request(\"POST\", \"/auth/v1/signin\",\n\t\tmap[string]interface{}{\n\t\t\t\"username\": username,\n\t\t\t\"password\": password,\n\t\t}, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resultMap, ok := result.(map[string]interface{}); ok {\n\t\taccessToken := resultMap[\"access_token\"].(string)\n\t\tuserID := resultMap[\"sub\"].(string)\n\n\t\tfmt.Printf(\"Login successful! User ID: %s\\n\", userID)\n\t\tfmt.Printf(\"Access token: %s...\\n\", accessToken[:20])\n\t\treturn resultMap, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"Login failed\")\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := SignIn(\"your_username\", \"your_password\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
            "index": 8,
            "id": "identity",
            "title": "Authentication"
          }
        ]
      }
    ],
    "_id": "6659ad07697c28d700385c6a2e5f18ac",
    "_openid": "anon",
    "createdAt": 1769744599204,
    "updatedAt": 1769766697057
  },
  {
    "category": "Framework Integration,MiniProgram / MiniGame,MiniGame,Cocos",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 0,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/api-reference/webv2/adapter",
    "content": [
      {
        "markdown": "`@cloudbase/js-sdk` Combine with `@cloudbase/adapter-cocos_native` allows you toin Cocos projectaccess CloudBase services and resources。",
        "index": 1,
        "title": "Install SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```bash\nnpm i @cloudbase/js-sdk @cloudbase/adapter-cocos_native\n```",
            "index": 1,
            "title": "npm",
            "content": []
          },
          {
            "markdown": "```bash\nyarn add @cloudbase/js-sdk @cloudbase/adapter-cocos_native\n```",
            "index": 2,
            "title": "yarn",
            "content": []
          },
          {
            "markdown": "```bash\npnpm add @cloudbase/js-sdk @cloudbase/adapter-cocos_native\n```",
            "index": 3,
            "title": "pnpm",
            "content": []
          }
        ]
      },
      {
        "markdown": "Add the following code to your Cocos project",
        "index": 2,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nimport cloudbaseSDK from \"@cloudbase/js-sdk\";\nimport adapter from \"@cloudbase/adapter-cocos_native\";\n\n// Registeradapter\ncloudbaseSDK.useAdapters(adapter);\n\nconst cloudbase = cloudbaseSDK.init({\n  // Environment ID\n  env: \"{%ENV_ID%}\",\n  // region\n  region: \"{%REGION%}\",\n  // Anonymous access token\n  accessKey: \"{%PUBLISHABLE_KEY%}\"\n});\n\nexport default cloudbase;\n```",
            "index": 1,
            "title": "scripts/services/CloudbaseService.js",
            "content": []
          }
        ]
      },
      {
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('QueryData')\nexport class QueryData extends Component {\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onLoad() {\n    try {\n      const { data, error } = await cloudbase.database().from(\"{%TABLE_NAME%}\").select(\"*\").limit(10);\n\n      if (!error) {\n        this.resultLabel.string = `Querysuccessful：${JSON.stringify(data)}`;\n        console.log('QueryResult：', data);\n      } else {\n        this.resultLabel.string = 'Queryfailed';\n        console.error('Queryfailed：', error);\n      }\n    } catch (error) {\n      this.resultLabel.string = `Queryfailed: ${error.message}`;\n      console.error('Queryfailed：', error);\n    }\n  }\n}\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"Example Title\" });\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('AddData')\nexport class AddData extends Component {\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onAddButtonClick() {\n    const title = this.titleInput.string;\n    if (!title) {\n      this.resultLabel.string = 'Please enterTitle';\n      return;\n    }\n\n    try {\n      const { data, error } = await cloudbase.database().from(\"{%TABLE_NAME%}\").insert({ title });\n\n      if (!error) {\n        this.resultLabel.string = 'Insert successful';\n        this.titleInput.string = '';\n        console.log('Insert successful：', data);\n      } else {\n        this.resultLabel.string = 'Insert failed';\n        console.error('Insert failed：', error);\n      }\n    } catch (error) {\n      this.resultLabel.string = `Insert failed: ${error.message}`;\n      console.error('Insert failed：', error);\n    }\n  }\n}\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ title: \"New Title\" })\n  .eq(\"id\", dataId);\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('UpdateData')\nexport class UpdateData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onUpdateButtonClick() {\n    const dataId = this.idInput.string;\n    const newTitle = this.titleInput.string;\n\n    if (!dataId || !newTitle) {\n      this.resultLabel.string = 'Please enterDataIDandNew Title';\n      return;\n    }\n\n    try {\n      const { data, error } = await cloudbase.database().from(\"{%TABLE_NAME%}\").update({ title: newTitle }).eq(\"id\", dataId);\n\n      if (!error) {\n        this.resultLabel.string = 'Update successful';\n        this.idInput.string = '';\n        this.titleInput.string = '';\n        console.log('Update successful：', data);\n      } else {\n        this.resultLabel.string = 'Update failed';\n        console.error('Update failed：', error);\n      }\n    } catch (error) {\n      this.resultLabel.string = `Update failed: ${error.message}`;\n      console.error('Update failed：', error);\n    }\n  }\n}\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Title\" });\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('UpsertData')\nexport class UpsertData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onUpsertButtonClick() {\n    const id = parseInt(this.idInput.string);\n    const title = this.titleInput.string;\n\n    if (!id || !title) {\n      this.resultLabel.string = 'Please enterIDandTitle';\n      return;\n    }\n\n    try {\n      const { data, error } = await cloudbase.database().from(\"{%TABLE_NAME%}\").upsert({ id, title });\n\n      if (!error) {\n        this.resultLabel.string = 'Operation successful';\n        this.idInput.string = '';\n        this.titleInput.string = '';\n        console.log('Operation successful：', data);\n      } else {\n        this.resultLabel.string = 'Operation failed';\n        console.error('Operation failed：', error);\n      }\n    } catch (error) {\n      this.resultLabel.string = `Operation failed: ${error.message}`;\n      console.error('Operation failed：', error);\n    }\n  }\n}\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", dataId);\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('DeleteData')\nexport class DeleteData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onDeleteButtonClick() {\n    const dataId = this.idInput.string;\n\n    if (!dataId) {\n      this.resultLabel.string = 'Please entershouldDeleteDataID';\n      return;\n    }\n\n    try {\n      const { data, error } = await cloudbase.database().from(\"{%TABLE_NAME%}\").delete().eq(\"id\", dataId);\n\n      if (!error) {\n        this.resultLabel.string = 'Delete successful';\n        this.idInput.string = '';\n        console.log('Delete successful：', data);\n      } else {\n        this.resultLabel.string = 'Delete failed';\n        console.error('Delete failed：', error);\n      }\n    } catch (error) {\n      this.resultLabel.string = `Delete failed: ${error.message}`;\n      console.error('Delete failed：', error);\n    }\n  }\n}\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('QueryDocData')\nexport class QueryDocData extends Component {\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onLoad() {\n    try {\n      const db = cloudbase.database();\n      const res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n\n      this.resultLabel.string = `Querysuccessful：${JSON.stringify(res.data)}`;\n      console.log('QueryResult：', res.data);\n    } catch (error) {\n      this.resultLabel.string = `Queryfailed: ${error.message}`;\n      console.error('Queryfailed：', error);\n    }\n  }\n}\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({ title: \"Example Title\" });\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('AddDocData')\nexport class AddDocData extends Component {\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onAddButtonClick() {\n    const title = this.titleInput.string;\n    if (!title) {\n      this.resultLabel.string = 'Please enterTitle';\n      return;\n    }\n\n    try {\n      const db = cloudbase.database();\n      const res = await db.collection(\"{%TABLE_NAME%}\").add({ title });\n\n      this.resultLabel.string = `Insert successful! id: ${res.id}`;\n      this.titleInput.string = '';\n      console.log('Insert successful：', res);\n    } catch (error) {\n      this.resultLabel.string = `Insert failed: ${error.message}`;\n      console.error('Insert failed：', error);\n    }\n  }\n}\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(dataId).update({ title: \"New Title\" });\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('UpdateDocData')\nexport class UpdateDocData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onUpdateButtonClick() {\n    const dataId = this.idInput.string;\n    const newTitle = this.titleInput.string;\n\n    if (!dataId || !newTitle) {\n      this.resultLabel.string = 'Please enterDataIDandNew Title';\n      return;\n    }\n\n    try {\n      const db = cloudbase.database();\n      await db.collection(\"{%TABLE_NAME%}\").doc(dataId).update({ title: newTitle });\n\n      this.resultLabel.string = 'Update successful';\n      this.idInput.string = '';\n      this.titleInput.string = '';\n      console.log('Update successful');\n    } catch (error) {\n      this.resultLabel.string = `Update failed: ${error.message}`;\n      console.error('Update failed：', error);\n    }\n  }\n}\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(dataId).remove();\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('DeleteDocData')\nexport class DeleteDocData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onDeleteButtonClick() {\n    const dataId = this.idInput.string;\n\n    if (!dataId) {\n      this.resultLabel.string = 'Please entershouldDeleteDataID';\n      return;\n    }\n\n    try {\n      const db = cloudbase.database();\n      await db.collection(\"{%TABLE_NAME%}\").doc(dataId).remove();\n\n      this.resultLabel.string = 'Delete successful';\n      this.idInput.string = '';\n      console.log('Delete successful');\n    } catch (error) {\n      this.resultLabel.string = `Delete failed: ${error.message}`;\n      console.error('Delete failed：', error);\n    }\n  }\n}\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('QueryModelData')\nexport class QueryModelData extends Component {\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onLoad() {\n    try {\n      const res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({ pageNumber: 1, pagesize: 10 });\n\n      const records = res.data?.records || [];\n      this.resultLabel.string = `Querysuccessful：${JSON.stringify(records)}`;\n      console.log('QueryResult：', records);\n    } catch (error) {\n      this.resultLabel.string = `Queryfailed: ${error.message}`;\n      console.error('Queryfailed：', error);\n    }\n  }\n}\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: { title: \"Example Title\" }\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('AddModelData')\nexport class AddModelData extends Component {\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onAddButtonClick() {\n    const title = this.titleInput.string;\n    if (!title) {\n      this.resultLabel.string = 'Please enterTitle';\n      return;\n    }\n\n    try {\n      const res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({ data: { title } });\n\n      this.resultLabel.string = `Insert successful! id: ${res.data.id}`;\n      this.titleInput.string = '';\n      console.log('Insert successful：', res);\n    } catch (error) {\n      this.resultLabel.string = `Insert failed: ${error.message}`;\n      console.error('Insert failed：', error);\n    }\n  }\n}\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nawait cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: { title: \"New Title\" },\n  filter: { where: { _id: { $eq: dataId } } }\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('UpdateModelData')\nexport class UpdateModelData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onUpdateButtonClick() {\n    const dataId = this.idInput.string;\n    const newTitle = this.titleInput.string;\n\n    if (!dataId || !newTitle) {\n      this.resultLabel.string = 'Please enterDataIDandNew Title';\n      return;\n    }\n\n    try {\n      await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n        data: { title: newTitle },\n        filter: { where: { _id: { $eq: dataId } } }\n      });\n\n      this.resultLabel.string = 'Update successful';\n      this.idInput.string = '';\n      this.titleInput.string = '';\n      console.log('Update successful');\n    } catch (error) {\n      this.resultLabel.string = `Update failed: ${error.message}`;\n      console.error('Update failed：', error);\n    }\n  }\n}\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nawait cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: { where: { _id: { $eq: dataId } } }\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('DeleteModelData')\nexport class DeleteModelData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onDeleteButtonClick() {\n    const dataId = this.idInput.string;\n\n    if (!dataId) {\n      this.resultLabel.string = 'Please entershouldDeleteDataID';\n      return;\n    }\n\n    try {\n      await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n        filter: { where: { _id: { $eq: dataId } } }\n      });\n\n      this.resultLabel.string = 'Delete successful';\n      this.idInput.string = '';\n      console.log('Delete successful');\n    } catch (error) {\n      this.resultLabel.string = `Delete failed: ${error.message}`;\n      console.error('Delete failed：', error);\n    }\n  }\n}\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {}\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('CallFunction')\nexport class CallFunction extends Component {\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onCallButtonClick() {\n    try {\n      const res = await cloudbase.callFunction({\n        name: \"{%FUNCTION_NAME%}\",\n        data: {}\n      });\n\n      this.resultLabel.string = `Callsuccessful：${JSON.stringify(res.result)}`;\n      console.log('CallResult：', res.result);\n    } catch (error) {\n      this.resultLabel.string = `Call failed: ${error.message}`;\n      console.error('Call failed：', error);\n    }\n  }\n}\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function",
            "content": []
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\n// Call {%SERVICE_NAME%} Cloud Runservice\nconst res = await cloudbase.callContainer({\n  name: \"{%SERVICE_NAME%}\"\n  method: 'POST',\n  path: '/',\n  header:{\n    'Content-Type': 'application/json; charset=utf-8'\n  },\n  data: {},\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('CallRun')\nexport class CallRun extends Component {\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onCallButtonClick() {\n    try {\n      // Call {%SERVICE_NAME%} Cloud Runservice\n      const res = await cloudbase.callContainer({\n        name: \"{%SERVICE_NAME%}\"\n        method: 'POST',\n        path: '/',\n        header:{\n          'Content-Type': 'application/json; charset=utf-8'\n        },\n        data: {},\n      });\n\n      this.resultLabel.string = `Callsuccessful：${JSON.stringify(res)}`;\n      console.log('CallResult：', res);\n    } catch (error) {\n      this.resultLabel.string = `Call failed: ${error.message}`;\n      console.error('Call failed：', error);\n    }\n  }\n}\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run",
            "content": []
          },
          {
            "index": 6,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.uploadFile({\n  cloudPath: `images/${Date.now()}.png`,\n  filePath: filePath\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('UploadFile')\nexport class UploadFile extends Component {\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onUploadButtonClick() {\n    try {\n      // Note：actualUseneedfromuserSelectorgame resourcesGetfilePath\n      const filePath = 'path/to/your/file.png';\n      const cloudPath = `images/${Date.now()}-${Math.random()}.png`;\n\n      const res = await cloudbase.uploadFile({\n        cloudPath: cloudPath,\n        filePath: filePath\n      });\n\n      this.resultLabel.string = `Upload successful！fileID: ${res.fileID}`;\n      console.log('Upload successful：', res);\n    } catch (error) {\n      this.resultLabel.string = `Uploadfailed: ${error.message}`;\n      console.error('Uploadfailed：', error);\n    }\n  }\n}\n```",
                "index": 1,
                "title": "Upload File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.getTempFileURL({\n  fileList: [fileId]\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('GetFileUrl')\nexport class GetFileUrl extends Component {\n  @property(EditBox)\n  fileIdInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onGetUrlButtonClick() {\n    const fileId = this.fileIdInput.string;\n\n    if (!fileId) {\n      this.resultLabel.string = 'Please enterfileID';\n      return;\n    }\n\n    try {\n      const res = await cloudbase.getTempFileURL({\n        fileList: [fileId]\n      });\n\n      const fileUrl = res.fileList[0].tempFileURL;\n      this.resultLabel.string = `fileURL：${fileUrl}`;\n      console.log('fileURL：', fileUrl);\n    } catch (error) {\n      this.resultLabel.string = `Getfailed: ${error.message}`;\n      console.error('Getfailed：', error);\n    }\n  }\n}\n```",
                "index": 2,
                "title": "Get File URL"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.downloadFile({\n  fileID: fileId\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('DownloadFile')\nexport class DownloadFile extends Component {\n  @property(EditBox)\n  fileIdInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onDownloadButtonClick() {\n    const fileId = this.fileIdInput.string;\n\n    if (!fileId) {\n      this.resultLabel.string = 'Please enterfileID';\n      return;\n    }\n\n    try {\n      const res = await cloudbase.downloadFile({\n        fileID: fileId\n      });\n\n      this.resultLabel.string = `Downloadsuccessful！localPath: ${res.tempFilePath}`;\n      console.log('Downloadsuccessful：', res);\n    } catch (error) {\n      this.resultLabel.string = `Downloadfailed: ${error.message}`;\n      console.error('Downloadfailed：', error);\n    }\n  }\n}\n```",
                "index": 3,
                "title": "Download File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.deleteFile({\n  fileList: [fileId]\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('DeleteFile')\nexport class DeleteFile extends Component {\n  @property(EditBox)\n  fileIdInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onDeleteButtonClick() {\n    const fileId = this.fileIdInput.string;\n\n    if (!fileId) {\n      this.resultLabel.string = 'Please enterfileID';\n      return;\n    }\n\n    try {\n      const res = await cloudbase.deleteFile({\n        fileList: [fileId]\n      });\n\n      if (res.fileList[0].code === \"SUCCESS\") {\n        this.resultLabel.string = 'Delete successful';\n        this.fileIdInput.string = '';\n        console.log('Delete successful');\n      } else {\n        this.resultLabel.string = 'Delete failed';\n        console.error('Delete failed');\n      }\n    } catch (error) {\n      this.resultLabel.string = `Delete failed: ${error.message}`;\n      console.error('Delete failed：', error);\n    }\n  }\n}\n```",
                "index": 4,
                "title": "Delete File"
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst ai = cloudbase.ai();\nconst model = ai.createModel(\"{%AI_MODEL_NAME%}\");\n\n// EnsurealreadyLogin\nconst loginState = await cloudbase.auth().getLoginState();\nif (!loginState) {\n  await cloudbase.auth().signInAnonymously();\n}\n\nconst res = await model.streamText({\n  model: \"{%AI_SUB_MODEL_NAME%}\",\n  messages: [\n    { role: \"system\", content: \"systemNoteword\" },\n    { role: \"user\", content: \"userInput\" }\n  ]\n});\n\nfor await (let str of res.textStream) {\n  // ProcessStreaming response\n}\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('CallAIModel')\nexport class CallAIModel extends Component {\n  @property(EditBox)\n  inputBox: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  @property(Label)\n  statusLabel: Label = null;\n\n  async onGenerateButtonClick() {\n    const input = this.inputBox.string;\n    if (!input) {\n      this.statusLabel.string = 'Please entertopic';\n      return;\n    }\n\n    this.statusLabel.string = 'Generating...';\n    this.resultLabel.string = '';\n\n    try {\n      const ai = cloudbase.ai();\n      const model = ai.createModel(\"{%AI_MODEL_NAME%}\");\n\n      // EnsurealreadyLogin\n      const loginState = await cloudbase.auth().getLoginState();\n      if (!loginState) {\n        await cloudbase.auth().signInAnonymously();\n      }\n\n      const res = await model.streamText({\n        model: \"{%AI_SUB_MODEL_NAME%}\",\n        messages: [\n          { role: \"system\", content: \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\" },\n          { role: \"user\", content: input }\n        ]\n      });\n\n      let fullText = '';\n      for await (let str of res.textStream) {\n        fullText += str;\n        this.resultLabel.string = fullText;\n      }\n\n      this.statusLabel.string = 'GenerateDone';\n      console.log('GenerateDone：', fullText);\n    } catch (err) {\n      this.statusLabel.string = 'Generation failed';\n      this.resultLabel.string = `Error: ${err.message}`;\n      console.error('Generation failed：', err);\n    }\n  }\n}\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation"
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\n// Call image generation cloud function\nconst res = await cloudbase.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: {\n    prompt: \"A cute cat playing in the sunshine\"\n  }\n});\n\nconst result = res.result;\n\nif (result.success) {\n  // Generation successful\n  console.log(\"Generation successful!\");\n  console.log(\"Image URL:\", result.imageUrl);\n  console.log(\"Optimized prompt:\", result.revised_prompt);\n\n  // Use image\n  // Note: Image URL is valid for 24 hours, please save or transfer promptly\n} else {\n  // Generation failed\n  console.error(\"Generation failed:\", result.code, result.message);\n}\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label, Sprite } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('GenerateImage')\nexport class GenerateImage extends Component {\n  @property(EditBox)\n  promptInput: EditBox = null;\n\n  @property(Label)\n  statusLabel: Label = null;\n\n  @property(Sprite)\n  imageSprite: Sprite = null;\n\n  async onGenerateButtonClick() {\n    const prompt = this.promptInput.string;\n    if (!prompt) {\n      this.statusLabel.string = 'Enter image description';\n      return;\n    }\n\n    this.statusLabel.string = 'Generating...';\n\n    try {\n      // Call image generation cloud function\n      const res = await cloudbase.callFunction({\n        name: \"<YOUR_FUNCTION_NAME>\",\n        data: {\n          prompt: prompt\n        }\n      });\n\n      const result = res.result;\n\n      if (result.success) {\n        this.statusLabel.string = 'Generation successful！';\n        console.log('Image URL:', result.imageUrl);\n        console.log('Optimized prompt:', result.revised_prompt);\n\n        // LoadImageto Sprite\n        // Note：needUsenetworkLoadImagemethod\n        // Specific implementationcanrootbased on Cocos Creator VersionAdjust\n      } else {\n        this.statusLabel.string = `Generation failed：${result.message}`;\n        console.error('Generation failed:', result.code, result.message);\n      }\n    } catch (err) {\n      this.statusLabel.string = 'Call failed';\n      console.error('Call failed:', err);\n    }\n  }\n}\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation"
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```javascript\nimport cloudbase from './services/CloudbaseService';\n\nconst ai = cloudbase.ai();\n\n// EnsurealreadyLogin\nconst loginState = await cloudbase.auth().getLoginState();\nif (!loginState) {\n  await cloudbase.auth().signInAnonymously();\n}\n\nconst res = await ai.bot.sendMessage({\n  botId: '{%AGENT_ID%}',\n  // Refer to frontend-backend communication protocol for input structure：\n  // https://docs.cloudbase.net/ai/agent/http-agent-protocol\n  threadId: '550e8400-e29b-41d4-a716-446655440000',\n  runId: 'run_001',\n  messages: [\n    {\n      id: 'msg-1',\n      role: 'user',\n      content: 'Hello',\n    },\n  ],\n  tools: [],\n  context: [],\n  state: {},\n  forwardedProps: {},\n});\n\nfor await (let str of res.textStream) {\n  // ProcessStreaming response\n}\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('CallAgent')\nexport class CallAgent extends Component {\n  @property(EditBox)\n  inputBox: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  @property(Label)\n  statusLabel: Label = null;\n\n  async onSendButtonClick() {\n    const input = this.inputBox.string;\n    if (!input) {\n      this.statusLabel.string = 'Please enterquestion';\n      return;\n    }\n\n    this.statusLabel.string = 'Send...';\n    this.resultLabel.string = '';\n\n    try {\n      const ai = cloudbase.ai();\n\n      // EnsurealreadyLogin\n      const loginState = await cloudbase.auth().getLoginState();\n      if (!loginState) {\n        await cloudbase.auth().signInAnonymously();\n      }\n\n      const res = await ai.bot.sendMessage({\n        botId: '{%AGENT_ID%}',\n        // Refer to frontend-backend communication protocol for input structure：\n        // https://docs.cloudbase.net/ai/agent/http-agent-protocol\n        threadId: '550e8400-e29b-41d4-a716-446655440000',\n        runId: 'run_001',\n        messages: [\n          {\n            id: 'msg-1',\n            role: 'user',\n            content: input,\n          },\n        ],\n        tools: [],\n        context: [],\n        state: {},\n        forwardedProps: {},\n      });\n\n      let fullText = '';\n      for await (let str of res.textStream) {\n        fullText += str;\n        this.resultLabel.string = fullText;\n      }\n\n      this.statusLabel.string = 'answerDone';\n      console.log('answerDone：', fullText);\n    } catch (err) {\n      this.statusLabel.string = 'Send failed';\n      this.resultLabel.string = `Error: ${err.message}`;\n      console.error('Send failed：', err);\n    }\n  }\n}\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst ai = cloudbase.ai();\n\n// EnsurealreadyLogin\nconst loginState = await cloudbase.auth().getLoginState();\nif (!loginState) {\n  await cloudbase.auth().signInAnonymously();\n}\n\nconst res = await ai.bot.sendMessage({\n  botId: \"{%AGENT_ID%}\",\n  msg: \"userMessage\"\n});\n\nfor await (let str of res.textStream) {\n  // ProcessStreaming response\n}\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('CallAgent')\nexport class CallAgent extends Component {\n  @property(EditBox)\n  inputBox: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  @property(Label)\n  statusLabel: Label = null;\n\n  async onSendButtonClick() {\n    const input = this.inputBox.string;\n    if (!input) {\n      this.statusLabel.string = 'Please enterquestion';\n      return;\n    }\n\n    this.statusLabel.string = 'Send...';\n    this.resultLabel.string = '';\n\n    try {\n      const ai = cloudbase.ai();\n\n      // EnsurealreadyLogin\n      const loginState = await cloudbase.auth().getLoginState();\n      if (!loginState) {\n        await cloudbase.auth().signInAnonymously();\n      }\n\n      const res = await ai.bot.sendMessage({\n        botId: '{%AGENT_ID%}',\n        msg: input,\n      });\n\n      let fullText = '';\n      for await (let str of res.textStream) {\n        fullText += str;\n        this.resultLabel.string = fullText;\n      }\n\n      this.statusLabel.string = 'answerDone';\n      console.log('answerDone：', fullText);\n    } catch (err) {\n      this.statusLabel.string = 'Send failed';\n      this.resultLabel.string = `Error: ${err.message}`;\n      console.error('Send failed：', err);\n    }\n  }\n}\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 9,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "Use **SMS Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMSVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: phone });\nconst verificationId = res.verification_id;\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register\nawait auth.signUp({\n  phone_number: `+86 ${phone}`,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${phone.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('SmsRegister')\nexport class SmsRegister extends Component {\n  @property(EditBox)\n  phoneInput: EditBox = null;\n\n  @property(EditBox)\n  codeInput: EditBox = null;\n\n  @property(Label)\n  messageLabel: Label = null;\n\n  private verificationId: string = '';\n\n  // Send Code\n  async onSendCodeButtonClick() {\n    const phone = this.phoneInput.string;\n    if (!phone) {\n      this.messageLabel.string = 'Please enterPhone number';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ phone_number: phone });\n      this.verificationId = res.verification_id;\n      this.messageLabel.string = 'Verification code sent！';\n    } catch (error) {\n      this.messageLabel.string = `Send failed: ${error.message}`;\n    }\n  }\n\n  // Register\n  async onRegisterButtonClick() {\n    const phone = this.phoneInput.string;\n    const code = this.codeInput.string;\n\n    if (!this.verificationId || !code) {\n      this.messageLabel.string = 'please firstSend Code';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      // Verify the code\n      const verifyRes = await auth.verify({\n        verification_id: this.verificationId,\n        verification_code: code,\n      });\n      // Register (auto-login if user exists)\n      await auth.signUp({\n        phone_number: `+86 ${phone}`,\n        verification_code: code,\n        verification_token: verifyRes.verification_token,\n        name: `user_${phone.slice(-4)}`,\n        password: \"admin@123\"\n      });\n      this.messageLabel.string = 'Registration successful！';\n      console.log('Registration successful');\n    } catch (error) {\n      this.messageLabel.string = `Registration failed: ${error.message}`;\n      console.error('Registration failed：', error);\n    }\n  }\n}\n```",
                "index": 1,
                "title": "SMS Code Registration"
              },
              {
                "markdown": "Use **Email Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\nconst verificationId = res.verification_id;\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register\nawait auth.signUp({\n  email,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${email.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('EmailRegister')\nexport class EmailRegister extends Component {\n  @property(EditBox)\n  emailInput: EditBox = null;\n\n  @property(EditBox)\n  codeInput: EditBox = null;\n\n  @property(Label)\n  messageLabel: Label = null;\n\n  private verificationId: string = '';\n\n  // Send Code\n  async onSendCodeButtonClick() {\n    const email = this.emailInput.string;\n    if (!email) {\n      this.messageLabel.string = 'Please enterEmail';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ email });\n      this.verificationId = res.verification_id;\n      this.messageLabel.string = 'Verification code sent！';\n    } catch (error) {\n      this.messageLabel.string = `Send failed: ${error.message}`;\n    }\n  }\n\n  // Register\n  async onRegisterButtonClick() {\n    const email = this.emailInput.string;\n    const code = this.codeInput.string;\n\n    if (!this.verificationId || !code) {\n      this.messageLabel.string = 'please firstSend Code';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      // Verify the code\n      const verifyRes = await auth.verify({\n        verification_id: this.verificationId,\n        verification_code: code,\n      });\n      // Register (auto-login if user exists)\n      await auth.signUp({\n        email,\n        verification_code: code,\n        verification_token: verifyRes.verification_token,\n        name: `user_${email.slice(-4)}`,\n        password: \"admin@123\"\n      });\n      this.messageLabel.string = 'Registration successful！';\n      console.log('Registration successful');\n    } catch (error) {\n      this.messageLabel.string = `Registration failed: ${error.message}`;\n      console.error('Registration failed：', error);\n    }\n  }\n}\n```",
                "index": 2,
                "title": "Email Code Registration"
              },
              {
                "markdown": "Use **Username Password Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **UsernamePasswordLogin**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst auth = cloudbase.auth();\nawait auth.signIn({\n  username, // Can be username, phone or email\n  password\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('PasswordLogin')\nexport class PasswordLogin extends Component {\n  @property(EditBox)\n  usernameInput: EditBox = null;\n\n  @property(EditBox)\n  passwordInput: EditBox = null;\n\n  @property(Label)\n  messageLabel: Label = null;\n\n  async onLoginButtonClick() {\n    const username = this.usernameInput.string;\n    const password = this.passwordInput.string;\n\n    if (!username || !password) {\n      this.messageLabel.string = 'Please enterAccountandPassword';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      await auth.signIn({\n        username, // Can be username, phone or email\n        password,\n      });\n      this.messageLabel.string = 'Login successful！';\n      console.log('Login successful');\n    } catch (error) {\n      this.messageLabel.string = `Login failed: ${error.message}`;\n      console.error('Login failed：', error);\n    }\n  }\n}\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login"
              },
              {
                "markdown": "Use **SMS Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMS Verification Login**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: `+86 ${phone}` });\nconst verificationInfo = res;\n\n// Login\nawait auth.signInWithSms({\n  verificationInfo: verificationInfo,\n  verificationCode: code,\n  phoneNum: `+86 ${phone}`\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('SmsLogin')\nexport class SmsLogin extends Component {\n  @property(EditBox)\n  phoneInput: EditBox = null;\n\n  @property(EditBox)\n  codeInput: EditBox = null;\n\n  @property(Label)\n  messageLabel: Label = null;\n\n  private verificationInfo: any = null;\n\n  // Send Code\n  async onSendCodeButtonClick() {\n    const phone = this.phoneInput.string;\n    if (!phone) {\n      this.messageLabel.string = 'Please enterPhone number';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n      this.verificationInfo = res;\n      this.messageLabel.string = 'Verification code sent！';\n    } catch (error) {\n      this.messageLabel.string = `Send failed: ${error.message}`;\n    }\n  }\n\n  // Login\n  async onLoginButtonClick() {\n    const phone = this.phoneInput.string;\n    const code = this.codeInput.string;\n\n    if (!this.verificationInfo || !code) {\n      this.messageLabel.string = 'please firstSend Code';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInWithSms({\n        verificationInfo: this.verificationInfo,\n        verificationCode: code,\n        phoneNum: `+86 ${phone}`\n      });\n      this.messageLabel.string = 'Login successful！';\n      console.log('Login successful');\n    } catch (error) {\n      this.messageLabel.string = `Login failed: ${error.message}`;\n      console.error('Login failed：', error);\n    }\n  }\n}\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login"
              },
              {
                "markdown": "Use **Email Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\nconst verificationInfo = res;\n\n// Login\nawait auth.signInWithEmail({\n  verificationInfo: verificationInfo,\n  verificationCode: code,\n  email\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('EmailLogin')\nexport class EmailLogin extends Component {\n  @property(EditBox)\n  emailInput: EditBox = null;\n\n  @property(EditBox)\n  codeInput: EditBox = null;\n\n  @property(Label)\n  messageLabel: Label = null;\n\n  private verificationInfo: any = null;\n\n  // Send Code\n  async onSendCodeButtonClick() {\n    const email = this.emailInput.string;\n    if (!email) {\n      this.messageLabel.string = 'Please enterEmail';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ email });\n      this.verificationInfo = res;\n      this.messageLabel.string = 'Verification code sent！';\n    } catch (error) {\n      this.messageLabel.string = `Send failed: ${error.message}`;\n    }\n  }\n\n  // Login\n  async onLoginButtonClick() {\n    const email = this.emailInput.string;\n    const code = this.codeInput.string;\n\n    if (!this.verificationInfo || !code) {\n      this.messageLabel.string = 'please firstSend Code';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInWithEmail({\n        verificationInfo: this.verificationInfo,\n        verificationCode: code,\n        email\n      });\n      this.messageLabel.string = 'Login successful！';\n      console.log('Login successful');\n    } catch (error) {\n      this.messageLabel.string = `Login failed: ${error.message}`;\n      console.error('Login failed：', error);\n    }\n  }\n}\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst auth = cloudbase.auth();\nawait auth.signInAnonymously();\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('AnonymousLogin')\nexport class AnonymousLogin extends Component {\n  @property(Label)\n  messageLabel: Label = null;\n\n  async onLoginButtonClick() {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInAnonymously();\n      this.messageLabel.string = 'anonymousLogin successful！';\n      console.log('anonymousLogin successful');\n    } catch (error) {\n      this.messageLabel.string = `Login failed: ${error.message}`;\n      console.error('Login failed：', error);\n    }\n  }\n}\n```",
                "index": 6,
                "title": "anonymousLogin"
              }
            ]
          }
        ]
      }
    ],
    "_id": "69f0bd6369a9287100433f902c321303",
    "_openid": "anon",
    "createdAt": 1769767022175,
    "updatedAt": 1775130882212
  },
  {
    "category": "Framework Integration,Mobile Frameworks,Android Kotlin",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 11,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/http-api/basic/overview",
    "content": [
      {
        "markdown": "Use **HTTP Request** in **Android Kotlin** Callvarious CloudBase capabilities\n\nin `build.gradle` (Module) Add dependencies：\n\n```gradle\ndependencies {\n    implementation 'com.squareup.okhttp3:okhttp:4.12.0'\n    implementation 'com.google.code.gson:gson:2.10.1'\n    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'\n}\n```",
        "index": 1,
        "title": "Install Dependencies",
        "content": []
      },
      {
        "markdown": "Add the following code to your **Android Kotlin** project",
        "index": 2,
        "title": "Initialize Configuration",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```kotlin\npackage com.example.cloudbase\n\nimport com.google.gson.Gson\nimport com.google.gson.reflect.TypeToken\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.withContext\nimport okhttp3.MediaType.Companion.toMediaType\nimport okhttp3.OkHttpClient\nimport okhttp3.Request\nimport okhttp3.RequestBody.Companion.toRequestBody\nimport java.util.concurrent.TimeUnit\n\nclass CloudBaseClient(\n    private val envId: String,\n    private var accessToken: String\n) {\n    private val baseUrl = \"https://$envId.api.tcloudbasegateway.com\"\n    private val gson = Gson()\n\n    private val client = OkHttpClient.Builder()\n        .connectTimeout(30, TimeUnit.SECONDS)\n        .readTimeout(30, TimeUnit.SECONDS)\n        .writeTimeout(30, TimeUnit.SECONDS)\n        .build()\n\n    /**\n     * UpdateAccess token\n     *\n     * @param newToken new access token\n     */\n    fun updateAccessToken(newToken: String) {\n        this.accessToken = newToken\n        println(\"Access token has beenUpdate\")\n    }\n\n    /**\n     * Unified HTTP request method\n     *\n     * @param method Request method (GET, POST, PUT, PATCH, DELETE)\n     * @param path APIPath (such as /v1/rdb/rest/table_name)\n     * @param body Request body data\n     * @param customHeaders Customheaders\n     *\n     * @return ResponseDataornull\n     */\n    suspend fun <T> request(\n        method: String,\n        path: String,\n        body: Any? = null,\n        customHeaders: Map<String, String> = emptyMap(),\n        typeToken: TypeToken<T>? = null\n    ): T? = withContext(Dispatchers.IO) {\n        val url = \"$baseUrl$path\"\n\n        val requestBuilder = Request.Builder()\n            .url(url)\n            .header(\"Content-Type\", \"application/json\")\n            .header(\"Accept\", \"application/json\")\n            .header(\"Authorization\", \"Bearer $accessToken\")\n\n        // AddCustomheaders\n        customHeaders.forEach { (key, value) ->\n            requestBuilder.header(key, value)\n        }\n\n        // SetRequest methodandbody\n        when (method.uppercase()) {\n            \"GET\" -> requestBuilder.get()\n            \"POST\", \"PUT\", \"PATCH\", \"DELETE\" -> {\n                val jsonBody = if (body != null) {\n                    gson.toJson(body).toRequestBody(\"application/json\".toMediaType())\n                } else {\n                    \"{}\".toRequestBody(\"application/json\".toMediaType())\n                }\n                when (method.uppercase()) {\n                    \"POST\" -> requestBuilder.post(jsonBody)\n                    \"PUT\" -> requestBuilder.put(jsonBody)\n                    \"PATCH\" -> requestBuilder.patch(jsonBody)\n                    \"DELETE\" -> requestBuilder.delete(jsonBody)\n                }\n            }\n        }\n\n        try {\n            val response = client.newCall(requestBuilder.build()).execute()\n\n            if (response.isSuccessful) {\n                val responseBody = response.body?.string()\n\n                // IfResponseis empty，Returntruerepresentssuccessful\n                if (responseBody.isNullOrEmpty()) {\n                    @Suppress(\"UNCHECKED_CAST\")\n                    return@withContext true as? T\n                }\n\n                return@withContext if (typeToken != null) {\n                    gson.fromJson(responseBody, typeToken.type)\n                } else {\n                    @Suppress(\"UNCHECKED_CAST\")\n                    gson.fromJson(responseBody, Any::class.java) as? T\n                }\n            } else {\n                println(\"Requestfailed: ${response.code} ${response.body?.string()}\")\n                return@withContext null\n            }\n        } catch (e: Exception) {\n            println(\"Requestfailed: ${e.message}\")\n            e.printStackTrace()\n            return@withContext null\n        }\n    }\n}\n\n// ConfigurationfileorInitializewhenCreateinstance\n// val cloudbase = CloudBaseClient(\n//     envId = \"your-env-id\",\n//     accessToken = \"your-access-token\"\n// )\n```",
            "index": 1,
            "title": "CloudBaseClient.kt"
          },
          {
            "markdown": "in `local.properties` orConfigurationfileAdd：\n\n> 💡Note: For user permissions, refer to the \"Authentication\" module to obtain access_token\n\n```properties\n# Environment ID\nCLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Anonymous access token\nCLOUDBASE_ACCESS_TOKEN={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": "Configurationfile"
          }
        ]
      },
      {
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```kotlin\nimport com.google.gson.reflect.TypeToken\n\nsuspend fun getMysqlData(cloudbase: CloudBaseClient, tableName: String): List<Map<String, Any>>? {\n    // Query MySQL database data\n    val data = cloudbase.request<List<Map<String, Any>>>(\n        method = \"GET\",\n        path = \"/v1/rdb/rest/$tableName?limit=10\",\n        typeToken = object : TypeToken<List<Map<String, Any>>>() {}\n    )\n\n    if (data != null) {\n        println(\"Querysuccessful: $data\")\n    }\n    return data ?: emptyList()\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = getMysqlData(cloudbase, \"{%TABLE_NAME%}\")\n//     println(result)\n// }\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun addMysqlData(cloudbase: CloudBaseClient, tableName: String, data: Map<String, Any>): Map<String, Any>? {\n    // Add MySQL database data\n    val result = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/v1/rdb/rest/$tableName\",\n        body = data,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (result != null) {\n        println(\"Insert successful: $result\")\n    }\n    return result\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = addMysqlData(cloudbase, \"{%TABLE_NAME%}\", mapOf(\"title\" to \"Example Title\"))\n//     println(result)\n// }\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun updateMysqlData(cloudbase: CloudBaseClient, tableName: String, dataId: String, data: Map<String, Any>): Any? {\n    // Update MySQL database data\n    val result = cloudbase.request<Any>(\n        method = \"PATCH\",\n        path = \"/v1/rdb/rest/$tableName?id=eq.$dataId\",\n        body = data\n    )\n\n    if (result != null) {\n        println(\"Update successful: $result\")\n    }\n    return result\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = updateMysqlData(cloudbase, \"{%TABLE_NAME%}\", \"<data id>\", mapOf(\"title\" to \"New Title\"))\n//     println(result)\n// }\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun deleteMysqlData(cloudbase: CloudBaseClient, tableName: String, dataId: String): Boolean {\n    // Delete MySQL database data\n    val result = cloudbase.request<Any>(\n        method = \"DELETE\",\n        path = \"/v1/rdb/rest/$tableName?id=eq.$dataId\"\n    )\n\n    if (result != null) {\n        println(\"Delete successful\")\n        return true\n    }\n    return false\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = deleteMysqlData(cloudbase, \"{%TABLE_NAME%}\", \"<data id>\")\n//     println(result)\n// }\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```kotlin\nimport com.google.gson.reflect.TypeToken\n\nsuspend fun getModelData(cloudbase: CloudBaseClient, modelName: String, envType: String = \"prod\"): List<Map<String, Any>> {\n    // QueryData ModelData\n    val payload = mapOf(\n        \"pageSize\" to 10,\n        \"pageNumber\" to 1,\n        \"getCount\" to true\n    )\n\n    val result = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/v1/model/$envType/$modelName/list\",\n        body = payload,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (result != null) {\n        val records = (result[\"data\"] as? Map<*, *>)?.get(\"records\") as? List<Map<String, Any>> ?: emptyList()\n        println(\"Querysuccessful: $records\")\n        return records\n    }\n    return emptyList()\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val records = getModelData(cloudbase, \"{%TABLE_NAME%}\")\n//     println(records)\n// }\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun addModelData(cloudbase: CloudBaseClient, modelName: String, data: Map<String, Any>, envType: String = \"prod\"): Map<String, Any>? {\n    // AddData ModelData\n    val result = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/v1/model/$envType/$modelName/create\",\n        body = mapOf(\"data\" to data),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (result != null) {\n        val docId = (result[\"data\"] as? Map<*, *>)?.get(\"id\")\n        println(\"Insert successful! id: $docId\")\n    }\n    return result\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = addModelData(cloudbase, \"{%TABLE_NAME%}\", mapOf(\"title\" to \"Example Title\"))\n//     println(result)\n// }\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun updateModelData(cloudbase: CloudBaseClient, modelName: String, dataId: String, data: Map<String, Any>, envType: String = \"prod\"): Boolean {\n    // UpdateData ModelData\n    val payload = mapOf(\n        \"data\" to data,\n        \"filter\" to mapOf(\n            \"where\" to mapOf(\n                \"_id\" to mapOf(\"\\$eq\" to dataId)\n            )\n        )\n    )\n\n    val result = cloudbase.request<Any>(\n        method = \"PUT\",\n        path = \"/v1/model/$envType/$modelName/update\",\n        body = payload\n    )\n\n    if (result != null) {\n        println(\"Update successful!\")\n        return true\n    }\n    return false\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = updateModelData(cloudbase, \"{%TABLE_NAME%}\", \"<data id>\", mapOf(\"title\" to \"New Title\"))\n//     println(result)\n// }\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun deleteModelData(cloudbase: CloudBaseClient, modelName: String, dataId: String, envType: String = \"prod\"): Boolean {\n    // DeleteData ModelData\n    val payload = mapOf(\n        \"filter\" to mapOf(\n            \"where\" to mapOf(\n                \"_id\" to mapOf(\"\\$eq\" to dataId)\n            )\n        )\n    )\n\n    val result = cloudbase.request<Any>(\n        method = \"POST\",\n        path = \"/v1/model/$envType/$modelName/delete\",\n        body = payload\n    )\n\n    if (result != null) {\n        println(\"Delete successful!\")\n        return true\n    }\n    return false\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = deleteModelData(cloudbase, \"{%TABLE_NAME%}\", \"<data id>\")\n//     println(result)\n// }\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```kotlin\nsuspend fun callFunction(cloudbase: CloudBaseClient, functionName: String, data: Map<String, Any>? = null): Map<String, Any>? {\n    // CallCloud Function\n    val result = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/v1/functions/$functionName\",\n        body = data ?: emptyMap<String, Any>(),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (result != null) {\n        println(\"Cloud function call result: $result\")\n    }\n    return result\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = callFunction(cloudbase, \"{%FUNCTION_NAME%}\")\n//     println(result)\n// }\n```",
            "index": 3,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```kotlin\nsuspend fun callContainer(cloudbase: CloudBaseClient, serviceName: String, path: String = \"\", method: String = \"GET\", data: Map<String, Any>? = null): Any? {\n    // CallCloud Runservice\n    val fullPath = \"/v1/cloudrun/$serviceName/$path\".trimEnd('/')\n    val result = cloudbase.request<Any>(\n        method = method.uppercase(),\n        path = fullPath,\n        body = data\n    )\n\n    if (result != null) {\n        println(\"Cloud RunCallResult: $result\")\n    }\n    return result\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = callContainer(cloudbase, \"{%SERVICE_NAME%}\")\n//     println(result)\n// }\n```",
            "index": 4,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```kotlin\nimport okhttp3.OkHttpClient\nimport okhttp3.Request\nimport okhttp3.RequestBody.Companion.toRequestBody\nimport java.io.File\n\nsuspend fun uploadFile(cloudbase: CloudBaseClient, filePath: String, objectId: String? = null): Map<String, String>? = withContext(Dispatchers.IO) {\n    // Upload FiletoCloud Storage\n    val file = File(filePath)\n\n    if (!file.exists()) {\n        println(\"filedoes not exist: $filePath\")\n        return@withContext null\n    }\n\n    val finalObjectId = objectId ?: \"uploads/${System.currentTimeMillis()}-${file.name}\"\n\n    // 1. Get upload info\n    val uploadInfo = cloudbase.request<List<Map<String, Any>>>(\n        method = \"POST\",\n        path = \"/v1/storages/get-objects-upload-info\",\n        body = listOf(mapOf(\"objectId\" to finalObjectId)),\n        typeToken = object : TypeToken<List<Map<String, Any>>>() {}\n    )\n\n    if (uploadInfo.isNullOrEmpty()) {\n        return@withContext null\n    }\n\n    val info = uploadInfo[0]\n    val uploadUrl = info[\"uploadUrl\"] as String\n\n    try {\n        // 2. Upload File\n        val fileData = file.readBytes()\n        val uploadHeaders = mapOf(\n            \"Authorization\" to (info[\"authorization\"] as String),\n            \"X-Cos-Security-Token\" to (info[\"token\"] as String),\n            \"X-Cos-Meta-Fileid\" to (info[\"cloudObjectMeta\"] as String)\n        )\n\n        val requestBuilder = Request.Builder()\n            .url(uploadUrl)\n            .put(fileData.toRequestBody())\n\n        uploadHeaders.forEach { (key, value) ->\n            requestBuilder.header(key, value)\n        }\n\n        val client = OkHttpClient()\n        val uploadResponse = client.newCall(requestBuilder.build()).execute()\n\n        if (uploadResponse.isSuccessful) {\n            val result = mapOf(\n                \"cloudObjectId\" to (info[\"cloudObjectId\"] as String),\n                \"downloadUrl\" to (info[\"downloadUrl\"] as String),\n                \"objectId\" to finalObjectId\n            )\n\n            println(\"fileUpload successful:\")\n            println(\"- Object ID: ${result[\"objectId\"]}\")\n            println(\"- DownloadURL: ${result[\"downloadUrl\"]}\")\n\n            return@withContext result\n        }\n\n        println(\"fileUploadfailed: ${uploadResponse.code}\")\n        return@withContext null\n    } catch (e: Exception) {\n        println(\"fileUploadfailed: ${e.message}\")\n        e.printStackTrace()\n        return@withContext null\n    }\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = uploadFile(cloudbase, \"/path/to/example.jpg\")\n//     println(result)\n// }\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun getFileUrl(cloudbase: CloudBaseClient, cloudObjectId: String): String? {\n    // GetCloud Storagefiletemporary accessURL\n    val result = cloudbase.request<List<Map<String, Any>>>(\n        method = \"POST\",\n        path = \"/v1/storages/get-objects-download-info\",\n        body = listOf(mapOf(\"cloudObjectId\" to cloudObjectId)),\n        typeToken = object : TypeToken<List<Map<String, Any>>>() {}\n    )\n\n    if (!result.isNullOrEmpty()) {\n        val downloadUrl = result[0][\"downloadUrl\"] as? String\n        println(\"fileURL: $downloadUrl\")\n        return downloadUrl\n    }\n    return null\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val fileUrl = getFileUrl(cloudbase, \"cloud://xxx.png\")\n//     println(fileUrl)\n// }\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```kotlin\nimport okhttp3.OkHttpClient\nimport okhttp3.Request\nimport java.io.File\n\nsuspend fun downloadFile(cloudbase: CloudBaseClient, cloudObjectId: String, savePath: String = \"./\"): Boolean = withContext(Dispatchers.IO) {\n    // DownloadCloud Storagefiletolocal\n    // 1. GetDownloadURL\n    val result = cloudbase.request<List<Map<String, Any>>>(\n        method = \"POST\",\n        path = \"/v1/storages/get-objects-download-info\",\n        body = listOf(mapOf(\"cloudObjectId\" to cloudObjectId)),\n        typeToken = object : TypeToken<List<Map<String, Any>>>() {}\n    )\n\n    if (result.isNullOrEmpty()) {\n        return@withContext false\n    }\n\n    val downloadUrl = result[0][\"downloadUrl\"] as String\n\n    try {\n        // 2. fromURLExtractfilename\n        val filename = downloadUrl.split(\"/\").last().split(\"?\").first()\n\n        // 3. Determine full path\n        val fullPath = if (File(savePath).isDirectory || savePath.endsWith(\"/\")) {\n            \"$savePath/$filename\"\n        } else {\n            savePath\n        }\n\n        // 4. Download File\n        val client = OkHttpClient()\n        val request = Request.Builder().url(downloadUrl).build()\n        val fileResponse = client.newCall(request).execute()\n\n        if (fileResponse.isSuccessful) {\n            // 5. Save to local\n            val file = File(fullPath)\n            file.parentFile?.mkdirs()\n            file.writeBytes(fileResponse.body!!.bytes())\n\n            println(\"Downloadsuccessful! filesaved to: $fullPath\")\n            return@withContext true\n        }\n\n        println(\"Downloadfailed: ${fileResponse.code}\")\n        return@withContext false\n    } catch (e: Exception) {\n        println(\"Downloadfailed: ${e.message}\")\n        e.printStackTrace()\n        return@withContext false\n    }\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     // Downloadto specified directory\n//     downloadFile(cloudbase, \"cloud://xxx.png\", \"/sdcard/Download/\")\n//\n//     // Downloadand rename\n//     downloadFile(cloudbase, \"cloud://xxx.png\", \"/sdcard/Download/my-image.png\")\n// }\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun deleteFile(cloudbase: CloudBaseClient, cloudObjectIds: Any): Boolean {\n    // DeleteCloud Storagefile\n    val ids = when (cloudObjectIds) {\n        is String -> listOf(cloudObjectIds)\n        is List<*> -> cloudObjectIds.filterIsInstance<String>()\n        else -> {\n            println(\"Parameter type error\")\n            return false\n        }\n    }\n\n    val data = ids.map { mapOf(\"cloudObjectId\" to it) }\n    val result = cloudbase.request<Any>(\n        method = \"POST\",\n        path = \"/v1/storages/delete-objects\",\n        body = data\n    )\n\n    if (result != null) {\n        println(\"Delete successful!\")\n        return true\n    }\n    return false\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = deleteFile(cloudbase, \"cloud://xxx.png\")\n//     println(result)\n// }\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```kotlin\nimport okhttp3.OkHttpClient\nimport okhttp3.Request\nimport okhttp3.RequestBody.Companion.toRequestBody\nimport okhttp3.MediaType.Companion.toMediaType\nimport com.google.gson.Gson\n\nsuspend fun streamText(cloudbase: CloudBaseClient, model: String, subModel: String, messages: List<Map<String, String>>): String? = withContext(Dispatchers.IO) {\n    // streamingtextthisGenerate\n    val payload = mapOf(\n        \"model\" to subModel,\n        \"messages\" to messages,\n        \"stream\" to true\n    )\n\n    val url = \"${cloudbase.baseUrl}/v1/ai/$model/chat/completions\"\n    val gson = Gson()\n\n    val requestBody = gson.toJson(payload).toRequestBody(\"application/json\".toMediaType())\n\n    val request = Request.Builder()\n        .url(url)\n        .header(\"Content-Type\", \"application/json\")\n        .header(\"Accept\", \"text/event-stream\")\n        .header(\"Authorization\", \"Bearer ${cloudbase.accessToken}\")\n        .post(requestBody)\n        .build()\n\n    try {\n        val client = OkHttpClient()\n        val response = client.newCall(request).execute()\n\n        if (response.isSuccessful) {\n            println(\"AI Streaming response:\")\n            var fullContent = \"\"\n\n            response.body?.source()?.use { source ->\n                while (!source.exhausted()) {\n                    val line = source.readUtf8Line() ?: continue\n\n                    if (line.startsWith(\"data: \")) {\n                        val dataStr = line.substring(6)\n                        if (dataStr.trim() != \"[DONE]\") {\n                            try {\n                                val chunkData = gson.fromJson(dataStr, Map::class.java)\n                                val choices = chunkData[\"choices\"] as? List<*>\n                                val delta = (choices?.get(0) as? Map<*, *>)?.get(\"delta\") as? Map<*, *>\n                                val content = delta?.get(\"content\") as? String ?: \"\"\n\n                                if (content.isNotEmpty()) {\n                                    print(content)\n                                    fullContent += content\n                                }\n                            } catch (e: Exception) {\n                                // Ignore JSON parsing error\n                            }\n                        }\n                    }\n                }\n            }\n\n            println()\n            return@withContext fullContent\n        } else {\n            println(\"AI Call failed: ${response.code}\")\n            return@withContext null\n        }\n    } catch (e: Exception) {\n        println(\"AI Call failed: ${e.message}\")\n        e.printStackTrace()\n        return@withContext null\n    }\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val response = streamText(\n//         cloudbase,\n//         \"{%AI_MODEL_NAME%}\",\n//         \"{%AI_SUB_MODEL_NAME%}\",\n//         listOf(\n//             mapOf(\"role\" to \"system\", \"content\" to \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create\"),\n//             mapOf(\"role\" to \"user\", \"content\" to \"Spring\")\n//         )\n//     )\n//     println(\"\\nComplete response: $response\")\n// }\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```kotlin\nimport com.google.gson.Gson\n\nsuspend fun generateImage(cloudbase: CloudBaseClient, prompt: String): Map<String, Any>? = withContext(Dispatchers.IO) {\n    /// Call image generation cloud function\n    val result = cloudbase.request(\n        \"POST\",\n        \"/v1/functions/<YOUR_FUNCTION_NAME>/invoke\",\n        mapOf(\"prompt\" to prompt)\n    )\n\n    if (result != null) {\n        val success = result[\"success\"] as? Boolean ?: false\n        \n        if (success) {\n            // Generation successful\n            println(\"Generation successful!\")\n            println(\"Image URL: ${result[\"imageUrl\"]}\")\n            println(\"Optimized prompt: ${result[\"revised_prompt\"]}\")\n\n            // Use image\n            // Note: Image URL is valid for 24 hours, please save or transfer promptly\n            return@withContext result\n        } else {\n            // Generation failed\n            println(\"Generation failed: ${result[\"code\"]} ${result[\"message\"]}\")\n            return@withContext null\n        }\n    }\n    return@withContext null\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = generateImage(cloudbase, \"A cute cat playing in the sunshine\")\n//     if (result != null) {\n//         println(\"Image URL: ${result[\"imageUrl\"]}\")\n//     }\n// }\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```kotlin\n/**\n * Android Kotlin Call Agent Example (AG-UI Protocol)\n * Protocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n */\nimport okhttp3.OkHttpClient\nimport okhttp3.Request\nimport okhttp3.RequestBody.Companion.toRequestBody\nimport okhttp3.MediaType.Companion.toMediaType\nimport com.google.gson.Gson\n\nsuspend fun chatWithAgentStream(cloudbase: CloudBaseClient, botId: String, userMessage: String): String? = withContext(Dispatchers.IO) {\n    // Build message list (AG-UI protocol format)\n    val messages = listOf(\n        mapOf(\n            \"id\" to \"msg_001\",\n            \"role\" to \"user\",\n            \"content\" to userMessage\n        )\n    )\n\n    // AG-UI Protocol request parameters\n    val payload = mapOf(\n        \"messages\" to messages,                                    // Required: Message list\n        \"threadId\" to \"550e8400-e29b-41d4-a716-446655440000\",     // Optional: Session ID for multi-turn conversation\n        \"runId\" to \"run_001\",                                      // Optional: Run ID for execution tracking\n        \"tools\" to emptyList<Any>(),                               // Optional: Frontend tool definitions\n        \"context\" to emptyList<Any>(),                             // Optional: Context information\n        \"forwardedProps\" to emptyMap<String, Any>()                // Optional: Pass-through parameters\n    )\n\n    val url = \"${cloudbase.baseUrl}/v1/aibot/bots/$botId/send-message\"\n    val gson = Gson()\n\n    val requestBody = gson.toJson(payload).toRequestBody(\"application/json\".toMediaType())\n\n    val request = Request.Builder()\n        .url(url)\n        .header(\"Content-Type\", \"application/json\")\n        .header(\"Accept\", \"text/event-stream\")\n        .header(\"Authorization\", \"Bearer ${cloudbase.accessToken}\")\n        .post(requestBody)\n        .build()\n\n    try {\n        val client = OkHttpClient()\n        val response = client.newCall(request).execute()\n\n        if (response.isSuccessful) {\n            println(\"AI Streaming response:\")\n            var fullContent = \"\"\n            var buffer = \"\"\n\n            response.body?.source()?.use { source ->\n                while (!source.exhausted()) {\n                    buffer += source.readUtf8Line() ?: \"\"\n                    buffer += \"\\n\"\n\n                    while (buffer.contains(\"\\n\")) {\n                        val newlineIndex = buffer.indexOf(\"\\n\")\n                        val line = buffer.substring(0, newlineIndex).trim()\n                        buffer = buffer.substring(newlineIndex + 1)\n\n                        if (line.startsWith(\"data: \")) {\n                            val dataStr = line.substring(6).trim()\n                            if (dataStr.isNotEmpty() && dataStr != \"[DONE]\") {\n                                try {\n                                    val chunkData = gson.fromJson(dataStr, Map::class.java)\n                                    val content = chunkData[\"content\"] as? String\n                                        ?: ((chunkData[\"choices\"] as? List<*>)?.get(0) as? Map<*, *>)?.let {\n                                            (it[\"delta\"] as? Map<*, *>)?.get(\"content\") as? String\n                                                ?: (it[\"message\"] as? Map<*, *>)?.get(\"content\") as? String\n                                        } ?: \"\"\n\n                                    if (content.isNotEmpty()) {\n                                        print(content)\n                                        fullContent += content\n                                    }\n                                } catch (e: Exception) {\n                                    // Ignore JSON parsing error\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n\n            println()\n            return@withContext fullContent\n        } else {\n            println(\"AI Call failed: ${response.code}\")\n            return@withContext null\n        }\n    } catch (e: Exception) {\n        println(\"AI Call failed: ${e.message}\")\n        e.printStackTrace()\n        return@withContext null\n    }\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val response = chatWithAgentStream(cloudbase, \"{%AGENT_ID%}\", \"Who are you\")\n//     println(\"\\nComplete response: $response\")\n// }\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```kotlin\nimport okhttp3.OkHttpClient\nimport okhttp3.Request\nimport okhttp3.RequestBody.Companion.toRequestBody\nimport okhttp3.MediaType.Companion.toMediaType\nimport com.google.gson.Gson\n\nsuspend fun chatWithAgentStream(cloudbase: CloudBaseClient, botId: String, msg: String, history: List<Map<String, String>>? = null): String? = withContext(Dispatchers.IO) {\n    // streamingCallAgent\n    val payload = mapOf(\n        \"history\" to (history ?: emptyList<Map<String, String>>()),\n        \"msg\" to msg\n    )\n\n    val url = \"${cloudbase.baseUrl}/v1/aibot/bots/$botId/send-message\"\n    val gson = Gson()\n\n    val requestBody = gson.toJson(payload).toRequestBody(\"application/json\".toMediaType())\n\n    val request = Request.Builder()\n        .url(url)\n        .header(\"Content-Type\", \"application/json\")\n        .header(\"Accept\", \"text/event-stream\")\n        .header(\"Authorization\", \"Bearer ${cloudbase.accessToken}\")\n        .post(requestBody)\n        .build()\n\n    try {\n        val client = OkHttpClient()\n        val response = client.newCall(request).execute()\n\n        if (response.isSuccessful) {\n            println(\"AI Streaming response:\")\n            var fullContent = \"\"\n            var buffer = \"\"\n\n            response.body?.source()?.use { source ->\n                while (!source.exhausted()) {\n                    buffer += source.readUtf8Line() ?: \"\"\n                    buffer += \"\\n\"\n\n                    while (buffer.contains(\"\\n\")) {\n                        val newlineIndex = buffer.indexOf(\"\\n\")\n                        val line = buffer.substring(0, newlineIndex).trim()\n                        buffer = buffer.substring(newlineIndex + 1)\n\n                        if (line.startsWith(\"data: \")) {\n                            val dataStr = line.substring(6).trim()\n                            if (dataStr.isNotEmpty() && dataStr != \"[DONE]\") {\n                                try {\n                                    val chunkData = gson.fromJson(dataStr, Map::class.java)\n                                    val content = chunkData[\"content\"] as? String\n                                        ?: ((chunkData[\"choices\"] as? List<*>)?.get(0) as? Map<*, *>)?.let {\n                                            (it[\"delta\"] as? Map<*, *>)?.get(\"content\") as? String\n                                                ?: (it[\"message\"] as? Map<*, *>)?.get(\"content\") as? String\n                                        } ?: \"\"\n\n                                    if (content.isNotEmpty()) {\n                                        print(content)\n                                        fullContent += content\n                                    }\n                                } catch (e: Exception) {\n                                    // Ignore JSON parsing error\n                                }\n                            }\n                        }\n                    }\n                }\n            }\n\n            println()\n            return@withContext fullContent\n        } else {\n            println(\"AI Call failed: ${response.code}\")\n            return@withContext null\n        }\n    } catch (e: Exception) {\n        println(\"AI Call failed: ${e.message}\")\n        e.printStackTrace()\n        return@withContext null\n    }\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val response = chatWithAgentStream(cloudbase, \"{%AGENT_ID%}\", \"Who are you\")\n//     println(\"\\nComplete response: $response\")\n// }\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 8,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```kotlin\nsuspend fun signUpWithPhoneCode(cloudbase: CloudBaseClient, phoneNumber: String, verificationCode: String, username: String? = null, password: String? = null, captchaToken: String? = null): Map<String, Any>? {\n    // Step1: SendSMSVerification code\n    val sendBody = mutableMapOf<String, Any>(\n        \"phone_number\" to if (phoneNumber.startsWith(\"+86\")) phoneNumber else \"+86$phoneNumber\",\n        \"target\" to \"NON_USER\"  // \"NON_USER\" - Accountdoes not existthenSend; \"ANY\" - No restriction\n    )\n\n    val sendHeaders = captchaToken?.let { mapOf(\"x-captcha-token\" to it) } ?: emptyMap()\n\n    val sendResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification\",\n        body = sendBody,\n        customHeaders = sendHeaders,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (sendResult == null) {\n        println(\"Send Codefailed\")\n        return null\n    }\n\n    val verificationId = sendResult[\"verification_id\"] as? String ?: return null\n    println(\"Verification codeSendsuccessful! ID: $verificationId\")\n\n    // Step2: Verify the code\n    val verifyResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification/verify\",\n        body = mapOf(\n            \"verification_id\" to verificationId,\n            \"verification_code\" to verificationCode\n        ),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (verifyResult == null) {\n        println(\"Verification codeError\")\n        return null\n    }\n\n    val verificationToken = verifyResult[\"verification_token\"] as? String ?: return null\n    println(\"Verifysuccessful!\")\n\n    // Step3: UseVerifytokenRegister\n    val signUpBody = mutableMapOf<String, Any>(\n        \"phone_number\" to if (phoneNumber.startsWith(\"+86\")) phoneNumber else \"+86$phoneNumber\",\n        \"verification_token\" to verificationToken\n    )\n\n    // Optional：AddUsernameandPassword\n    username?.let { signUpBody[\"username\"] = it }\n    password?.let { signUpBody[\"password\"] = it }\n\n    val signUpResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/signup\",\n        body = signUpBody,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (signUpResult != null) {\n        val accessToken = signUpResult[\"access_token\"] as? String\n        val userId = signUpResult[\"sub\"] as? String\n\n        println(\"Registration successful! User ID: $userId\")\n        println(\"Access token: ${accessToken?.take(20)}...\")\n\n        // UpdateAccess token\n        accessToken?.let { cloudbase.updateAccessToken(it) }\n        return signUpResult\n    }\n\n    println(\"Registration failed\")\n    return null\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = signUpWithPhoneCode(cloudbase, \"13800138000\", \"123456\", \"myusername\", \"mypassword\")\n//     if (result != null) {\n//         println(\"Phone numberRegistration successful\")\n//     }\n// }\n```",
                "index": 1,
                "title": "SMS Code Registration",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun signUpWithEmailCode(cloudbase: CloudBaseClient, email: String, verificationCode: String, username: String? = null, password: String? = null, captchaToken: String? = null): Map<String, Any>? {\n    // Step1: SendEmailVerification code\n    val sendBody = mutableMapOf<String, Any>(\n        \"email\" to email,\n        \"target\" to \"NON_USER\"  // \"NON_USER\" - Accountdoes not existthenSend; \"ANY\" - No restriction\n    )\n\n    val sendHeaders = captchaToken?.let { mapOf(\"x-captcha-token\" to it) } ?: emptyMap()\n\n    val sendResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification\",\n        body = sendBody,\n        customHeaders = sendHeaders,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (sendResult == null) {\n        println(\"Send Codefailed\")\n        return null\n    }\n\n    val verificationId = sendResult[\"verification_id\"] as? String ?: return null\n    println(\"Verification codeSendsuccessful! ID: $verificationId\")\n\n    // Step2: Verify the code\n    val verifyResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification/verify\",\n        body = mapOf(\n            \"verification_id\" to verificationId,\n            \"verification_code\" to verificationCode\n        ),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (verifyResult == null) {\n        println(\"Verification codeError\")\n        return null\n    }\n\n    val verificationToken = verifyResult[\"verification_token\"] as? String ?: return null\n    println(\"Verifysuccessful!\")\n\n    // Step3: UseVerifytokenRegister\n    val signUpBody = mutableMapOf<String, Any>(\n        \"email\" to email,\n        \"verification_token\" to verificationToken\n    )\n\n    // Optional：AddUsernameandPassword\n    username?.let { signUpBody[\"username\"] = it }\n    password?.let { signUpBody[\"password\"] = it }\n\n    val signUpResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/signup\",\n        body = signUpBody,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (signUpResult != null) {\n        val accessToken = signUpResult[\"access_token\"] as? String\n        val userId = signUpResult[\"sub\"] as? String\n\n        println(\"Registration successful! User ID: $userId\")\n        println(\"Access token: ${accessToken?.take(20)}...\")\n\n        // UpdateAccess token\n        accessToken?.let { cloudbase.updateAccessToken(it) }\n        return signUpResult\n    }\n\n    println(\"Registration failed\")\n    return null\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = signUpWithEmailCode(cloudbase, \"user@example.com\", \"123456\", \"myusername\", \"mypassword\")\n//     if (result != null) {\n//         println(\"EmailRegistration successful\")\n//     }\n// }\n```",
                "index": 2,
                "title": "Email Code Registration",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun signIn(cloudbase: CloudBaseClient, username: String, password: String): Map<String, Any>? {\n    // Username Password Login\n    val result = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/signin\",\n        body = mapOf(\"username\" to username, \"password\" to password),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (result != null) {\n        val accessToken = result[\"access_token\"] as? String\n        val refreshToken = result[\"refresh_token\"] as? String\n        val userId = result[\"sub\"] as? String\n\n        println(\"Login successful! User ID: $userId\")\n        println(\"Access token: ${accessToken?.take(20)}...\")\n\n        // UpdateAccess token\n        accessToken?.let { cloudbase.updateAccessToken(it) }\n        return result\n    }\n    return null\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val result = signIn(cloudbase, \"your_username\", \"your_password\")\n//     println(result)\n// }\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun loginWithPhoneCode(cloudbase: CloudBaseClient, phoneNumber: String, verificationCode: String, captchaToken: String? = null): Boolean {\n    // Step1: SendSMSVerification code\n    val sendBody = mutableMapOf<String, Any>(\n        \"phone_number\" to if (phoneNumber.startsWith(\"+86\")) phoneNumber else \"+86$phoneNumber\",\n        \"target\" to \"ANY\"  // \"ANY\" - No restriction，Noneregardless of userYesNoexistsallSend; \"USER\" - AccountmustexiststhenSend\n    )\n\n    val sendHeaders = captchaToken?.let { mapOf(\"x-captcha-token\" to it) } ?: emptyMap()\n\n    val sendResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification\",\n        body = sendBody,\n        customHeaders = sendHeaders,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (sendResult == null) {\n        println(\"Send Codefailed\")\n        return false\n    }\n\n    val verificationId = sendResult[\"verification_id\"] as? String ?: return false\n    println(\"Verification codeSendsuccessful! ID: $verificationId\")\n\n    // Step2: Verify the code\n    val verifyResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification/verify\",\n        body = mapOf(\n            \"verification_id\" to verificationId,\n            \"verification_code\" to verificationCode\n        ),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (verifyResult == null) {\n        println(\"Verification codeError\")\n        return false\n    }\n\n    val verificationToken = verifyResult[\"verification_token\"] as? String ?: return false\n    println(\"Verifysuccessful!\")\n\n    // Step3: UseVerifytokenLogin\n    val loginResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/signin\",\n        body = mapOf(\n            \"phone_number\" to if (phoneNumber.startsWith(\"+86\")) phoneNumber else \"+86$phoneNumber\",\n            \"verification_token\" to verificationToken\n        ),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (loginResult != null) {\n        val accessToken = loginResult[\"access_token\"] as? String\n        println(\"Login successful!\")\n        accessToken?.let { cloudbase.updateAccessToken(it) }\n        return true\n    }\n\n    println(\"Login failed\")\n    return false\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val success = loginWithPhoneCode(cloudbase, \"13800138000\", \"123456\")\n//     if (success) {\n//         println(\"Phone numberLogin successful\")\n//     }\n// }\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login",
                "content": []
              },
              {
                "markdown": "```kotlin\nsuspend fun loginWithEmailCode(cloudbase: CloudBaseClient, email: String, verificationCode: String, captchaToken: String? = null): Boolean {\n    // Step1: SendEmailVerification code\n    val sendBody = mutableMapOf<String, Any>(\n        \"email\" to email,\n        \"target\" to \"ANY\"  // \"ANY\" - No restriction，Noneregardless of userYesNoexistsallSend; \"USER\" - AccountmustexiststhenSend\n    )\n\n    val sendHeaders = captchaToken?.let { mapOf(\"x-captcha-token\" to it) } ?: emptyMap()\n\n    val sendResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification\",\n        body = sendBody,\n        customHeaders = sendHeaders,\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (sendResult == null) {\n        println(\"Send Codefailed\")\n        return false\n    }\n\n    val verificationId = sendResult[\"verification_id\"] as? String ?: return false\n    println(\"Verification codeSendsuccessful! ID: $verificationId\")\n\n    // Step2: Verify the code\n    val verifyResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/verification/verify\",\n        body = mapOf(\n            \"verification_id\" to verificationId,\n            \"verification_code\" to verificationCode\n        ),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (verifyResult == null) {\n        println(\"Verification codeError\")\n        return false\n    }\n\n    val verificationToken = verifyResult[\"verification_token\"] as? String ?: return false\n    println(\"Verifysuccessful!\")\n\n    // Step3: UseVerifytokenLogin\n    val loginResult = cloudbase.request<Map<String, Any>>(\n        method = \"POST\",\n        path = \"/auth/v1/signin\",\n        body = mapOf(\n            \"email\" to email,\n            \"verification_token\" to verificationToken\n        ),\n        typeToken = object : TypeToken<Map<String, Any>>() {}\n    )\n\n    if (loginResult != null) {\n        val accessToken = loginResult[\"access_token\"] as? String\n        println(\"Login successful!\")\n        accessToken?.let { cloudbase.updateAccessToken(it) }\n        return true\n    }\n\n    println(\"Login failed\")\n    return false\n}\n\n// Usage Example\n// lifecycleScope.launch {\n//     val success = loginWithEmailCode(cloudbase, \"user@example.com\", \"123456\")\n//     if (success) {\n//         println(\"EmailLogin successful\")\n//     }\n// }\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login",
                "content": []
              }
            ]
          }
        ]
      }
    ],
    "_id": "754426be69a9286d00430bbc7ac3fa0c",
    "_openid": "anon",
    "createdAt": 1769744600669,
    "updatedAt": 1769766698595
  },
  {
    "category": "CloudBase MCP,CodeBuddy Code",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 118,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/codebuddy-code",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "```bash\ncodebuddy mcp add --scope project cloudbase --env INTEGRATION_IDE=CodeBuddyCode -- npx @cloudbase/cloudbase-mcp@latest\n```",
            "title": "CLI Command"
          },
          {
            "markdown": "Add the following configuration to `.mcp.json`:\n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"CodeBuddyCode\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "754426be69a9287000430be14417066f",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "Framework Integration,Mobile Frameworks,iOS Swift",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 13,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/http-api/basic/overview",
    "content": [
      {
        "markdown": "Use **HTTP Request** in **iOS Swift** Callvarious CloudBase capabilities\n\nthisprojectUse Swift Native URLSession，NoneneedadditionalDependency。\n\nif neededUsethird-party library，canUse CocoaPods or Swift Package Manager Install：\n\n```ruby\n# Podfile\npod 'Alamofire', '~> 5.8'\n```",
        "index": 1,
        "title": "Install Dependencies",
        "content": []
      },
      {
        "markdown": "Add the following code to your **iOS Swift** project",
        "index": 2,
        "title": "Initialize Configuration",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```swift\nimport Foundation\n\nclass CloudBaseClient {\n    let envId: String\n    private(set) var accessToken: String\n    let baseUrl: String\n\n    init(envId: String, accessToken: String) {\n        self.envId = envId\n        self.accessToken = accessToken\n        self.baseUrl = \"https://\\(envId).api.tcloudbasegateway.com\"\n    }\n\n    /// UpdateAccess token\n    ///\n    /// - Parameter newToken: new access token\n    func updateAccessToken(_ newToken: String) {\n        self.accessToken = newToken\n        print(\"Access token has beenUpdate\")\n    }\n\n    /// Unified HTTP request method\n    ///\n    /// - Parameters:\n    ///   - method: Request method (GET, POST, PUT, PATCH, DELETE)\n    ///   - path: APIPath (such as /v1/rdb/rest/table_name)\n    ///   - body: Request body data\n    ///   - customHeaders: Customheaders\n    /// - Returns: ResponseDataornil\n    func request<T: Decodable>(\n        method: String,\n        path: String,\n        body: [String: Any]? = nil,\n        customHeaders: [String: String] = [:],\n        completion: @escaping (T?) -> Void\n    ) {\n        guard let url = URL(string: \"\\(baseUrl)\\(path)\") else {\n            print(\"InvalidURL\")\n            completion(nil)\n            return\n        }\n\n        var request = URLRequest(url: url)\n        request.httpMethod = method.uppercased()\n        request.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n        request.setValue(\"application/json\", forHTTPHeaderField: \"Accept\")\n        request.setValue(\"Bearer \\(accessToken)\", forHTTPHeaderField: \"Authorization\")\n\n        // AddCustomheaders\n        customHeaders.forEach { key, value in\n            request.setValue(value, forHTTPHeaderField: key)\n        }\n\n        // SetRequestbody\n        if let body = body {\n            do {\n                request.httpBody = try JSONSerialization.data(withJSONObject: body)\n            } catch {\n                print(\"JSONSerializefailed: \\(error)\")\n                completion(nil)\n                return\n            }\n        }\n\n        let task = URLSession.shared.dataTask(with: request) { data, response, error in\n            if let error = error {\n                print(\"Requestfailed: \\(error.localizedDescription)\")\n                completion(nil)\n                return\n            }\n\n            guard let httpResponse = response as? HTTPURLResponse,\n                  (200...299).contains(httpResponse.statusCode) else {\n                print(\"Requestfailed: \\((response as? HTTPURLResponse)?.statusCode ?? -1)\")\n                completion(nil)\n                return\n            }\n\n            guard let data = data else {\n                // IfResponseis empty，Returntruerepresentssuccessful\n                if T.self == Bool.self {\n                    completion(true as? T)\n                } else {\n                    completion(nil)\n                }\n                return\n            }\n\n            do {\n                let decoder = JSONDecoder()\n                let result = try decoder.decode(T.self, from: data)\n                completion(result)\n            } catch {\n                // try asasAnyDecode\n                if let json = try? JSONSerialization.jsonObject(with: data) as? T {\n                    completion(json)\n                } else {\n                    print(\"JSONParsefailed: \\(error)\")\n                    completion(nil)\n                }\n            }\n        }\n\n        task.resume()\n    }\n\n    /// SyncVersion（Use async/await）\n    @available(iOS 13.0, *)\n    func request<T: Decodable>(\n        method: String,\n        path: String,\n        body: [String: Any]? = nil,\n        customHeaders: [String: String] = [:]\n    ) async -> T? {\n        await withCheckedContinuation { continuation in\n            request(method: method, path: path, body: body, customHeaders: customHeaders) { (result: T?) in\n                continuation.resume(returning: result)\n            }\n        }\n    }\n}\n\n// ConfigurationfileorInitializewhenCreateinstance\n// let cloudbase = CloudBaseClient(\n//     envId: \"your-env-id\",\n//     accessToken: \"your-access-token\"\n// )\n```",
            "index": 1,
            "title": "CloudBaseClient.swift"
          },
          {
            "markdown": "Create `Config.plist` fileStorageConfiguration：\n\n> 💡 Note: For user permissions, refer to the \"Authentication\" module to obtain access_token\n\n```xml\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n    <!-- Environment ID -->\n    <key>CLOUDBASE_ENV_ID</key>\n    <string>{%ENV_ID%}</string>\n    <!-- Anonymous access token -->\n    <key>CLOUDBASE_ACCESS_TOKEN</key>\n    <string>{%PUBLISHABLE_KEY%}</string>\n</dict>\n</plist>\n```\n\nReadConfigurationandInitializeclient：\n\n```swift\nfunc loadConfig() -> (envId: String, accessToken: String)? {\n    guard let path = Bundle.main.path(forResource: \"Config\", ofType: \"plist\"),\n          let config = NSDictionary(contentsOfFile: path),\n          let envId = config[\"CLOUDBASE_ENV_ID\"] as? String,\n          let accessToken = config[\"CLOUDBASE_ACCESS_TOKEN\"] as? String else {\n        return nil\n    }\n    return (envId, accessToken)\n}\n\n// in AppDelegate or SceneDelegate Initialize\nclass AppDelegate: UIResponder, UIApplicationDelegate {\n    var cloudbase: CloudBaseClient?\n\n    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {\n        // fromConfigurationfileLoadEnvironmentInfo\n        if let config = loadConfig() {\n            cloudbase = CloudBaseClient(envId: config.envId, accessToken: config.accessToken)\n            print(\"CloudBaseclientInitializesuccessful\")\n        } else {\n            print(\"ConfigurationfileLoadfailed\")\n        }\n        return true\n    }\n}\n\n// orinneedplacedirectlyInitialize\n// if let config = loadConfig() {\n//     let cloudbase = CloudBaseClient(envId: config.envId, accessToken: config.accessToken)\n//     // Use cloudbase performaftersubsequentoperate\n// }\n```",
            "index": 2,
            "title": "Config.plist"
          }
        ]
      },
      {
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```swift\nfunc getMysqlData(cloudbase: CloudBaseClient, tableName: String, completion: @escaping ([[String: Any]]?) -> Void) {\n    // Query MySQL database data\n    cloudbase.request(\n        method: \"GET\",\n        path: \"/v1/rdb/rest/\\(tableName)?limit=10\"\n    ) { (data: [[String: Any]]?) in\n        if let data = data {\n            print(\"Querysuccessful: \\(data)\")\n        }\n        completion(data ?? [])\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [[String: Any]]? = await cloudbase.request(\n//         method: \"GET\",\n//         path: \"/v1/rdb/rest/{%TABLE_NAME%}?limit=10\"\n//     )\n//     print(result)\n// }\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```swift\nfunc addMysqlData(cloudbase: CloudBaseClient, tableName: String, data: [String: Any], completion: @escaping ([String: Any]?) -> Void) {\n    // Add MySQL database data\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/rdb/rest/\\(tableName)\",\n        body: data\n    ) { (result: [String: Any]?) in\n        if let result = result {\n            print(\"Insert successful: \\(result)\")\n        }\n        completion(result)\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [String: Any]? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/rdb/rest/{%TABLE_NAME%}\",\n//         body: [\"title\": \"Example Title\"]\n//     )\n//     print(result)\n// }\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```swift\nfunc updateMysqlData(cloudbase: CloudBaseClient, tableName: String, dataId: String, data: [String: Any], completion: @escaping (Any?) -> Void) {\n    // Update MySQL database data\n    cloudbase.request(\n        method: \"PATCH\",\n        path: \"/v1/rdb/rest/\\(tableName)?id=eq.\\(dataId)\",\n        body: data\n    ) { (result: Any?) in\n        if result != nil {\n            print(\"Update successful: \\(result ?? \"\")\")\n        }\n        completion(result)\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: Any? = await cloudbase.request(\n//         method: \"PATCH\",\n//         path: \"/v1/rdb/rest/{%TABLE_NAME%}?id=eq.<data id>\",\n//         body: [\"title\": \"New Title\"]\n//     )\n//     print(result)\n// }\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```swift\nfunc deleteMysqlData(cloudbase: CloudBaseClient, tableName: String, dataId: String, completion: @escaping (Bool) -> Void) {\n    // Delete MySQL database data\n    cloudbase.request(\n        method: \"DELETE\",\n        path: \"/v1/rdb/rest/\\(tableName)?id=eq.\\(dataId)\"\n    ) { (result: Bool?) in\n        if result == true {\n            print(\"Delete successful\")\n            completion(true)\n        } else {\n            completion(false)\n        }\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: Bool? = await cloudbase.request(\n//         method: \"DELETE\",\n//         path: \"/v1/rdb/rest/{%TABLE_NAME%}?id=eq.<data id>\"\n//     )\n//     print(result ?? false)\n// }\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```swift\nfunc getModelData(cloudbase: CloudBaseClient, modelName: String, envType: String = \"prod\", completion: @escaping ([[String: Any]]) -> Void) {\n    // QueryData ModelData\n    let payload: [String: Any] = [\n        \"pageSize\": 10,\n        \"pageNumber\": 1,\n        \"getCount\": true\n    ]\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/model/\\(envType)/\\(modelName)/list\",\n        body: payload\n    ) { (result: [String: Any]?) in\n        if let result = result,\n           let data = result[\"data\"] as? [String: Any],\n           let records = data[\"records\"] as? [[String: Any]] {\n            print(\"Querysuccessful: \\(records)\")\n            completion(records)\n        } else {\n            completion([])\n        }\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [String: Any]? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/model/prod/{%TABLE_NAME%}/list\",\n//         body: [\"pageSize\": 10, \"pageNumber\": 1, \"getCount\": true]\n//     )\n//     print(result)\n// }\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```swift\nfunc addModelData(cloudbase: CloudBaseClient, modelName: String, data: [String: Any], envType: String = \"prod\", completion: @escaping ([String: Any]?) -> Void) {\n    // AddData ModelData\n    let payload: [String: Any] = [\"data\": data]\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/model/\\(envType)/\\(modelName)/create\",\n        body: payload\n    ) { (result: [String: Any]?) in\n        if let result = result,\n           let data = result[\"data\"] as? [String: Any],\n           let docId = data[\"id\"] {\n            print(\"Insert successful! id: \\(docId)\")\n        }\n        completion(result)\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [String: Any]? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/model/prod/{%TABLE_NAME%}/create\",\n//         body: [\"data\": [\"title\": \"Example Title\"]]\n//     )\n//     print(result)\n// }\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```swift\nfunc updateModelData(cloudbase: CloudBaseClient, modelName: String, dataId: String, data: [String: Any], envType: String = \"prod\", completion: @escaping (Bool) -> Void) {\n    // UpdateData ModelData\n    let payload: [String: Any] = [\n        \"data\": data,\n        \"filter\": [\n            \"where\": [\n                \"_id\": [\"$eq\": dataId]\n            ]\n        ]\n    ]\n\n    cloudbase.request(\n        method: \"PUT\",\n        path: \"/v1/model/\\(envType)/\\(modelName)/update\",\n        body: payload\n    ) { (result: Any?) in\n        if result != nil {\n            print(\"Update successful!\")\n            completion(true)\n        } else {\n            completion(false)\n        }\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let payload: [String: Any] = [\n//         \"data\": [\"title\": \"New Title\"],\n//         \"filter\": [\"where\": [\"_id\": [\"$eq\": \"<data id>\"]]]\n//     ]\n//     let result: Any? = await cloudbase.request(\n//         method: \"PUT\",\n//         path: \"/v1/model/prod/{%TABLE_NAME%}/update\",\n//         body: payload\n//     )\n//     print(result != nil)\n// }\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```swift\nfunc deleteModelData(cloudbase: CloudBaseClient, modelName: String, dataId: String, envType: String = \"prod\", completion: @escaping (Bool) -> Void) {\n    // DeleteData ModelData\n    let payload: [String: Any] = [\n        \"filter\": [\n            \"where\": [\n                \"_id\": [\"$eq\": dataId]\n            ]\n        ]\n    ]\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/model/\\(envType)/\\(modelName)/delete\",\n        body: payload\n    ) { (result: Any?) in\n        if result != nil {\n            print(\"Delete successful!\")\n            completion(true)\n        } else {\n            completion(false)\n        }\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let payload: [String: Any] = [\n//         \"filter\": [\"where\": [\"_id\": [\"$eq\": \"<data id>\"]]]\n//     ]\n//     let result: Any? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/model/prod/{%TABLE_NAME%}/delete\",\n//         body: payload\n//     )\n//     print(result != nil)\n// }\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```swift\nfunc callFunction(cloudbase: CloudBaseClient, functionName: String, data: [String: Any]? = nil, completion: @escaping ([String: Any]?) -> Void) {\n    // CallCloud Function\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/functions/\\(functionName)\",\n        body: data ?? [:]\n    ) { (result: [String: Any]?) in\n        if let result = result {\n            print(\"Cloud function call result: \\(result)\")\n        }\n        completion(result)\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [String: Any]? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/functions/{%FUNCTION_NAME%}\",\n//         body: [:]\n//     )\n//     print(result)\n// }\n```",
            "index": 3,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```swift\nfunc callContainer(cloudbase: CloudBaseClient, serviceName: String, path: String = \"\", method: String = \"GET\", data: [String: Any]? = nil, completion: @escaping (Any?) -> Void) {\n    // CallCloud Runservice\n    var fullPath = \"/v1/cloudrun/\\(serviceName)/\\(path)\"\n    if fullPath.hasSuffix(\"/\") {\n        fullPath = String(fullPath.dropLast())\n    }\n\n    cloudbase.request(\n        method: method.uppercased(),\n        path: fullPath,\n        body: data\n    ) { (result: Any?) in\n        if let result = result {\n            print(\"Cloud RunCallResult: \\(result)\")\n        }\n        completion(result)\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: Any? = await cloudbase.request(\n//         method: \"GET\",\n//         path: \"/v1/cloudrun/{%SERVICE_NAME%}\"\n//     )\n//     print(result)\n// }\n```",
            "index": 4,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```swift\nfunc uploadFile(cloudbase: CloudBaseClient, filePath: String, objectId: String? = nil, completion: @escaping ([String: String]?) -> Void) {\n    // Upload FiletoCloud Storage\n    guard let fileUrl = URL(string: filePath),\n          let fileData = try? Data(contentsOf: fileUrl) else {\n        print(\"filedoes not exist: \\(filePath)\")\n        completion(nil)\n        return\n    }\n\n    let filename = fileUrl.lastPathComponent\n    let timestamp = Int(Date().timeIntervalSince1970 * 1000)\n    let finalObjectId = objectId ?? \"uploads/\\(timestamp)-\\(filename)\"\n\n    // 1. Get upload info\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/storages/get-objects-upload-info\",\n        body: [[\"objectId\": finalObjectId]]\n    ) { (uploadInfo: [[String: Any]]?) in\n        guard let uploadInfo = uploadInfo, !uploadInfo.isEmpty else {\n            completion(nil)\n            return\n        }\n\n        let info = uploadInfo[0]\n        guard let uploadUrl = info[\"uploadUrl\"] as? String,\n              let authorization = info[\"authorization\"] as? String,\n              let token = info[\"token\"] as? String,\n              let cloudObjectMeta = info[\"cloudObjectMeta\"] as? String else {\n            completion(nil)\n            return\n        }\n\n        // 2. Upload File\n        guard let url = URL(string: uploadUrl) else {\n            completion(nil)\n            return\n        }\n\n        var request = URLRequest(url: url)\n        request.httpMethod = \"PUT\"\n        request.setValue(authorization, forHTTPHeaderField: \"Authorization\")\n        request.setValue(token, forHTTPHeaderField: \"X-Cos-Security-Token\")\n        request.setValue(cloudObjectMeta, forHTTPHeaderField: \"X-Cos-Meta-Fileid\")\n        request.httpBody = fileData\n\n        let task = URLSession.shared.dataTask(with: request) { _, response, error in\n            if let error = error {\n                print(\"fileUploadfailed: \\(error.localizedDescription)\")\n                completion(nil)\n                return\n            }\n\n            guard let httpResponse = response as? HTTPURLResponse,\n                  (200...299).contains(httpResponse.statusCode) else {\n                print(\"fileUploadfailed\")\n                completion(nil)\n                return\n            }\n\n            let result = [\n                \"cloudObjectId\": info[\"cloudObjectId\"] as? String ?? \"\",\n                \"downloadUrl\": info[\"downloadUrl\"] as? String ?? \"\",\n                \"objectId\": finalObjectId\n            ]\n\n            print(\"fileUpload successful:\")\n            print(\"- Object ID: \\(result[\"objectId\"] ?? \"\")\")\n            print(\"- DownloadURL: \\(result[\"downloadUrl\"] ?? \"\")\")\n\n            completion(result)\n        }\n\n        task.resume()\n    }\n}\n\n// Usage Example\n// uploadFile(cloudbase: cloudbase, filePath: \"./example.jpg\") { result in\n//     print(result)\n// }\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```swift\nfunc getFileUrl(cloudbase: CloudBaseClient, cloudObjectId: String, completion: @escaping (String?) -> Void) {\n    // GetCloud Storagefiletemporary accessURL\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/storages/get-objects-download-info\",\n        body: [[\"cloudObjectId\": cloudObjectId]]\n    ) { (result: [[String: Any]]?) in\n        if let result = result, !result.isEmpty,\n           let downloadUrl = result[0][\"downloadUrl\"] as? String {\n            print(\"fileURL: \\(downloadUrl)\")\n            completion(downloadUrl)\n        } else {\n            completion(nil)\n        }\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [[String: Any]]? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/storages/get-objects-download-info\",\n//         body: [[\"cloudObjectId\": \"cloud://xxx.png\"]]\n//     )\n//     if let downloadUrl = result?.first?[\"downloadUrl\"] as? String {\n//         print(downloadUrl)\n//     }\n// }\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```swift\nfunc downloadFile(cloudbase: CloudBaseClient, cloudObjectId: String, savePath: String = \"./\", completion: @escaping (Bool) -> Void) {\n    // DownloadCloud Storagefiletolocal\n    // 1. GetDownloadURL\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/storages/get-objects-download-info\",\n        body: [[\"cloudObjectId\": cloudObjectId]]\n    ) { (result: [[String: Any]]?) in\n        guard let result = result, !result.isEmpty,\n              let downloadUrl = result[0][\"downloadUrl\"] as? String else {\n            completion(false)\n            return\n        }\n\n        guard let url = URL(string: downloadUrl) else {\n            completion(false)\n            return\n        }\n\n        // 2. Download File\n        let task = URLSession.shared.downloadTask(with: url) { tempUrl, _, error in\n            if let error = error {\n                print(\"Downloadfailed: \\(error.localizedDescription)\")\n                completion(false)\n                return\n            }\n\n            guard let tempUrl = tempUrl else {\n                completion(false)\n                return\n            }\n\n            // 3. DetermineSavePath\n            let filename = url.lastPathComponent.components(separatedBy: \"?\").first ?? \"file\"\n            let fileManager = FileManager.default\n            var fullPath: URL\n\n            if savePath.hasSuffix(\"/\") {\n                fullPath = URL(fileURLWithPath: savePath).appendingPathComponent(filename)\n            } else {\n                fullPath = URL(fileURLWithPath: savePath)\n            }\n\n            // 4. Savefile\n            do {\n                if fileManager.fileExists(atPath: fullPath.path) {\n                    try fileManager.removeItem(at: fullPath)\n                }\n                try fileManager.moveItem(at: tempUrl, to: fullPath)\n                print(\"Downloadsuccessful! filesaved to: \\(fullPath.path)\")\n                completion(true)\n            } catch {\n                print(\"Downloadfailed: \\(error.localizedDescription)\")\n                completion(false)\n            }\n        }\n\n        task.resume()\n    }\n}\n\n// Usage Example\n// downloadFile(cloudbase: cloudbase, cloudObjectId: \"cloud://xxx.png\", savePath: \"./downloads/\") { success in\n//     print(success)\n// }\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```swift\nfunc deleteFile(cloudbase: CloudBaseClient, cloudObjectIds: Any, completion: @escaping (Bool) -> Void) {\n    // DeleteCloud Storagefile\n    var ids: [String] = []\n\n    if let idString = cloudObjectIds as? String {\n        ids = [idString]\n    } else if let idArray = cloudObjectIds as? [String] {\n        ids = idArray\n    } else {\n        print(\"Parameter type error\")\n        completion(false)\n        return\n    }\n\n    let data = ids.map { [\"cloudObjectId\": $0] }\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/storages/delete-objects\",\n        body: data\n    ) { (result: Any?) in\n        if result != nil {\n            print(\"Delete successful!\")\n            completion(true)\n        } else {\n            completion(false)\n        }\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let data = [[\"cloudObjectId\": \"cloud://xxx.png\"]]\n//     let result: Any? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/v1/storages/delete-objects\",\n//         body: data\n//     )\n//     print(result != nil)\n// }\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```swift\nfunc streamText(cloudbase: CloudBaseClient, model: String, subModel: String, messages: [[String: String]], completion: @escaping (String?) -> Void) {\n    // streamingtextthisGenerate\n    let payload: [String: Any] = [\n        \"model\": subModel,\n        \"messages\": messages,\n        \"stream\": true\n    ]\n\n    guard let url = URL(string: \"\\(cloudbase.baseUrl)/v1/ai/\\(model)/chat/completions\") else {\n        completion(nil)\n        return\n    }\n\n    var request = URLRequest(url: url)\n    request.httpMethod = \"POST\"\n    request.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n    request.setValue(\"text/event-stream\", forHTTPHeaderField: \"Accept\")\n    request.setValue(\"Bearer \\(cloudbase.accessToken)\", forHTTPHeaderField: \"Authorization\")\n\n    do {\n        request.httpBody = try JSONSerialization.data(withJSONObject: payload)\n    } catch {\n        print(\"JSONSerializefailed: \\(error)\")\n        completion(nil)\n        return\n    }\n\n    let task = URLSession.shared.dataTask(with: request) { data, response, error in\n        if let error = error {\n            print(\"AI Call failed: \\(error.localizedDescription)\")\n            completion(nil)\n            return\n        }\n\n        guard let data = data,\n              let responseString = String(data: data, encoding: .utf8) else {\n            completion(nil)\n            return\n        }\n\n        print(\"AI Streaming response:\")\n        var fullContent = \"\"\n\n        let lines = responseString.components(separatedBy: \"\\n\")\n        for line in lines {\n            if line.hasPrefix(\"data: \") {\n                let dataStr = String(line.dropFirst(6))\n                if dataStr.trimmingCharacters(in: .whitespaces) != \"[DONE]\" {\n                    if let data = dataStr.data(using: .utf8),\n                       let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],\n                       let choices = json[\"choices\"] as? [[String: Any]],\n                       let delta = choices.first?[\"delta\"] as? [String: Any],\n                       let content = delta[\"content\"] as? String {\n                        print(content, terminator: \"\")\n                        fullContent += content\n                    }\n                }\n            }\n        }\n\n        print()\n        completion(fullContent)\n    }\n\n    task.resume()\n}\n\n// Usage Example\n// streamText(\n//     cloudbase: cloudbase,\n//     model: \"{%AI_MODEL_NAME%}\",\n//     subModel: \"{%AI_SUB_MODEL_NAME%}\",\n//     messages: [\n//         [\"role\": \"system\", \"content\": \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create\"],\n//         [\"role\": \"user\", \"content\": \"Spring\"]\n//     ]\n// ) { response in\n//     print(\"\\nComplete response: \\(response ?? \"\")\")\n// }\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```swift\nfunc generateImage(cloudbase: CloudBaseClient, prompt: String, completion: @escaping ([String: Any]?) -> Void) {\n    // PrepareCallparameter\n    let data: [String: Any] = [\"prompt\": prompt]\n    \n    // CallCloud FunctionGenerate Image\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/v1/functions/<YOUR_FUNCTION_NAME>\",\n        body: data\n    ) { (result: [String: Any]?) in\n        if let result = result {\n            if let success = result[\"success\"] as? Bool, success {\n                let imageUrl = result[\"imageUrl\"] as? String ?? \"\"\n                let revisedPrompt = result[\"revised_prompt\"] as? String ?? \"\"\n                \n                print(\"Generation successful!\")\n                print(\"Image URL: \\(imageUrl)\")\n                print(\"Optimized prompt: \\(revisedPrompt)\")\n                print(\"Note: Image URLValidis valid for24hours\")\n                \n                completion(result)\n            } else {\n                let code = result[\"code\"] as? String ?? \"\"\n                let message = result[\"message\"] as? String ?? \"\"\n                print(\"Generation failed: \\(code) - \\(message)\")\n                completion(nil)\n            }\n        } else {\n            print(\"Requestfailed\")\n            completion(nil)\n        }\n    }\n}\n\n// Usage Example\n// generateImage(cloudbase: cloudbase, prompt: \"A cute cat playing in the sunshine\") { result in\n//     if let result = result {\n//         print(\"ImageGenerateDone: \\(result)\")\n//     }\n// }\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```swift\n/**\n * iOS Swift Call Agent Example (AG-UI Protocol)\n * Protocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n */\nfunc chatWithAgentStream(cloudbase: CloudBaseClient, botId: String, userMessage: String, completion: @escaping (String?) -> Void) {\n    // Build message list (AG-UI protocol format)\n    let messages: [[String: Any]] = [\n        [\n            \"id\": \"msg_001\",\n            \"role\": \"user\",\n            \"content\": userMessage\n        ]\n    ]\n\n    // AG-UI Protocol request parameters\n    let payload: [String: Any] = [\n        \"messages\": messages,                                    // Required: Message list\n        \"threadId\": \"550e8400-e29b-41d4-a716-446655440000\",     // Optional: Session ID for multi-turn conversation\n        \"runId\": \"run_001\",                                      // Optional: Run ID for execution tracking\n        \"tools\": [],                                             // Optional: Frontend tool definitions\n        \"context\": [],                                           // Optional: Context information\n        \"forwardedProps\": [:]                                    // Optional: Pass-through parameters\n    ]\n\n    guard let url = URL(string: \"\\(cloudbase.baseUrl)/v1/aibot/bots/\\(botId)/send-message\") else {\n        completion(nil)\n        return\n    }\n\n    var request = URLRequest(url: url)\n    request.httpMethod = \"POST\"\n    request.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n    request.setValue(\"text/event-stream\", forHTTPHeaderField: \"Accept\")\n    request.setValue(\"Bearer \\(cloudbase.accessToken)\", forHTTPHeaderField: \"Authorization\")\n\n    do {\n        request.httpBody = try JSONSerialization.data(withJSONObject: payload)\n    } catch {\n        print(\"JSONSerializefailed: \\(error)\")\n        completion(nil)\n        return\n    }\n\n    let task = URLSession.shared.dataTask(with: request) { data, response, error in\n        if let error = error {\n            print(\"AI Call failed: \\(error.localizedDescription)\")\n            completion(nil)\n            return\n        }\n\n        guard let data = data,\n              let responseString = String(data: data, encoding: .utf8) else {\n            completion(nil)\n            return\n        }\n\n        print(\"AI Streaming response:\")\n        var fullContent = \"\"\n\n        let lines = responseString.components(separatedBy: \"\\n\")\n        for line in lines {\n            if line.hasPrefix(\"data: \") {\n                let dataStr = String(line.dropFirst(6)).trimmingCharacters(in: .whitespaces)\n                if !dataStr.isEmpty && dataStr != \"[DONE]\" {\n                    if let data = dataStr.data(using: .utf8),\n                       let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {\n                        var content = \"\"\n\n                        if let directContent = json[\"content\"] as? String {\n                            content = directContent\n                        } else if let choices = json[\"choices\"] as? [[String: Any]] {\n                            if let delta = choices.first?[\"delta\"] as? [String: Any],\n                               let deltaContent = delta[\"content\"] as? String {\n                                content = deltaContent\n                            } else if let message = choices.first?[\"message\"] as? [String: Any],\n                                      let messageContent = message[\"content\"] as? String {\n                                content = messageContent\n                            }\n                        }\n\n                        if !content.isEmpty {\n                            print(content, terminator: \"\")\n                            fullContent += content\n                        }\n                    }\n                }\n            }\n        }\n\n        print()\n        completion(fullContent)\n    }\n\n    task.resume()\n}\n\n// Usage Example\n// chatWithAgentStream(cloudbase: cloudbase, botId: \"{%AGENT_ID%}\", userMessage: \"Who are you\") { response in\n//     print(\"\\nComplete response: \\(response ?? \"\")\")\n// }\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```swift\nfunc chatWithAgentStream(cloudbase: CloudBaseClient, botId: String, msg: String, history: [[String: String]]? = nil, completion: @escaping (String?) -> Void) {\n    // streamingCallAgent\n    let payload: [String: Any] = [\n        \"history\": history ?? [],\n        \"msg\": msg\n    ]\n\n    guard let url = URL(string: \"\\(cloudbase.baseUrl)/v1/aibot/bots/\\(botId)/send-message\") else {\n        completion(nil)\n        return\n    }\n\n    var request = URLRequest(url: url)\n    request.httpMethod = \"POST\"\n    request.setValue(\"application/json\", forHTTPHeaderField: \"Content-Type\")\n    request.setValue(\"text/event-stream\", forHTTPHeaderField: \"Accept\")\n    request.setValue(\"Bearer \\(cloudbase.accessToken)\", forHTTPHeaderField: \"Authorization\")\n\n    do {\n        request.httpBody = try JSONSerialization.data(withJSONObject: payload)\n    } catch {\n        print(\"JSONSerializefailed: \\(error)\")\n        completion(nil)\n        return\n    }\n\n    let task = URLSession.shared.dataTask(with: request) { data, response, error in\n        if let error = error {\n            print(\"AI Call failed: \\(error.localizedDescription)\")\n            completion(nil)\n            return\n        }\n\n        guard let data = data,\n              let responseString = String(data: data, encoding: .utf8) else {\n            completion(nil)\n            return\n        }\n\n        print(\"AI Streaming response:\")\n        var fullContent = \"\"\n\n        let lines = responseString.components(separatedBy: \"\\n\")\n        for line in lines {\n            if line.hasPrefix(\"data: \") {\n                let dataStr = String(line.dropFirst(6)).trimmingCharacters(in: .whitespaces)\n                if !dataStr.isEmpty && dataStr != \"[DONE]\" {\n                    if let data = dataStr.data(using: .utf8),\n                       let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {\n                        var content = \"\"\n\n                        if let directContent = json[\"content\"] as? String {\n                            content = directContent\n                        } else if let choices = json[\"choices\"] as? [[String: Any]] {\n                            if let delta = choices.first?[\"delta\"] as? [String: Any],\n                               let deltaContent = delta[\"content\"] as? String {\n                                content = deltaContent\n                            } else if let message = choices.first?[\"message\"] as? [String: Any],\n                                      let messageContent = message[\"content\"] as? String {\n                                content = messageContent\n                            }\n                        }\n\n                        if !content.isEmpty {\n                            print(content, terminator: \"\")\n                            fullContent += content\n                        }\n                    }\n                }\n            }\n        }\n\n        print()\n        completion(fullContent)\n    }\n\n    task.resume()\n}\n\n// Usage Example\n// chatWithAgentStream(cloudbase: cloudbase, botId: \"{%AGENT_ID%}\", msg: \"Who are you\") { response in\n//     print(\"\\nComplete response: \\(response ?? \"\")\")\n// }\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 8,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```swift\nfunc signUpWithPhoneCode(cloudbase: CloudBaseClient, phoneNumber: String, verificationCode: String, username: String? = nil, password: String? = nil, captchaToken: String? = nil, completion: @escaping ([String: Any]?) -> Void) {\n    // Step1: SendSMSVerification code\n    var body: [String: Any] = [\n        \"phone_number\": phoneNumber.hasPrefix(\"+86\") ? phoneNumber : \"+86\\(phoneNumber)\",\n        \"target\": \"NON_USER\"  // \"NON_USER\" - Accountdoes not existthenSend; \"ANY\" - No restriction\n    ]\n\n    var headers: [String: String] = [:]\n    if let token = captchaToken {\n        headers[\"x-captcha-token\"] = token\n    }\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/auth/v1/verification\",\n        body: body,\n        customHeaders: headers\n    ) { (sendResult: [String: Any]?) in\n        guard let sendResult = sendResult,\n              let verificationId = sendResult[\"verification_id\"] as? String else {\n            print(\"Send Codefailed\")\n            completion(nil)\n            return\n        }\n\n        print(\"Verification codeSendsuccessful! ID: \\(verificationId)\")\n\n        // Step2: Verify the code\n        cloudbase.request(\n            method: \"POST\",\n            path: \"/auth/v1/verification/verify\",\n            body: [\n                \"verification_id\": verificationId,\n                \"verification_code\": verificationCode\n            ]\n        ) { (verifyResult: [String: Any]?) in\n            guard let verifyResult = verifyResult,\n                  let verificationToken = verifyResult[\"verification_token\"] as? String else {\n                print(\"Verification codeError\")\n                completion(nil)\n                return\n            }\n\n            print(\"Verifysuccessful!\")\n\n            // Step3: UseVerifytokenRegister\n            var signUpBody: [String: Any] = [\n                \"phone_number\": phoneNumber.hasPrefix(\"+86\") ? phoneNumber : \"+86\\(phoneNumber)\",\n                \"verification_token\": verificationToken\n            ]\n\n            // Optional：AddUsernameandPassword\n            if let username = username {\n                signUpBody[\"username\"] = username\n            }\n            if let password = password {\n                signUpBody[\"password\"] = password\n            }\n\n            cloudbase.request(\n                method: \"POST\",\n                path: \"/auth/v1/signup\",\n                body: signUpBody\n            ) { (signUpResult: [String: Any]?) in\n                if let signUpResult = signUpResult,\n                   let accessToken = signUpResult[\"access_token\"] as? String,\n                   let userId = signUpResult[\"sub\"] as? String {\n                    print(\"Registration successful! User ID: \\(userId)\")\n                    print(\"Access token: \\(String(accessToken.prefix(20)))...\")\n\n                    // UpdateAccess token\n                    cloudbase.updateAccessToken(accessToken)\n                    completion(signUpResult)\n                } else {\n                    print(\"Registration failed\")\n                    completion(nil)\n                }\n            }\n        }\n    }\n}\n\n// Usage Example\n// signUpWithPhoneCode(\n//     cloudbase: cloudbase,\n//     phoneNumber: \"13800138000\",\n//     verificationCode: \"123456\",\n//     username: \"myusername\",\n//     password: \"mypassword\"\n// ) { result in\n//     if result != nil {\n//         print(\"Phone numberRegistration successful\")\n//     }\n// }\n```",
                "index": 1,
                "title": "SMS Code Registration",
                "content": []
              },
              {
                "markdown": "```swift\nfunc signUpWithEmailCode(cloudbase: CloudBaseClient, email: String, verificationCode: String, username: String? = nil, password: String? = nil, captchaToken: String? = nil, completion: @escaping ([String: Any]?) -> Void) {\n    // Step1: SendEmailVerification code\n    var body: [String: Any] = [\n        \"email\": email,\n        \"target\": \"NON_USER\"  // \"NON_USER\" - Accountdoes not existthenSend; \"ANY\" - No restriction\n    ]\n\n    var headers: [String: String] = [:]\n    if let token = captchaToken {\n        headers[\"x-captcha-token\"] = token\n    }\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/auth/v1/verification\",\n        body: body,\n        customHeaders: headers\n    ) { (sendResult: [String: Any]?) in\n        guard let sendResult = sendResult,\n              let verificationId = sendResult[\"verification_id\"] as? String else {\n            print(\"Send Codefailed\")\n            completion(nil)\n            return\n        }\n\n        print(\"Verification codeSendsuccessful! ID: \\(verificationId)\")\n\n        // Step2: Verify the code\n        cloudbase.request(\n            method: \"POST\",\n            path: \"/auth/v1/verification/verify\",\n            body: [\n                \"verification_id\": verificationId,\n                \"verification_code\": verificationCode\n            ]\n        ) { (verifyResult: [String: Any]?) in\n            guard let verifyResult = verifyResult,\n                  let verificationToken = verifyResult[\"verification_token\"] as? String else {\n                print(\"Verification codeError\")\n                completion(nil)\n                return\n            }\n\n            print(\"Verifysuccessful!\")\n\n            // Step3: UseVerifytokenRegister\n            var signUpBody: [String: Any] = [\n                \"email\": email,\n                \"verification_token\": verificationToken\n            ]\n\n            // Optional：AddUsernameandPassword\n            if let username = username {\n                signUpBody[\"username\"] = username\n            }\n            if let password = password {\n                signUpBody[\"password\"] = password\n            }\n\n            cloudbase.request(\n                method: \"POST\",\n                path: \"/auth/v1/signup\",\n                body: signUpBody\n            ) { (signUpResult: [String: Any]?) in\n                if let signUpResult = signUpResult,\n                   let accessToken = signUpResult[\"access_token\"] as? String,\n                   let userId = signUpResult[\"sub\"] as? String {\n                    print(\"Registration successful! User ID: \\(userId)\")\n                    print(\"Access token: \\(String(accessToken.prefix(20)))...\")\n\n                    // UpdateAccess token\n                    cloudbase.updateAccessToken(accessToken)\n                    completion(signUpResult)\n                } else {\n                    print(\"Registration failed\")\n                    completion(nil)\n                }\n            }\n        }\n    }\n}\n\n// Usage Example\n// signUpWithEmailCode(\n//     cloudbase: cloudbase,\n//     email: \"user@example.com\",\n//     verificationCode: \"123456\",\n//     username: \"myusername\",\n//     password: \"mypassword\"\n// ) { result in\n//     if result != nil {\n//         print(\"EmailRegistration successful\")\n//     }\n// }\n```",
                "index": 2,
                "title": "Email Code Registration",
                "content": []
              },
              {
                "markdown": "```swift\nfunc signIn(cloudbase: CloudBaseClient, username: String, password: String, completion: @escaping ([String: Any]?) -> Void) {\n    // Username Password Login\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/auth/v1/signin\",\n        body: [\"username\": username, \"password\": password]\n    ) { (result: [String: Any]?) in\n        if let result = result,\n           let accessToken = result[\"access_token\"] as? String,\n           let userId = result[\"sub\"] as? String {\n            print(\"Login successful! User ID: \\(userId)\")\n            print(\"Access token: \\(String(accessToken.prefix(20)))...\")\n\n            // UpdateAccess token\n            cloudbase.updateAccessToken(accessToken)\n        }\n        completion(result)\n    }\n}\n\n// Usage Example（async/await）\n// Task {\n//     let result: [String: Any]? = await cloudbase.request(\n//         method: \"POST\",\n//         path: \"/auth/v1/signin\",\n//         body: [\"username\": \"your_username\", \"password\": \"your_password\"]\n//     )\n//     if let result = result,\n//        let accessToken = result[\"access_token\"] as? String {\n//         // UpdateAccess token\n//         cloudbase.updateAccessToken(accessToken)\n//     }\n//     print(result)\n// }\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login",
                "content": []
              },
              {
                "markdown": "```swift\nfunc loginWithPhoneCode(cloudbase: CloudBaseClient, phoneNumber: String, verificationCode: String, captchaToken: String? = nil, completion: @escaping (Bool) -> Void) {\n    // Step1: SendSMSVerification code\n    var body: [String: Any] = [\n        \"phone_number\": phoneNumber.hasPrefix(\"+86\") ? phoneNumber : \"+86\\(phoneNumber)\",\n        \"target\": \"ANY\"  // \"ANY\" - No restriction，Noneregardless of userYesNoexistsallSend; \"USER\" - AccountmustexiststhenSend\n    ]\n\n    var headers: [String: String] = [:]\n    if let token = captchaToken {\n        headers[\"x-captcha-token\"] = token\n    }\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/auth/v1/verification\",\n        body: body,\n        customHeaders: headers\n    ) { (sendResult: [String: Any]?) in\n        guard let sendResult = sendResult,\n              let verificationId = sendResult[\"verification_id\"] as? String else {\n            print(\"Send Codefailed\")\n            completion(false)\n            return\n        }\n\n        print(\"Verification codeSendsuccessful! ID: \\(verificationId)\")\n\n        // Step2: Verify the code\n        cloudbase.request(\n            method: \"POST\",\n            path: \"/auth/v1/verification/verify\",\n            body: [\n                \"verification_id\": verificationId,\n                \"verification_code\": verificationCode\n            ]\n        ) { (verifyResult: [String: Any]?) in\n            guard let verifyResult = verifyResult,\n                  let verificationToken = verifyResult[\"verification_token\"] as? String else {\n                print(\"Verification codeError\")\n                completion(false)\n                return\n            }\n\n            print(\"Verifysuccessful!\")\n\n            // Step3: UseVerifytokenLogin\n            cloudbase.request(\n                method: \"POST\",\n                path: \"/auth/v1/signin\",\n                body: [\n                    \"phone_number\": phoneNumber.hasPrefix(\"+86\") ? phoneNumber : \"+86\\(phoneNumber)\",\n                    \"verification_token\": verificationToken\n                ]\n            ) { (loginResult: [String: Any]?) in\n                if let loginResult = loginResult,\n                   let accessToken = loginResult[\"access_token\"] as? String {\n                    print(\"Login successful!\")\n                    cloudbase.updateAccessToken(accessToken)\n                    completion(true)\n                } else {\n                    print(\"Login failed\")\n                    completion(false)\n                }\n            }\n        }\n    }\n}\n\n// Usage Example\n// loginWithPhoneCode(\n//     cloudbase: cloudbase,\n//     phoneNumber: \"13800138000\",\n//     verificationCode: \"123456\"\n// ) { success in\n//     if success {\n//         print(\"Phone numberLogin successful\")\n//     }\n// }\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login",
                "content": []
              },
              {
                "markdown": "```swift\nfunc loginWithEmailCode(cloudbase: CloudBaseClient, email: String, verificationCode: String, captchaToken: String? = nil, completion: @escaping (Bool) -> Void) {\n    // Step1: SendEmailVerification code\n    var body: [String: Any] = [\n        \"email\": email,\n        \"target\": \"ANY\"  // \"ANY\" - No restriction，Noneregardless of userYesNoexistsallSend; \"USER\" - AccountmustexiststhenSend\n    ]\n\n    var headers: [String: String] = [:]\n    if let token = captchaToken {\n        headers[\"x-captcha-token\"] = token\n    }\n\n    cloudbase.request(\n        method: \"POST\",\n        path: \"/auth/v1/verification\",\n        body: body,\n        customHeaders: headers\n    ) { (sendResult: [String: Any]?) in\n        guard let sendResult = sendResult,\n              let verificationId = sendResult[\"verification_id\"] as? String else {\n            print(\"Send Codefailed\")\n            completion(false)\n            return\n        }\n\n        print(\"Verification codeSendsuccessful! ID: \\(verificationId)\")\n\n        // Step2: Verify the code\n        cloudbase.request(\n            method: \"POST\",\n            path: \"/auth/v1/verification/verify\",\n            body: [\n                \"verification_id\": verificationId,\n                \"verification_code\": verificationCode\n            ]\n        ) { (verifyResult: [String: Any]?) in\n            guard let verifyResult = verifyResult,\n                  let verificationToken = verifyResult[\"verification_token\"] as? String else {\n                print(\"Verification codeError\")\n                completion(false)\n                return\n            }\n\n            print(\"Verifysuccessful!\")\n\n            // Step3: UseVerifytokenLogin\n            cloudbase.request(\n                method: \"POST\",\n                path: \"/auth/v1/signin\",\n                body: [\n                    \"email\": email,\n                    \"verification_token\": verificationToken\n                ]\n            ) { (loginResult: [String: Any]?) in\n                if let loginResult = loginResult,\n                   let accessToken = loginResult[\"access_token\"] as? String {\n                    print(\"Login successful!\")\n                    cloudbase.updateAccessToken(accessToken)\n                    completion(true)\n                } else {\n                    print(\"Login failed\")\n                    completion(false)\n                }\n            }\n        }\n    }\n}\n\n// Usage Example\n// loginWithEmailCode(\n//     cloudbase: cloudbase,\n//     email: \"user@example.com\",\n//     verificationCode: \"123456\"\n// ) { success in\n//     if success {\n//         print(\"EmailLogin successful\")\n//     }\n// }\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login",
                "content": []
              }
            ]
          }
        ]
      }
    ],
    "_id": "7dc2756e69a9286e0042b86476056c94",
    "_openid": "anon",
    "createdAt": 1769744605450,
    "updatedAt": 1769766703341
  },
  {
    "category": "CloudBase MCP,Trae",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 114,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/trae",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.trae/mcp.json`:\n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Trae\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "7eeea64669a9286f0043487e6e23ca06",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,CodeBuddy",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 117,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/codebuddy",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "CodeBuddy IDE has built-in CloudBase MCP integration. We recommend using the configuration integration method first. [View BaaS integration documentation](https://www.codebuddy.ai/docs/zh/ide/User-guide/Integration)",
            "title": "Built-in Integration"
          },
          {
            "markdown": "For manual MCP configuration, please refer to [CodeBuddy Documentation](https://www.codebuddy.ai/docs/zh/ide/Config%20MCP) \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"CodeBuddyManual\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "7eeea64669a9286f004348804711373f",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1770708765560
  },
  {
    "category": "CloudBase MCP,RooCode",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 108,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/roocode",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.roocode/mcp.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n\t \"disabled\": false,\n \"env\": {\n \"INTEGRATION_IDE\": \"RooCode\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "7eeea64669a92870004348896ce868cc",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,WindSurf",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 103,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/windsurf",
    "content": [
      {
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.windsurf/mcp.json`: \n```json\n{\n  \"mcpServers\": {\n    \"cloudbase\": {\n      \"command\": \"npx\",\n      \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n      \"env\": {\n        \"INTEGRATION_IDE\": \"WindSurf\",\n        \"CLOUDBASE_MCP_PLUGINS_DISABLED\": \"interactive\"\n      }\n    }\n  }\n}\n```\n",
            "title": "Manual Configuration",
            "content": []
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "94ed52ca69a9286e0043496b49bbeb47",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769757569583
  },
  {
    "category": "CloudBase MCP,OpenAI Codex CLI",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 110,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/openai-codex-cli",
    "content": [
      {
        "docsUrl": "",
        "markdown": "**Prerequisites:** \n```bash\nnpm i @cloudbase/cloudbase-mcp -g\n```\n\nRun the following command in terminal based on your operating system:\n\n**MacOS, Linux, WSL:**\n```bash\ncodex mcp add cloudbase --env INTEGRATION_IDE=CodeX -- cloudbase-mcp\n```\n\n**Windows Powershell:**\n```bash\ncodex mcp add cloudbase --env INTEGRATION_IDE=CodeX -- cmd /c cloudbase-mcp\n```",
        "title": "Installation",
        "type": "",
        "content": []
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "94ed52ca69a9286f00434975177bbf65",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Tongyi Lingma",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 113,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/tongyi-lingma",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "For manual MCP configuration, please refer to [Tongyi Lingmadocumentation](https://help.aliyun.com/zh/lingma/user-guide/guide-for-using-mcp) \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"LingMa\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "94ed52ca69a928700043497d0204c5f0",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "Framework Integration,Web Frameworks,React(Vite)",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 10,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/api-reference/webv2/initialization",
    "content": [
      {
        "markdown": "`@cloudbase/js-sdk` allows you to use JavaScript on Web (such as PC web pages, WeChat H5, etc.) to access CloudBase services and resources.（）",
        "index": 1,
        "title": "Install SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```bash\nnpm i @cloudbase/js-sdk\n```",
            "index": 1,
            "title": "npm",
            "content": []
          },
          {
            "markdown": "```bash\nyarn add @cloudbase/js-sdk\n```",
            "index": 2,
            "title": "yarn",
            "content": []
          },
          {
            "markdown": "```bash\npnpm add @cloudbase/js-sdk\n```",
            "index": 3,
            "title": "pnpm",
            "content": []
          }
        ]
      },
      {
        "markdown": "Add the following code to your React project",
        "index": 2,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nimport cloudbaseSDK from \"@cloudbase/js-sdk\";\n\nexport const cloudbase = cloudbaseSDK.init({\n  env: import.meta.env.VITE_CLOUDBASE_ENV_ID,\n  region: import.meta.env.VITE_CLOUDBASE_REGION,\n  accessKey: import.meta.env.VITE_CLOUDBASE_ACCESS_KEY\n});\n```",
            "index": 1,
            "title": "src/utils/cloudbase.js",
            "content": []
          },
          {
            "markdown": "```properties\n# Environment ID\nVITE_CLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Region\nVITE_CLOUDBASE_REGION={%REGION%}\n\n# Anonymous access token\nVITE_CLOUDBASE_ACCESS_KEY={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": ".env",
            "content": []
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table (limit 10 records)\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n\nconsole.log(\"Query result:\", data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Insert a record into {%TABLE_NAME%} table\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"New Post\", status: \"draft\" })\n  .select();\n\nconsole.log(\"Insert result:\", data);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ status: \"published\" })\n  .eq(\"id\", 1)\n  .select();\n\nconsole.log(\"Update result:\", data);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Upsert: update on conflict, otherwise insert\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Post Title\", status: \"published\" }, { onConflict: \"id\" })\n  .select();\n\nconsole.log(\"Upsert result:\", data);\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", 1);\n\nconsole.log(\"Delete completed:\", error);\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table first 10 records\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\nif (!error) {\n  console.log(data);\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState, useEffect } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState([]);\n\n  useEffect(() => {\n    getData();\n  }, []);\n\n  const getData = async () => {\n    // Query {%TABLE_NAME%} table first 10 records\n    const { data, error } = await cloudbase\n      .rdb()\n      .from(\"{%TABLE_NAME%}\")\n      .select(\"*\")\n      .limit(10);\n    if (!error) setData(data || []);\n  };\n\n  return (\n    <ul>\n      {data.map(item => (\n        <li key={item.id}>{item.title}</li>\n      ))}\n    </ul>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} table data\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"Example Title\" });\nif (!error) {\n  console.log(\"Insert successful\");\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [title, setTitle] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  const addData = async () => {\n    // Add {%TABLE_NAME%} table data\n    const { error } = await cloudbase\n      .rdb()\n      .from(\"{%TABLE_NAME%}\")\n      .insert({ title });\n    if (!error) {\n      setTitle(\"\");\n      setMessage(\"Insert successful！\");\n    } else {\n      setMessage(\"Insert failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <input value={title} onChange={e => setTitle(e.target.value)} />\n      <button onClick={addData}>Add</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} table id with specified value\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ title: \"New Title\" })\n  .eq(\"id\", \"<data id>\");\nif (!error) {\n  console.log(\"Update successful\");\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const updateData = async () => {\n    // Update {%TABLE_NAME%} table id with specified value\n    const { error } = await cloudbase\n      .rdb()\n      .from(\"{%TABLE_NAME%}\")\n      .update({ title: \"New Title\" })\n      .eq(\"id\", \"<data id>\");\n    if (!error) {\n      setMessage(\"Update successful！\");\n    } else {\n      setMessage(\"Update failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={updateData}>Update</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Example Title\" });\nif (!error) {\n  console.log(\"Operation successful\");\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const upsertData = async () => {\n    // If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\n    const { error } = await cloudbase\n      .rdb()\n      .from(\"{%TABLE_NAME%}\")\n      .upsert({ id: 1, title: \"Example Title\" });\n    if (!error) {\n      setMessage(\"Operation successful！\");\n    } else {\n      setMessage(\"Operation failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={upsertData}>UpdateorCreate</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} table id with specified value\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", \"<data id>\");\nif (!error) {\n  console.log(\"Delete successful\");\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const deleteData = async () => {\n    // Delete {%TABLE_NAME%} table id with specified value\n    const { error } = await cloudbase\n      .rdb()\n      .from(\"{%TABLE_NAME%}\")\n      .delete()\n      .eq(\"id\", \"<data id>\");\n    if (!error) {\n      setMessage(\"Delete successful！\");\n    } else {\n      setMessage(\"Delete failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={deleteData}>Delete</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table first 10 records\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\nconsole.log(res.data);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState, useEffect } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState([]);\n\n  useEffect(() => {\n    getData();\n  }, []);\n\n  const getData = async () => {\n    // Query {%TABLE_NAME%} table first 10 records\n    const db = cloudbase.database();\n    const res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n    setData(res.data || []);\n  };\n\n  return (\n    <ul>\n      {data.map(item => (\n        <li key={item._id}>{item.title}</li>\n      ))}\n    </ul>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} table data\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({ title: \"Example Title\" });\nconsole.log(`Insert successful! id: ${res.id}`);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const addData = async () => {\n    try {\n      // Add {%TABLE_NAME%} table data\n      const db = cloudbase.database();\n      const res = await db\n        .collection(\"{%TABLE_NAME%}\")\n        .add({ title: \"Example Title\" });\n      setMessage(`Insert successful! id: ${res.id}`);\n    } catch (error) {\n      setMessage(\"Insert failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={addData}>Add</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} table id with specified value\nconst db = cloudbase.database();\nawait db\n  .collection(\"{%TABLE_NAME%}\")\n  .doc(\"<data id>\")\n  .update({ title: \"New Title\" });\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const updateData = async () => {\n    try {\n      // Update {%TABLE_NAME%} table id with specified value\n      const db = cloudbase.database();\n      await db\n        .collection(\"{%TABLE_NAME%}\")\n        .doc(\"<data id>\")\n        .update({ title: \"New Title\" });\n      setMessage(\"Update successful！\");\n    } catch (error) {\n      setMessage(\"Update failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={updateData}>Update</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} table id with specified value\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").remove();\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const deleteData = async () => {\n    try {\n      // Delete {%TABLE_NAME%} table id with specified value\n      const db = cloudbase.database();\n      await db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").remove();\n      setMessage(\"Delete successful！\");\n    } catch (error) {\n      setMessage(\"Delete failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={deleteData}>Delete</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} Data Modelbefore10recordsData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\nconsole.log(res.data?.records);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState, useEffect } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState([]);\n\n  useEffect(() => {\n    getData();\n  }, []);\n\n  const getData = async () => {\n    // Query {%TABLE_NAME%} Data Modelbefore10recordsData\n    const res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n      pageNumber: 1,\n      pagesize: 10\n    });\n    setData(res.data?.records || []);\n  };\n\n  return (\n    <ul>\n      {data.map(item => (\n        <li key={item._id}>{item.title}</li>\n      ))}\n    </ul>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} Data ModelData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: { title: \"Example Title\" }\n});\nconsole.log(`Insert successful! id: ${res.data.id}`);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const addData = async () => {\n    try {\n      // Add {%TABLE_NAME%} Data ModelData\n      const res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n        data: { title: \"Example Title\" }\n      });\n      setMessage(`Insert successful! id: ${res.data.id}`);\n    } catch (error) {\n      setMessage(\"Insert failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={addData}>Add</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} Data Model _id with specified value\nawait cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: { title: \"New Title\" },\n  filter: { where: { _id: { $eq: \"<data id>\" } } }\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const updateData = async () => {\n    try {\n      // Update {%TABLE_NAME%} Data Model _id with specified value\n      await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n        data: { title: \"New Title\" },\n        filter: { where: { _id: { $eq: \"<data id>\" } } }\n      });\n      setMessage(\"Update successful！\");\n    } catch (error) {\n      setMessage(\"Update failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={updateData}>Update</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} Data Model _id with specified value\nawait cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: { where: { _id: { $eq: \"<data id>\" } } }\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const deleteData = async () => {\n    try {\n      // Delete {%TABLE_NAME%} Data Model _id with specified value\n      await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n        filter: { where: { _id: { $eq: \"<data id>\" } } }\n      });\n      setMessage(\"Delete successful！\");\n    } catch (error) {\n      setMessage(\"Delete failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={deleteData}>Delete</button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call {%FUNCTION_NAME%} Cloud Function\nconst res = await cloudbase.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {}\n});\nconsole.log(res.result);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState(null);\n\n  const getData = async () => {\n    // Call {%FUNCTION_NAME%} Cloud Function\n    const res = await cloudbase.callFunction({\n      name: \"{%FUNCTION_NAME%}\",\n      data: {}\n    });\n    setData(res.result);\n  };\n\n  return (\n    <div>\n      <button onClick={getData}>CallCloud Function</button>\n      {data && <pre>{JSON.stringify(data, null, 2)}</pre>}\n    </div>\n  );\n}\n\nexport default Page;\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function",
            "content": []
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call {%SERVICE_NAME%} Cloud Runservice\nconst res = await cloudbase.callContainer({\n  name: \"{%SERVICE_NAME%}\"\n  method: 'POST',\n  path: '/',\n  header:{\n    'Content-Type': 'application/json; charset=utf-8'\n  },\n  data: {},\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState(null);\n\n  const getData = async () => {\n    // Call {%SERVICE_NAME%} Cloud Runservice\n    const res = await cloudbase.callContainer({\n      name: \"{%SERVICE_NAME%}\"\n      method: 'POST',\n      path: '/',\n      header:{\n        'Content-Type': 'application/json; charset=utf-8'\n      },\n      data: {},\n    });\n    setData(res);\n  };\n\n  return (\n    <div>\n      <button onClick={getData}>CallCloud Run</button>\n      {data && <pre>{JSON.stringify(data, null, 2)}</pre>}\n    </div>\n  );\n}\n\nexport default Page;\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run",
            "content": []
          },
          {
            "index": 6,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.uploadFile({\n  cloudPath: `images/${Date.now()}-${file.name}`, // Path to upload in cloud\n  filePath: file\n});\nconsole.log(res.fileID);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [fileID, setFileID] = useState(\"\");\n\n  const uploadFile = async e => {\n    const file = e.target.files[0];\n    const res = await cloudbase.uploadFile({\n      cloudPath: `images/${Date.now()}-${file.name}`, // Path to upload in cloud\n      filePath: file\n    });\n    setFileID(res.fileID);\n  };\n\n  return (\n    <div>\n      <input type=\"file\" onChange={uploadFile} />\n      {fileID && <p>Upload successful: {fileID}</p>}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "title": "Upload File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.getTempFileURL({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\nconsole.log(res.fileList[0].tempFileURL);\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [fileUrl, setFileUrl] = useState(\"\");\n\n  const getData = async () => {\n    const res = await cloudbase.getTempFileURL({\n      fileList: [\"cloud://xxx.png\"] // File fileID list\n    });\n    setFileUrl(res.fileList[0].tempFileURL);\n  };\n\n  return (\n    <div>\n      <button onClick={getData}>GetURL</button>\n      {fileUrl && <p>URL: {fileUrl}</p>}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 2,
                "title": "Get File URL"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nawait cloudbase.downloadFile({\n  fileID: \"cloud://xxx.png\" // File fileID\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const downloadFile = async () => {\n    await cloudbase.downloadFile({\n      fileID: \"cloud://xxx.png\" // File fileID\n    });\n  };\n\n  return <button onClick={downloadFile}>Download File</button>;\n}\n\nexport default Page;\n```",
                "index": 3,
                "title": "Download File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.deleteFile({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\nif (res.fileList[0].code === \"SUCCESS\") {\n  console.log(\"Delete successful\");\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n\n  const deleteFile = async () => {\n    const res = await cloudbase.deleteFile({\n      fileList: [\"cloud://xxx.png\"] // File fileID list\n    });\n    if (res.fileList[0].code === \"SUCCESS\") {\n      setMessage(\"Delete successful！\");\n    } else {\n      setMessage(\"Delete failed！\", res.fileList);\n    }\n  };\n\n  return (\n    <div>\n      <button onClick={deleteFile}>Delete File</button>\n      {message && <p>{message}</p>}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 4,
                "title": "Delete File"
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase\n  .ai()\n  .createModel(\"{%AI_MODEL_NAME%}\")\n  .streamText({\n    model: \"{%AI_SUB_MODEL_NAME%}\",\n    messages: [{ role: \"user\", content: \"Hello\" }]\n  });\n\nfor await (let data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data?.choices?.[0]?.delta?.reasoning_content;\n  if (think) console.log(think);\n\n  // Print generated text content\n  const text = data?.choices?.[0]?.delta?.content;\n  if (text) console.log(text);\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState(\"\");\n  const [input, setInput] = useState(\"\");\n\n  const getData = async () => {\n    const res = await cloudbase\n      .ai()\n      .createModel(\"{%AI_MODEL_NAME%}\")\n      .streamText({\n        model: \"{%AI_SUB_MODEL_NAME%}\",\n        messages: [{ role: \"user\", content: input }]\n      });\n\n    let result = \"\";\n    for await (let data of res.dataStream) {\n      // Print reasoning content if available\n      const think = data?.choices?.[0]?.delta?.reasoning_content;\n      if (think) {\n        result += think;\n      }\n\n      // Print generated text content\n      const text = data?.choices?.[0]?.delta?.content;\n      if (text) result += text;\n\n      setData(result);\n    }\n  };\n\n  return (\n    <div>\n      <input\n        value={input}\n        placeholder=\"Enter AI conversation content\"\n        onChange={e => setInput(e.target.value)}\n      />\n      <button onClick={getData}>Send</button>\n      <p>{data}</p>\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation"
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call image generation cloud function\nconst res = await cloudbase.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: {\n    prompt: \"A cute cat playing in the sunshine\"\n  }\n});\n\nconst result = res.result;\n\nif (result.success) {\n  // Generation successful\n  console.log(\"Generation successful!\");\n  console.log(\"Image URL:\", result.imageUrl);\n  console.log(\"Optimized prompt:\", result.revised_prompt);\n\n  // Use image\n  // Note: Image URL is valid for 24 hours, please save or transfer promptly\n} else {\n  // Generation failed\n  console.error(\"Generation failed:\", result.code, result.message);\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [prompt, setPrompt] = useState(\"\");\n  const [imageUrl, setImageUrl] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n  const [loading, setLoading] = useState(false);\n\n  const generateImage = async () => {\n    setLoading(true);\n    setMessage(\"\");\n    setImageUrl(\"\");\n\n    try {\n      // Call image generation cloud function\n      const res = await cloudbase.callFunction({\n        name: \"<YOUR_FUNCTION_NAME>\",\n        data: {\n          prompt: prompt\n        }\n      });\n\n      const result = res.result;\n\n      if (result.success) {\n        setImageUrl(result.imageUrl);\n        setMessage(\"Generation successful！\");\n      } else {\n        setMessage(`Generation failed：${result.message}`);\n      }\n    } catch (error) {\n      setMessage(\"Call failed：\" + error.message);\n    } finally {\n      setLoading(false);\n    }\n  };\n\n  return (\n    <div>\n      <input\n        value={prompt}\n        placeholder=\"Enter image description\"\n        onChange={e => setPrompt(e.target.value)}\n      />\n      <button onClick={generateImage} disabled={!prompt || loading}>\n        {loading ? \"Generating...\" : \"Generate Image\"}\n      </button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n      {imageUrl && (\n        <div>\n          <img src={imageUrl} alt=\"Generated image\" style={{ maxWidth: \"100%\" }} />\n          <p style={{ fontSize: \"12px\", color: \"#666\" }}>\n            Note: Image URL is valid for 24 hours, please save promptly\n          </p>\n        </div>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation"
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from './utils/cloudbase';\n\nconst res = await cloudbase.ai().bot.sendMessage({\n  botId: '{%AGENT_ID%}',\n  // Refer to frontend-backend communication protocol for input structure：\n  //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n  threadId: '550e8400-e29b-41d4-a716-446655440000',\n  runId: 'run_001',\n  messages: [\n    {\n      id: 'msg_001',\n      role: 'user',\n      content: 'Hello',\n    },\n  ],\n  tools: [],\n  context: [],\n  state: {},\n  forwardedProps: {},\n});\n\nfor await (const data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data.reasoning_content;\n  if (think) console.log(think);\n\n  // Print output content\n  const content = data.content;\n  if (content) console.log(content);\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from 'react';\nimport { cloudbase } from './utils/cloudbase';\n\nfunction Page() {\n  const [data, setData] = useState('');\n  const [input, setInput] = useState('');\n\n  const getData = async () => {\n    const res = await cloudbase.ai().bot.sendMessage({\n      botId: '{%AGENT_ID%}',\n      // Refer to frontend-backend communication protocol for input structure：\n      //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n      threadId: '550e8400-e29b-41d4-a716-446655440000',\n      runId: 'run_001',\n      messages: [\n        {\n          id: 'msg_001',\n          role: 'user',\n          content: input,\n        },\n      ],\n      tools: [],\n      context: [],\n      state: {},\n      forwardedProps: {},\n    });\n\n    let result = '';\n    for await (const data of res.dataStream) {\n      // Print reasoning content if available\n      const think = data.reasoning_content;\n      if (think) {\n        result += think;\n      }\n\n      // Print output content\n      const content = data.content;\n      if (content) result += content;\n\n      setData(result);\n    }\n  };\n\n  return (\n    <div>\n      <input value={input} placeholder=\"Enter Agent conversation content\" onChange={(e) => setInput(e.target.value)} />\n      <button onClick={getData}>Send</button>\n      <p>{data}</p>\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.ai().bot.sendMessage({\n  botId: \"{%AGENT_ID%}\",\n  msg: \"Hello\"\n});\n\nfor await (const data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data.reasoning_content;\n  if (think) console.log(think);\n\n  // Print output content\n  const content = data.content;\n  if (content) console.log(content);\n}\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [data, setData] = useState(\"\");\n  const [input, setInput] = useState(\"\");\n\n  const getData = async () => {\n    const res = await cloudbase.ai().bot.sendMessage({\n      botId: \"{%AGENT_ID%}\",\n      msg: input\n    });\n\n    let result = \"\";\n    for await (const data of res.dataStream) {\n      // Print reasoning content if available\n      const think = data.reasoning_content;\n      if (think) {\n        result += think;\n      }\n\n      // Print output content\n      const content = data.content;\n      if (content) result += content;\n\n      setData(result);\n    }\n  };\n\n  return (\n    <div>\n      <input\n        value={input}\n        placeholder=\"Enter Agent conversation content\"\n        onChange={e => setInput(e.target.value)}\n      />\n      <button onClick={getData}>Send</button>\n      <p>{data}</p>\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 9,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "Use **SMS Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMSVerification code**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: phone });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  phone_number: `+86 ${phone}`,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${phone.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [phone, setPhone] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationId, setVerificationId] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ phone_number: phone });\n      setVerificationId(res.verification_id);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(\"Send failed：\" + error.message);\n    }\n  };\n\n  // Register\n  const register = async () => {\n    try {\n      const auth = cloudbase.auth();\n      // Verify the code\n      const verifyRes = await auth.verify({\n        verification_id: verificationId,\n        verification_code: code\n      });\n      // Register (auto-login if user exists)\n      await auth.signUp({\n        phone_number: `+86 ${phone}`,\n        verification_code: code,\n        verification_token: verifyRes.verification_token,\n        name: `user_${phone.slice(-4)}`,\n        password: \"admin@123\"\n      });\n      setMessage(\"Registration successful！\");\n    } catch (error) {\n      setMessage(\"Registration failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <label>Phone number：</label>\n      <input\n        value={phone}\n        onChange={e => setPhone(e.target.value)}\n        placeholder=\"13800000000\"\n      />\n      <div>\n        <label>Verification code：</label>\n        <input\n          value={code}\n          onChange={e => setCode(e.target.value)}\n          placeholder=\"Verification code\"\n        />\n        <button disabled={!phone} onClick={sendCode}>\n          Send Code\n        </button>\n      </div>\n      <button disabled={!verificationId || !code} onClick={register}>\n        Register\n      </button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 1,
                "title": "SMS Code Registration"
              },
              {
                "markdown": "Use **Email Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  email,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${email.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [email, setEmail] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationId, setVerificationId] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ email });\n      setVerificationId(res.verification_id);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(\"Send failed：\" + error.message);\n    }\n  };\n\n  // Register\n  const register = async () => {\n    try {\n      const auth = cloudbase.auth();\n      // Verify the code\n      const verifyRes = await auth.verify({\n        verification_id: verificationId,\n        verification_code: code\n      });\n      // Register (auto-login if user exists)\n      await auth.signUp({\n        email,\n        verification_code: code,\n        verification_token: verifyRes.verification_token,\n        name: `user_${email.slice(-4)}`,\n        password: \"admin@123\"\n      });\n      setMessage(\"Registration successful！\");\n    } catch (error) {\n      setMessage(\"Registration failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <label>Email：</label>\n      <input\n        value={email}\n        onChange={e => setEmail(e.target.value)}\n        placeholder=\"example@email.com\"\n      />\n      <div>\n        <label>Verification code：</label>\n        <input\n          value={code}\n          onChange={e => setCode(e.target.value)}\n          placeholder=\"Verification code\"\n        />\n        <button disabled={!email} onClick={sendCode}>\n          Send Code\n        </button>\n      </div>\n      <button disabled={!verificationId || !code} onClick={register}>\n        Register\n      </button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 2,
                "title": "Email Code Registration"
              },
              {
                "markdown": "Use **Username Password Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **UsernamePasswordLogin**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\nawait auth.signIn({\n  username, // Can be username, phone or email\n  password\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [username, setUsername] = useState(\"\");\n  const [password, setPassword] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  // Login\n  const login = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signIn({\n        username: username, // Can be username, phone or email\n        password: password\n      });\n      setMessage(\"Login successful！\");\n    } catch (error) {\n      setMessage(\"Login failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <label>Account：</label>\n      <input\n        value={username}\n        onChange={e => setUsername(e.target.value)}\n        placeholder=\"Username/Phone/Email\"\n      />\n      Note: Add country code for phone login +86\n      <br />\n      <label>Password：</label>\n      <input\n        type=\"password\"\n        value={password}\n        onChange={e => setPassword(e.target.value)}\n        placeholder=\"Enter password\"\n      />\n      <br />\n      <button disabled={!username || !password} onClick={login}>\n        Login\n      </button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login"
              },
              {
                "markdown": "Use **SMS Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMS Verification Login**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n\n// Login\nawait auth.signInWithSms({\n  verificationInfo: res,\n  verificationCode: code,\n  phoneNum: `+86 ${phone}`\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [phone, setPhone] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationInfo, setVerificationInfo] = useState(null);\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n      setVerificationInfo(res);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(\"Send failed：\" + error.message);\n    }\n  };\n\n  // Login\n  const login = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInWithSms({\n        verificationInfo,\n        verificationCode: code,\n        phoneNum: `+86 ${phone}`\n      });\n      setMessage(\"Login successful！\");\n    } catch (error) {\n      setMessage(\"Login failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <label>Phone number：</label>\n      <input\n        value={phone}\n        onChange={e => setPhone(e.target.value)}\n        placeholder=\"13800000000\"\n      />\n      <div>\n        <label>Verification code：</label>\n        <input\n          value={code}\n          onChange={e => setCode(e.target.value)}\n          placeholder=\"Verification code\"\n        />\n        <button onClick={sendCode} disabled={!phone}>\n          Send Code\n        </button>\n      </div>\n      <button onClick={login} disabled={!verificationInfo || !code}>\n        Login\n      </button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login"
              },
              {
                "markdown": "Use **Email Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Login\nawait auth.signInWithEmail({\n  verificationInfo: res,\n  verificationCode: code,\n  email\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [email, setEmail] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationInfo, setVerificationInfo] = useState(null);\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ email });\n      setVerificationInfo(res);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(\"Send failed：\" + error.message);\n    }\n  };\n\n  // Login\n  const login = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInWithEmail({\n        verificationInfo,\n        verificationCode: code,\n        email\n      });\n      setMessage(\"Login successful！\");\n    } catch (error) {\n      setMessage(\"Login failed：\" + error.message);\n    }\n  };\n\n  return (\n    <div>\n      <label>Email：</label>\n      <input\n        value={email}\n        onChange={e => setEmail(e.target.value)}\n        placeholder=\"example@email.com\"\n      />\n      <div>\n        <label>Verification code：</label>\n        <input\n          value={code}\n          onChange={e => setCode(e.target.value)}\n          placeholder=\"Verification code\"\n        />\n        <button onClick={sendCode} disabled={!email}>\n          Send Code\n        </button>\n      </div>\n      <button onClick={login} disabled={!verificationInfo || !code}>\n        Login\n      </button>\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login"
              },
              {
                "markdown": "Use **Google OAuth Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **Google OAuth Login**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Step1：GenerateGoogleauthorization URLandRedirect\nconst state = Date.now().toString();\nlocalStorage.setItem(\"google_login_state\", state);\nconst { uri } = await auth.genProviderRedirectUri({\n  provider_id: \"google\",\n  provider_redirect_uri: window.location.href,\n  state: state\n});\nwindow.location.href = uri;\n\n// Step2：Usecodeexchange forprovider_token\nconst { provider_token } = await auth.grantProviderToken({\n  provider_id: \"google\",\n  provider_redirect_uri: window.location.origin + window.location.pathname,\n  provider_code: code\n});\n\n// Step3：Useprovider_tokenLogin\nawait auth.signInWithProvider({\n  provider_token: provider_token\n});\n```\n\n**Full Example：**\n\n```jsx\nimport { useState, useEffect } from \"react\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nfunction Page() {\n  const [message, setMessage] = useState(\"\");\n  const [isCallback, setIsCallback] = useState(false);\n\n  useEffect(() => {\n    // CheckYesNoYesGoogleCallbackPage\n    const urlParams = new URLSearchParams(window.location.search);\n    const code = urlParams.get(\"code\");\n    const state = urlParams.get(\"state\");\n\n    if (code && state) {\n      setIsCallback(true);\n      handleGoogleCallback(code, state);\n    }\n  }, []);\n\n  // Step1：Redirect toGoogleauthorization page\n  const startGoogleLogin = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const state = Date.now().toString(); // Generate unique identifier to prevent CSRF attacks\n\n      // Save state locally for callback verification\n      localStorage.setItem(\"google_login_state\", state);\n\n      // GenerateGoogleauthorization URL\n      const { uri } = await auth.genProviderRedirectUri({\n        provider_id: \"google\", // Fixed value, representingGoogleOpen Platform\n        provider_redirect_uri: window.location.href, // Callback to current page after authorization\n        state: state\n      });\n\n      // Redirect toGoogleauthorization page\n      window.location.href = uri;\n    } catch (error) {\n      setMessage(\"Redirect failed：\" + error.message);\n    }\n  };\n\n  // Step2and3：ProcessGoogleCallbackandDoneLogin\n  const handleGoogleCallback = async (code, state) => {\n    try {\n      // Verify state matches to prevent CSRF attacks\n      const savedState = localStorage.getItem(\"google_login_state\");\n      if (savedState !== state) {\n        setMessage(\"Login failed：State verification failed\");\n        return;\n      }\n\n      const auth = cloudbase.auth();\n\n      // Usecodeexchange forprovider_token\n      const { provider_token } = await auth.grantProviderToken({\n        provider_id: \"google\",\n        provider_redirect_uri:\n          window.location.origin + window.location.pathname,\n        provider_code: code\n      });\n\n      try {\n        // Try direct login\n        await auth.signInWithProvider({\n          provider_token: provider_token\n        });\n\n        setMessage(\"Login successful！\");\n\n        // Clear URL parameters and local storage\n        localStorage.removeItem(\"google_login_state\");\n        window.history.replaceState(\n          {},\n          document.title,\n          window.location.pathname\n        );\n      } catch (loginError) {\n        // IfYesfirst-timeGoogleLogin，needfirstRegisterandbindthe\n        if (loginError.error === \"not_found\") {\n          setMessage(\"Detected first-timeGoogleLogin，Need to bindaccount...\");\n\n          // Here you need to guide the user to complete the registration process\n          // For example: collect phone verification code for registration\n          // After successful registration, call bindWithProvider bindtheGoogleidentity\n\n          // Example: Assuming an account registered via other methods, bindirect\n          await auth.bindWithProvider({\n            provider_token: provider_token\n          });\n\n          // Re-login after successful bindng\n          await auth.signInWithProvider({\n            provider_token: provider_token\n          });\n\n          setMessage(\"bindand login successful！\");\n\n          // Clear URL parameters and local storage\n          localStorage.removeItem(\"google_login_state\");\n          window.history.replaceState(\n            {},\n            document.title,\n            window.location.pathname\n          );\n        } else {\n          throw loginError;\n        }\n      }\n    } catch (error) {\n      setMessage(\"Login failed：\" + error.message);\n      localStorage.removeItem(\"google_login_state\");\n    }\n  };\n\n  return (\n    <div>\n      {!isCallback && <button onClick={startGoogleLogin}>GoogleLogin</button>}\n      {isCallback && <p>ProcessingGoogleLogin...</p>}\n      {message && (\n        <p style={{ color: message.includes(\"successful\") ? \"green\" : \"red\" }}>\n          {message}\n        </p>\n      )}\n    </div>\n  );\n}\n\nexport default Page;\n```",
                "index": 6,
                "id": "google",
                "title": "Google OAuth Login"
              }
            ]
          }
        ]
      }
    ],
    "_id": "aca45c22697c807b00436a3d02777aba",
    "_openid": "anon",
    "createdAt": 1769767035561,
    "updatedAt": 1769767035561
  },
  {
    "category": "Framework Integration,Backend Frameworks,Go",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 6,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/http-api/basic/overview",
    "content": [
      {
        "markdown": "Use **HTTP Request** in **Go** Callvarious CloudBase capabilities\n\n```bash\ngo get github.com/joho/godotenv\n```",
        "index": 1,
        "title": "Install Dependencies",
        "content": []
      },
      {
        "markdown": "Add the following code to your **Go** project",
        "index": 2,
        "title": "Initialize Configuration",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```go\npackage main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\n\t\"github.com/joho/godotenv\"\n)\n\ntype CloudBaseClient struct {\n\tEnvID       string\n\tAccessToken string\n\tBaseURL     string\n\tHTTPClient  *http.Client\n}\n\nfunc NewCloudBaseClient() *CloudBaseClient {\n\tgodotenv.Load()\n\n\tenvID := os.Getenv(\"CLOUDBASE_ENV_ID\")\n\taccessToken := os.Getenv(\"CLOUDBASE_ACCESS_TOKEN\")\n\n\treturn &CloudBaseClient{\n\t\tEnvID:       envID,\n\t\tAccessToken: accessToken,\n\t\tBaseURL:     fmt.Sprintf(\"https://%s.api.tcloudbasegateway.com\", envID),\n\t\tHTTPClient:  &http.Client{},\n\t}\n}\n\nfunc (c *CloudBaseClient) Request(method, path string, body interface{}, customHeaders map[string]string) (interface{}, error) {\n\turl := c.BaseURL + path\n\n\tvar reqBody io.Reader\n\tif body != nil {\n\t\tjsonData, err := json.Marshal(body)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"JSONSerializefailed: %w\", err)\n\t\t}\n\t\treqBody = bytes.NewBuffer(jsonData)\n\t}\n\n\treq, err := http.NewRequest(method, url, reqBody)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Create requestfailed: %w\", err)\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+c.AccessToken)\n\n\tfor key, value := range customHeaders {\n\t\treq.Header.Set(key, value)\n\t}\n\n\tresp, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Requestfailed: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\tbodyBytes, _ := io.ReadAll(resp.Body)\n\t\treturn nil, fmt.Errorf(\"Requestfailed，status code: %d, Response: %s\", resp.StatusCode, string(bodyBytes))\n\t}\n\n\tbodyBytes, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Read responsefailed: %w\", err)\n\t}\n\n\tif len(bodyBytes) == 0 {\n\t\treturn true, nil\n\t}\n\n\tvar result interface{}\n\tif err := json.Unmarshal(bodyBytes, &result); err != nil {\n\t\treturn nil, fmt.Errorf(\"JSONParsefailed: %w\", err)\n\t}\n\n\treturn result, nil\n}\n\nvar Cloudbase = NewCloudBaseClient()\n```",
            "index": 1,
            "title": "cloudbase_client.go"
          },
          {
            "markdown": "> 💡Note: If admin permission is needed, obtain the APIKey from the [CloudBase Platform/ApiKeymanagement page](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}&#/env/apikey) Get APIKey to replace CLOUDBASE_ACCESS_TOKEN\n\n```properties\n# Environment ID\nCLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Anonymous access token\nCLOUDBASE_ACCESS_TOKEN={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": ".env"
          }
        ]
      },
      {
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc GetMySQLData(tableName string) (interface{}, error) {\n\tpath := fmt.Sprintf(\"/v1/rdb/rest/%s?limit=10\", tableName)\n\tdata, err := Cloudbase.Request(\"GET\", path, nil, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Querysuccessful:\", data)\n\treturn data, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := GetMySQLData(\"{%TABLE_NAME%}\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc AddMySQLData(tableName string, data map[string]interface{}) (interface{}, error) {\n\tpath := fmt.Sprintf(\"/v1/rdb/rest/%s\", tableName)\n\tresult, err := Cloudbase.Request(\"POST\", path, data, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Insert successful:\", result)\n\treturn result, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := AddMySQLData(\"{%TABLE_NAME%}\", map[string]interface{}{\n\t\t\"title\": \"Example Title\",\n\t})\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc UpdateMySQLData(tableName, dataID string, data map[string]interface{}) (interface{}, error) {\n\tpath := fmt.Sprintf(\"/v1/rdb/rest/%s?id=eq.%s\", tableName, dataID)\n\tresult, err := Cloudbase.Request(\"PATCH\", path, data, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Update successful:\", result)\n\treturn result, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := UpdateMySQLData(\"{%TABLE_NAME%}\", \"<data id>\", map[string]interface{}{\n\t\t\"title\": \"New Title\",\n\t})\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc DeleteMySQLData(tableName, dataID string) (bool, error) {\n\tpath := fmt.Sprintf(\"/v1/rdb/rest/%s?id=eq.%s\", tableName, dataID)\n\t_, err := Cloudbase.Request(\"DELETE\", path, nil, nil)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfmt.Println(\"Delete successful\")\n\treturn true, nil\n}\n\n// Usage Example\nfunc main() {\n\tsuccess, err := DeleteMySQLData(\"{%TABLE_NAME%}\", \"<data id>\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\tfmt.Println(\"DeleteResult:\", success)\n}\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc GetModelData(modelName, envType string) ([]interface{}, error) {\n\tif envType == \"\" {\n\t\tenvType = \"prod\"\n\t}\n\n\tpath := fmt.Sprintf(\"/v1/model/%s/%s/list\", envType, modelName)\n\tpayload := map[string]interface{}{\n\t\t\"pageSize\":   10,\n\t\t\"pageNumber\": 1,\n\t\t\"getCount\":   true,\n\t}\n\n\tresult, err := Cloudbase.Request(\"POST\", path, payload, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resultMap, ok := result.(map[string]interface{}); ok {\n\t\tif data, ok := resultMap[\"data\"].(map[string]interface{}); ok {\n\t\t\tif records, ok := data[\"records\"].([]interface{}); ok {\n\t\t\t\tfmt.Println(\"Querysuccessful:\", records)\n\t\t\t\treturn records, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn []interface{}{}, nil\n}\n\n// Usage Example\nfunc main() {\n\trecords, err := GetModelData(\"{%TABLE_NAME%}\", \"prod\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc AddModelData(modelName string, data map[string]interface{}, envType string) (interface{}, error) {\n\tif envType == \"\" {\n\t\tenvType = \"prod\"\n\t}\n\n\tpath := fmt.Sprintf(\"/v1/model/%s/%s/create\", envType, modelName)\n\tpayload := map[string]interface{}{\n\t\t\"data\": data,\n\t}\n\n\tresult, err := Cloudbase.Request(\"POST\", path, payload, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resultMap, ok := result.(map[string]interface{}); ok {\n\t\tif dataMap, ok := resultMap[\"data\"].(map[string]interface{}); ok {\n\t\t\tif docID, ok := dataMap[\"id\"].(string); ok {\n\t\t\t\tfmt.Printf(\"Insert successful! id: %s\\n\", docID)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := AddModelData(\"{%TABLE_NAME%}\", map[string]interface{}{\n\t\t\"title\": \"Example Title\",\n\t}, \"prod\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc UpdateModelData(modelName, dataID string, data map[string]interface{}, envType string) (bool, error) {\n\tif envType == \"\" {\n\t\tenvType = \"prod\"\n\t}\n\n\tpath := fmt.Sprintf(\"/v1/model/%s/%s/update\", envType, modelName)\n\tpayload := map[string]interface{}{\n\t\t\"data\": data,\n\t\t\"filter\": map[string]interface{}{\n\t\t\t\"where\": map[string]interface{}{\n\t\t\t\t\"_id\": map[string]interface{}{\n\t\t\t\t\t\"$eq\": dataID,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err := Cloudbase.Request(\"PUT\", path, payload, nil)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfmt.Println(\"Update successful!\")\n\treturn true, nil\n}\n\n// Usage Example\nfunc main() {\n\tsuccess, err := UpdateModelData(\"{%TABLE_NAME%}\", \"<data id>\", map[string]interface{}{\n\t\t\"title\": \"New Title\",\n\t}, \"prod\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc DeleteModelData(modelName, dataID, envType string) (bool, error) {\n\tif envType == \"\" {\n\t\tenvType = \"prod\"\n\t}\n\n\tpath := fmt.Sprintf(\"/v1/model/%s/%s/delete\", envType, modelName)\n\tpayload := map[string]interface{}{\n\t\t\"filter\": map[string]interface{}{\n\t\t\t\"where\": map[string]interface{}{\n\t\t\t\t\"_id\": map[string]interface{}{\n\t\t\t\t\t\"$eq\": dataID,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err := Cloudbase.Request(\"POST\", path, payload, nil)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfmt.Println(\"Delete successful!\")\n\treturn true, nil\n}\n\n// Usage Example\nfunc main() {\n\tsuccess, err := DeleteModelData(\"{%TABLE_NAME%}\", \"<data id>\", \"prod\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc CallFunction(functionName string, data map[string]interface{}) (interface{}, error) {\n\tif data == nil {\n\t\tdata = map[string]interface{}{}\n\t}\n\n\tpath := fmt.Sprintf(\"/v1/functions/%s\", functionName)\n\tresult, err := Cloudbase.Request(\"POST\", path, data, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Cloud function call result:\", result)\n\treturn result, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := CallFunction(\"{%FUNCTION_NAME%}\", nil)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
            "index": 3,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\nfunc CallContainer(serviceName, path, method string, data map[string]interface{}) (interface{}, error) {\n\tif method == \"\" {\n\t\tmethod = \"GET\"\n\t}\n\n\tfullPath := fmt.Sprintf(\"/v1/cloudrun/%s/%s\", serviceName, path)\n\tfullPath = strings.TrimSuffix(fullPath, \"/\")\n\n\tresult, err := Cloudbase.Request(strings.ToUpper(method), fullPath, data, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Cloud RunCallResult:\", result)\n\treturn result, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := CallContainer(\"{%SERVICE_NAME%}\", \"\", \"GET\", nil)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
            "index": 4,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"time\"\n)\n\nfunc UploadFile(filePath, objectID string) (map[string]interface{}, error) {\n\tif objectID == \"\" {\n\t\tfilename := filepath.Base(filePath)\n\t\ttimestamp := time.Now().UnixMilli()\n\t\tobjectID = fmt.Sprintf(\"uploads/%d-%s\", timestamp, filename)\n\t}\n\n\tuploadInfo, err := Cloudbase.Request(\"POST\", \"/v1/storages/get-objects-upload-info\",\n\t\t[]map[string]interface{}{{\"objectId\": objectID}}, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinfoList, ok := uploadInfo.([]interface{})\n\tif !ok || len(infoList) == 0 {\n\t\treturn nil, fmt.Errorf(\"Get upload infofailed\")\n\t}\n\n\tinfo := infoList[0].(map[string]interface{})\n\tuploadURL := info[\"uploadUrl\"].(string)\n\n\tfile, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"filedoes not exist: %s\", filePath)\n\t}\n\tdefer file.Close()\n\n\tfileData, err := io.ReadAll(file)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Readfilefailed: %w\", err)\n\t}\n\n\treq, err := http.NewRequest(\"PUT\", uploadURL, bytes.NewReader(fileData))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Set(\"Authorization\", info[\"authorization\"].(string))\n\treq.Header.Set(\"X-Cos-Security-Token\", info[\"token\"].(string))\n\treq.Header.Set(\"X-Cos-Meta-Fileid\", info[\"cloudObjectMeta\"].(string))\n\n\tclient := &http.Client{}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fileUploadfailed: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\treturn nil, fmt.Errorf(\"Uploadfailed，status code: %d\", resp.StatusCode)\n\t}\n\n\tresult := map[string]interface{}{\n\t\t\"cloudObjectId\": info[\"cloudObjectId\"],\n\t\t\"downloadUrl\":   info[\"downloadUrl\"],\n\t\t\"objectId\":      objectID,\n\t}\n\n\tfmt.Println(\"fileUpload successful:\")\n\tfmt.Printf(\"- Object ID: %s\\n\", result[\"objectId\"])\n\tfmt.Printf(\"- DownloadURL: %s\\n\", result[\"downloadUrl\"])\n\n\treturn result, nil\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := UploadFile(\"./example.jpg\", \"\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc GetFileURL(cloudObjectID string) (string, error) {\n\tresult, err := Cloudbase.Request(\"POST\", \"/v1/storages/get-objects-download-info\",\n\t\t[]map[string]interface{}{{\"cloudObjectId\": cloudObjectID}}, nil)\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif resultList, ok := result.([]interface{}); ok && len(resultList) > 0 {\n\t\tif info, ok := resultList[0].(map[string]interface{}); ok {\n\t\t\tif downloadURL, ok := info[\"downloadUrl\"].(string); ok {\n\t\t\t\tfmt.Println(\"fileURL:\", downloadURL)\n\t\t\t\treturn downloadURL, nil\n\t\t\t}\n\t\t}\n\t}\n\n\treturn \"\", fmt.Errorf(\"Get File URLfailed\")\n}\n\n// Usage Example\nfunc main() {\n\tfileURL, err := GetFileURL(\"cloud://xxx.png\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\nfunc DownloadFile(cloudObjectID, savePath string) (bool, error) {\n\tif savePath == \"\" {\n\t\tsavePath = \"./\"\n\t}\n\n\tresult, err := Cloudbase.Request(\"POST\", \"/v1/storages/get-objects-download-info\",\n\t\t[]map[string]interface{}{{\"cloudObjectId\": cloudObjectID}}, nil)\n\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tif resultList, ok := result.([]interface{}); ok && len(resultList) > 0 {\n\t\tif info, ok := resultList[0].(map[string]interface{}); ok {\n\t\t\tdownloadURL := info[\"downloadUrl\"].(string)\n\n\t\t\tparts := strings.Split(downloadURL, \"/\")\n\t\t\tfilename := strings.Split(parts[len(parts)-1], \"?\")[0]\n\n\t\t\tfileInfo, err := os.Stat(savePath)\n\t\t\tvar fullPath string\n\t\t\tif err == nil && fileInfo.IsDir() || strings.HasSuffix(savePath, \"/\") {\n\t\t\t\tfullPath = filepath.Join(savePath, filename)\n\t\t\t} else {\n\t\t\t\tfullPath = savePath\n\t\t\t}\n\n\t\t\tresp, err := http.Get(downloadURL)\n\t\t\tif err != nil {\n\t\t\t\treturn false, fmt.Errorf(\"Downloadfailed: %w\", err)\n\t\t\t}\n\t\t\tdefer resp.Body.Close()\n\n\t\t\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\t\t\treturn false, fmt.Errorf(\"Downloadfailed，status code: %d\", resp.StatusCode)\n\t\t\t}\n\n\t\t\toutFile, err := os.Create(fullPath)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\t\t\tdefer outFile.Close()\n\n\t\t\t_, err = io.Copy(outFile, resp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn false, err\n\t\t\t}\n\n\t\t\tfmt.Printf(\"Downloadsuccessful! filesaved to: %s\\n\", fullPath)\n\t\t\treturn true, nil\n\t\t}\n\t}\n\n\treturn false, fmt.Errorf(\"Downloadfailed\")\n}\n\n// Usage Example\nfunc main() {\n\t// Downloadto current directory，Useoriginalfilename\n\tsuccess, err := DownloadFile(\"cloud://xxx.png\", \"\")\n\n\t// Downloadto specified directory\n\t// success, err := DownloadFile(\"cloud://xxx.png\", \"./downloads/\")\n\n\t// Downloadand rename\n\t// success, err := DownloadFile(\"cloud://xxx.png\", \"./my-image.png\")\n\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc DeleteFile(cloudObjectIDs interface{}) (bool, error) {\n\tvar data []map[string]interface{}\n\n\tswitch v := cloudObjectIDs.(type) {\n\tcase string:\n\t\tdata = []map[string]interface{}{{\"cloudObjectId\": v}}\n\tcase []string:\n\t\tfor _, id := range v {\n\t\t\tdata = append(data, map[string]interface{}{\"cloudObjectId\": id})\n\t\t}\n\tdefault:\n\t\treturn false, fmt.Errorf(\"Not supportedparameterType\")\n\t}\n\n\t_, err := Cloudbase.Request(\"POST\", \"/v1/storages/delete-objects\", data, nil)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\n\tfmt.Println(\"Delete successful!\")\n\treturn true, nil\n}\n\n// Usage Example\nfunc main() {\n\tsuccess, err := DeleteFile(\"cloud://xxx.png\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```go\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n)\n\nfunc StreamText(model, subModel string, messages []map[string]string) (string, error) {\n\tpayload := map[string]interface{}{\n\t\t\"model\":    subModel,\n\t\t\"messages\": messages,\n\t\t\"stream\":   true,\n\t}\n\n\tjsonData, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\turl := fmt.Sprintf(\"%s/v1/ai/%s/chat/completions\", Cloudbase.BaseURL, model)\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonData))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"text/event-stream\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+Cloudbase.AccessToken)\n\n\tresp, err := Cloudbase.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"AI Call failed: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tfmt.Println(\"AI Streaming response:\")\n\tfullContent := \"\"\n\tscanner := bufio.NewScanner(resp.Body)\n\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tif strings.HasPrefix(line, \"data: \") {\n\t\t\tdataStr := strings.TrimPrefix(line, \"data: \")\n\t\t\tif strings.TrimSpace(dataStr) != \"[DONE]\" {\n\t\t\t\tvar chunkData map[string]interface{}\n\t\t\t\tif err := json.Unmarshal([]byte(dataStr), &chunkData); err == nil {\n\t\t\t\t\tif choices, ok := chunkData[\"choices\"].([]interface{}); ok && len(choices) > 0 {\n\t\t\t\t\t\tif choice, ok := choices[0].(map[string]interface{}); ok {\n\t\t\t\t\t\t\tif delta, ok := choice[\"delta\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\t\tif content, ok := delta[\"content\"].(string); ok {\n\t\t\t\t\t\t\t\t\tfmt.Print(content)\n\t\t\t\t\t\t\t\t\tfullContent += content\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println()\n\treturn fullContent, nil\n}\n\n// Usage Example\nfunc main() {\n\tresponse, err := StreamText(\n\t\t\"{%AI_MODEL_NAME%}\",\n\t\t\"{%AI_SUB_MODEL_NAME%}\",\n\t\t[]map[string]string{\n\t\t\t{\"role\": \"system\", \"content\": \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\"},\n\t\t\t{\"role\": \"user\", \"content\": \"Spring\"},\n\t\t},\n\t)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```go\npackage main\n\nimport \"fmt\"\n\nfunc GenerateImage(prompt string) (map[string]interface{}, error) {\n\t// PrepareCallparameter\n\tdata := map[string]interface{}{\n\t\t\"prompt\": prompt,\n\t}\n\n\t// CallCloud FunctionGenerate Image\n\tresult, err := Cloudbase.Request(\"POST\", \"/v1/functions/<YOUR_FUNCTION_NAME>\", data, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resultMap, ok := result.(map[string]interface{}); ok {\n\t\tif success, ok := resultMap[\"success\"].(bool); ok && success {\n\t\t\timageUrl := resultMap[\"imageUrl\"].(string)\n\t\t\trevisedPrompt := \"\"\n\t\t\tif rp, ok := resultMap[\"revised_prompt\"].(string); ok {\n\t\t\t\trevisedPrompt = rp\n\t\t\t}\n\n\t\t\tfmt.Println(\"Generation successful!\")\n\t\t\tfmt.Printf(\"Image URL: %s\\n\", imageUrl)\n\t\t\tfmt.Printf(\"Optimized prompt: %s\\n\", revisedPrompt)\n\t\t\tfmt.Println(\"Note: Image URLValidis valid for24hours\")\n\n\t\t\treturn resultMap, nil\n\t\t} else {\n\t\t\tcode := \"\"\n\t\t\tmessage := \"\"\n\t\t\tif c, ok := resultMap[\"code\"].(string); ok {\n\t\t\t\tcode = c\n\t\t\t}\n\t\t\tif m, ok := resultMap[\"message\"].(string); ok {\n\t\t\t\tmessage = m\n\t\t\t}\n\t\t\treturn nil, fmt.Errorf(\"Generation failed: %s - %s\", code, message)\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"Requestfailed\")\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := GenerateImage(\"A cute cat playing in the sunshine\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t} else {\n\t\tfmt.Println(\"ImageGenerateDone:\", result)\n\t}\n}\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```go\n/*\nGo Call Agent Example (AG-UI Protocol)\nProtocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n*/\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n)\n\n// Message AG-UI protocolMessagestructure\ntype Message struct {\n\tID      string `json:\"id\"`\n\tRole    string `json:\"role\"`\n\tContent string `json:\"content\"`\n}\n\n// AGUIRequest AG-UI protocolRequestbody\ntype AGUIRequest struct {\n\tMessages       []Message              `json:\"messages\"`                 // Required: Message list\n\tThreadID       string                 `json:\"threadId,omitempty\"`       // Optional: Session ID for multi-turn conversation\n\tRunID          string                 `json:\"runId,omitempty\"`          // Optional: Run ID for execution tracking\n\tTools          []interface{}          `json:\"tools,omitempty\"`          // Optional: Frontend tool definitions\n\tContext        []interface{}          `json:\"context,omitempty\"`        // Optional: Context information\n\tForwardedProps map[string]interface{} `json:\"forwardedProps,omitempty\"` // Optional: Pass-through parameters\n}\n\nfunc ChatWithAgentStream(botID, msg string, history []Message) (string, error) {\n\tif history == nil {\n\t\thistory = []Message{}\n\t}\n\n\turl := fmt.Sprintf(\"%s/v1/aibot/bots/%s/send-message\", Cloudbase.BaseURL, botID)\n\n\t// Build message list (AG-UI protocol format)\n\tmessages := make([]Message, 0, len(history)+1)\n\n\t// AddHistoryMessage\n\tmessages = append(messages, history...)\n\n\t// AddCurrentuserMessage\n\tmessages = append(messages, Message{\n\t\tID:      fmt.Sprintf(\"msg-%s\", uuid.New().String()),\n\t\tRole:    \"user\",\n\t\tContent: msg,\n\t})\n\n\t// AG-UI protocolRequestbody\n\tpayload := AGUIRequest{\n\t\tMessages:       messages,\n\t\tThreadID:       fmt.Sprintf(\"thread-%s\", uuid.New().String()),\n\t\tRunID:          fmt.Sprintf(\"run-%s\", uuid.New().String()),\n\t\tTools:          []interface{}{},\n\t\tContext:        []interface{}{},\n\t\tForwardedProps: map[string]interface{}{},\n\t}\n\n\tjsonData, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonData))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"text/event-stream\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+Cloudbase.AccessToken)\n\n\tclient := &http.Client{Timeout: 30 * time.Second}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"AI Call failed: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tfmt.Println(\"AI Streaming response:\")\n\tfullContent := \"\"\n\tscanner := bufio.NewScanner(resp.Body)\n\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\t\tif strings.HasPrefix(line, \"data: \") {\n\t\t\tdataStr := strings.TrimSpace(strings.TrimPrefix(line, \"data: \"))\n\t\t\tif dataStr != \"\" && dataStr != \"[DONE]\" {\n\t\t\t\tvar chunkData map[string]interface{}\n\t\t\t\tif err := json.Unmarshal([]byte(dataStr), &chunkData); err == nil {\n\t\t\t\t\tvar content string\n\t\t\t\t\tif c, ok := chunkData[\"content\"].(string); ok {\n\t\t\t\t\t\tcontent = c\n\t\t\t\t\t} else if choices, ok := chunkData[\"choices\"].([]interface{}); ok && len(choices) > 0 {\n\t\t\t\t\t\tif choice, ok := choices[0].(map[string]interface{}); ok {\n\t\t\t\t\t\t\tif delta, ok := choice[\"delta\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\t\tif c, ok := delta[\"content\"].(string); ok {\n\t\t\t\t\t\t\t\t\tcontent = c\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if message, ok := choice[\"message\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\t\tif c, ok := message[\"content\"].(string); ok {\n\t\t\t\t\t\t\t\t\tcontent = c\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif content != \"\" {\n\t\t\t\t\t\tfmt.Print(content)\n\t\t\t\t\t\tfullContent += content\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println()\n\treturn fullContent, nil\n}\n\n// Usage Example\nfunc main() {\n\tresponse, err := ChatWithAgentStream(\"{%AGENT_ID%}\", \"Who are you\", nil)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n\t_ = response\n}\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```go\npackage main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n)\n\nfunc ChatWithAgentStream(botID, msg string, history []map[string]string) (string, error) {\n\tif history == nil {\n\t\thistory = []map[string]string{}\n\t}\n\n\turl := fmt.Sprintf(\"%s/v1/aibot/bots/%s/send-message\", Cloudbase.BaseURL, botID)\n\tpayload := map[string]interface{}{\n\t\t\"history\": history,\n\t\t\"msg\":     msg,\n\t}\n\n\tjsonData, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq, err := http.NewRequest(\"POST\", url, bytes.NewBuffer(jsonData))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"text/event-stream\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+Cloudbase.AccessToken)\n\n\tclient := &http.Client{Timeout: 30 * time.Second}\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"AI Call failed: %w\", err)\n\t}\n\tdefer resp.Body.Close()\n\n\tfmt.Println(\"AI Streaming response:\")\n\tfullContent := \"\"\n\tscanner := bufio.NewScanner(resp.Body)\n\n\tfor scanner.Scan() {\n\t\tline := strings.TrimSpace(scanner.Text())\n\t\tif strings.HasPrefix(line, \"data: \") {\n\t\t\tdataStr := strings.TrimSpace(strings.TrimPrefix(line, \"data: \"))\n\t\t\tif dataStr != \"\" && dataStr != \"[DONE]\" {\n\t\t\t\tvar chunkData map[string]interface{}\n\t\t\t\tif err := json.Unmarshal([]byte(dataStr), &chunkData); err == nil {\n\t\t\t\t\tvar content string\n\t\t\t\t\tif c, ok := chunkData[\"content\"].(string); ok {\n\t\t\t\t\t\tcontent = c\n\t\t\t\t\t} else if choices, ok := chunkData[\"choices\"].([]interface{}); ok && len(choices) > 0 {\n\t\t\t\t\t\tif choice, ok := choices[0].(map[string]interface{}); ok {\n\t\t\t\t\t\t\tif delta, ok := choice[\"delta\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\t\tif c, ok := delta[\"content\"].(string); ok {\n\t\t\t\t\t\t\t\t\tcontent = c\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if message, ok := choice[\"message\"].(map[string]interface{}); ok {\n\t\t\t\t\t\t\t\tif c, ok := message[\"content\"].(string); ok {\n\t\t\t\t\t\t\t\t\tcontent = c\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tif content != \"\" {\n\t\t\t\t\t\tfmt.Print(content)\n\t\t\t\t\t\tfullContent += content\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfmt.Println()\n\treturn fullContent, nil\n}\n\n// Usage Example\nfunc main() {\n\tresponse, err := ChatWithAgentStream(\"{%AGENT_ID%}\", \"Who are you\", nil)\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "markdown": "```go\npackage main\n\nimport \"fmt\"\n\nfunc SignIn(username, password string) (map[string]interface{}, error) {\n\tresult, err := Cloudbase.Request(\"POST\", \"/auth/v1/signin\",\n\t\tmap[string]interface{}{\n\t\t\t\"username\": username,\n\t\t\t\"password\": password,\n\t\t}, nil)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif resultMap, ok := result.(map[string]interface{}); ok {\n\t\taccessToken := resultMap[\"access_token\"].(string)\n\t\tuserID := resultMap[\"sub\"].(string)\n\n\t\tfmt.Printf(\"Login successful! User ID: %s\\n\", userID)\n\t\tfmt.Printf(\"Access token: %s...\\n\", accessToken[:20])\n\t\treturn resultMap, nil\n\t}\n\n\treturn nil, fmt.Errorf(\"Login failed\")\n}\n\n// Usage Example\nfunc main() {\n\tresult, err := SignIn(\"your_username\", \"your_password\")\n\tif err != nil {\n\t\tfmt.Println(\"Error:\", err)\n\t}\n}\n```",
            "index": 8,
            "id": "identity",
            "title": "Authentication"
          }
        ]
      }
    ],
    "_id": "b1ab49d269a9286d0043c26728724ecb",
    "_openid": "anon",
    "createdAt": 1769744599204,
    "updatedAt": 1769766697057
  },
  {
    "category": "Framework Integration,Backend Frameworks,Node.js",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 8,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/api-reference/server/node-sdk/initialization",
    "content": [
      {
        "markdown": "`@cloudbase/node-sdk` allows you toin Node.js serverUse JavaScript/TypeScript access CloudBase services and resources。",
        "index": 1,
        "title": "Install SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```bash\nnpm i @cloudbase/node-sdk dotenv\n```",
            "index": 1,
            "title": "npm"
          },
          {
            "markdown": "```bash\nyarn add @cloudbase/node-sdk dotenv\n```",
            "index": 2,
            "title": "yarn"
          },
          {
            "markdown": "```bash\npnpm add @cloudbase/node-sdk dotenv\n```",
            "index": 3,
            "title": "pnpm"
          }
        ]
      },
      {
        "markdown": "Add the following code to your Node.js project",
        "index": 2,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nconst cloudbaseSDK = require(\"@cloudbase/node-sdk\");\nrequire(\"dotenv\").config();\n\nconst cloudbase = cloudbaseSDK.init({\n  env: process.env.CLOUDBASE_ENV_ID,\n  secretId: process.env.CLOUDBASE_SECRETID,\n  secretKey: process.env.CLOUDBASE_SECRETKEY\n});\n\nmodule.exports = { cloudbase };\n```",
            "index": 1,
            "title": "./utils/cloudbase.js"
          },
          {
            "markdown": "<div class=\"tea-alert tea-alert--brand\" style=\"padding:9px calc(var(--tea-space-100)*4)\">\n<div class=\"tea-alert__info\">\nplease go to <a target=\"_blank\"  class=\"tea-link-external\"  style =\"text-decoration:underline\" href=\"https://console.cloud.tencent.com/cam/capi\">Tencent Cloud Console/APIkey management</a> GenerateAPIkey\n</div>\n</div>\n\n```properties\n# Environment ID\nCLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Tencent CloudAPIkeyID\nCLOUDBASE_SECRET_ID={%SECRET_ID%}\n\n# Tencent CloudAPIkeyKey\nCLOUDBASE_SECRET_KEY={%SECRET_KEY%}\n```",
            "index": 2,
            "title": ".env"
          }
        ]
      },
      {
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function getData() {\n  // Query {%TABLE_NAME%} table first 10 records\n  const { data, error } = await cloudbase\n    .rdb()\n    .from(\"{%TABLE_NAME%}\")\n    .select(\"*\")\n    .limit(10);\n\n  if (!error) {\n    console.log(\"Querysuccessful:\", data);\n    return data;\n  } else {\n    console.error(\"Queryfailed:\", error);\n  }\n}\n\ngetData();\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function addData() {\n  // Add {%TABLE_NAME%} table data\n  const { data, error } = await cloudbase\n    .rdb()\n    .from(\"{%TABLE_NAME%}\")\n    .insert({ title: \"Example Title\" });\n\n  if (!error) {\n    console.log(\"Insert successful:\", data);\n  } else {\n    console.error(\"Insert failed:\", error);\n  }\n}\n\naddData();\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function updateData() {\n  // Update {%TABLE_NAME%} table id with specified value\n  const { data, error } = await cloudbase\n    .rdb()\n    .from(\"{%TABLE_NAME%}\")\n    .update({ title: \"New Title\" })\n    .eq(\"id\", \"<data id>\");\n\n  if (!error) {\n    console.log(\"Update successful:\", data);\n  } else {\n    console.error(\"Update failed:\", error);\n  }\n}\n\nupdateData();\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function upsertData() {\n  // If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\n  const { data, error } = await cloudbase\n    .rdb()\n    .from(\"{%TABLE_NAME%}\")\n    .upsert({ id: 1, title: \"Example Title\" });\n\n  if (!error) {\n    console.log(\"Operation successful:\", data);\n  } else {\n    console.error(\"Operation failed:\", error);\n  }\n}\n\nupsertData();\n```",
                "index": 4,
                "title": "Upsert Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function deleteData() {\n  // Delete {%TABLE_NAME%} table id with specified value\n  const { data, error } = await cloudbase\n    .rdb()\n    .from(\"{%TABLE_NAME%}\")\n    .delete()\n    .eq(\"id\", \"<data id>\");\n\n  if (!error) {\n    console.log(\"Delete successful:\", data);\n  } else {\n    console.error(\"Delete failed:\", error);\n  }\n}\n\ndeleteData();\n```",
                "index": 5,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function getData() {\n  // Query {%TABLE_NAME%} table first 10 records\n  const db = cloudbase.database();\n  const res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n\n  console.log(\"Querysuccessful:\", res.data);\n  return res.data;\n}\n\ngetData();\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function addData() {\n  try {\n    // Add {%TABLE_NAME%} table data\n    const db = cloudbase.database();\n    const res = await db\n      .collection(\"{%TABLE_NAME%}\")\n      .add({ title: \"Example Title\" });\n\n    console.log(`Insert successful! id: ${res.id}`);\n  } catch (error) {\n    console.error(\"Insert failed:\", error);\n  }\n}\n\naddData();\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function updateData() {\n  try {\n    // Update {%TABLE_NAME%} table id with specified value\n    const db = cloudbase.database();\n    await db\n      .collection(\"{%TABLE_NAME%}\")\n      .doc(\"<data id>\")\n      .update({ title: \"New Title\" });\n\n    console.log(\"Update successful!\");\n  } catch (error) {\n    console.error(\"Update failed:\", error);\n  }\n}\n\nupdateData();\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function deleteData() {\n  try {\n    // Delete {%TABLE_NAME%} table id with specified value\n    const db = cloudbase.database();\n    await db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").remove();\n\n    console.log(\"Delete successful!\");\n  } catch (error) {\n    console.error(\"Delete failed:\", error);\n  }\n}\n\ndeleteData();\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function getData() {\n  // Query {%TABLE_NAME%} Data Modelbefore10recordsData\n  const res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n    pageNumber: 1,\n    pagesize: 10\n  });\n\n  console.log(\"Querysuccessful:\", res.data?.records);\n  return res.data?.records;\n}\n\ngetData();\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function addData() {\n  try {\n    // Add {%TABLE_NAME%} Data ModelData\n    const res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n      data: { title: \"Example Title\" }\n    });\n\n    console.log(`Insert successful! id: ${res.data.id}`);\n  } catch (error) {\n    console.error(\"Insert failed:\", error);\n  }\n}\n\naddData();\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function updateData() {\n  try {\n    // Update {%TABLE_NAME%} Data Model _id with specified value\n    await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n      data: { title: \"New Title\" },\n      filter: { where: { _id: { $eq: \"<data id>\" } } }\n    });\n\n    console.log(\"Update successful!\");\n  } catch (error) {\n    console.error(\"Update failed:\", error);\n  }\n}\n\nupdateData();\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function deleteData() {\n  try {\n    // Delete {%TABLE_NAME%} Data Model _id with specified value\n    await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n      filter: { where: { _id: { $eq: \"<data id>\" } } }\n    });\n\n    console.log(\"Delete successful!\");\n  } catch (error) {\n    console.error(\"Delete failed:\", error);\n  }\n}\n\ndeleteData();\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function callFunction() {\n  // Call {%FUNCTION_NAME%} Cloud Function\n  const res = await cloudbase.callFunction({\n    name: \"{%FUNCTION_NAME%}\",\n    data: {}\n  });\n\n  console.log(\"Cloud FunctionReturn:\", res.result);\n  return res.result;\n}\n\ncallFunction();\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function callRun() {\n  // Call {%SERVICE_NAME%} Cloud Runservice\n  const res = await cloudbase.callContainer({\n    name: \"{%SERVICE_NAME%}\"\n    method: 'POST',\n    path: '/',\n    header:{\n      'Content-Type': 'application/json; charset=utf-8'\n    },\n    data: {},\n  });\n}\n\ncallRun();\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 6,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\nconst fs = require(\"fs\");\n\nasync function uploadFile() {\n  const filePath = \"./example.png\"; // localfilePath\n  const cloudPath = `images/${Date.now()}-example.png`; // Path to upload in cloud\n\n  const res = await cloudbase.uploadFile({\n    cloudPath: cloudPath,\n    fileContent: fs.createReadStream(filePath)\n  });\n\n  console.log(\"Upload successful:\", res.fileID);\n  return res.fileID;\n}\n\nuploadFile();\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function getFileUrl() {\n  const res = await cloudbase.getTempFileURL({\n    fileList: [\"cloud://xxx.png\"] // File fileID list\n  });\n\n  console.log(\"fileURL:\", res.fileList[0].tempFileURL);\n  return res.fileList[0].tempFileURL;\n}\n\ngetFileUrl();\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\nconst fs = require(\"fs\");\n\nasync function downloadFile() {\n  const res = await cloudbase.downloadFile({\n    fileID: \"cloud://xxx.png\" // File fileID\n  });\n\n  // willfileSave to local\n  fs.writeFileSync(\"./downloaded-file.png\", res.fileContent);\n  console.log(\"Downloadsuccessful!\");\n}\n\ndownloadFile();\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function deleteFile() {\n  const res = await cloudbase.deleteFile({\n    fileList: [\"cloud://xxx.png\"] // File fileID list\n  });\n\n  if (res.fileList[0].code === \"SUCCESS\") {\n    console.log(\"Delete successful!\");\n  } else {\n    console.error(\"Delete failed:\", res.fileList);\n  }\n}\n\ndeleteFile();\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function callAIModel(input) {\n  const ai = cloudbase.ai();\n  const model = ai.createModel(\"{%AI_MODEL_NAME%}\");\n  await auth.signInAnonymously();\n\n  try {\n    console.log(\"currentlyinGeneratepoem...\");\n    const res = await model.streamText({\n      model: \"{%AI_SUB_MODEL_NAME%}\",\n      messages: [\n        {\n          role: \"system\",\n          content:\n            \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\"\n        },\n        { role: \"user\", content: input }\n      ]\n    });\n\n    let response = \"\";\n    for await (let str of res.textStream) {\n      process.stdout.write(str);\n      response += str;\n    }\n    console.log(\"\\nGenerateDone！\");\n    return response;\n  } catch (err) {\n    console.error(\"poemGeneration failed:\", err);\n    return null;\n  }\n}\n\n// CallExample\ncallAIModel(\"Spring\");\n```",
                "index": 1,
                "title": "SDKCall",
                "content": []
              },
              {
                "markdown": "<div class=\"tea-alert tea-alert--brand\" style=\"padding:9px calc(var(--tea-space-100)*4)\">\n<div class=\"tea-alert__info\">\ngo to <a target=\"_blank\" class=\"tea-link-external\" style=\"text-decoration:underline\" href=\"https://tcb.cloud.tencent.com/dev#/env/apikey\">EnvironmentConfiguration</a> Getserver API Key。\n</div>\n</div>\n\n**Install Dependencies**\n\n```bash\nnpm i @langchain/openai\n```\n\n**Usage Example：**\n\n```js\nconst { ChatOpenAI } = require(\"@langchain/openai\");\n\nconst model = new ChatOpenAI({\n  modelName: \"{%AI_SUB_MODEL_NAME%}\",\n  apiKey: \"<CLOUDBASE_API_KEY>\",\n  configuration: {\n    baseURL: \"https://{%ENV_ID%}.api.tcloudbasegateway.com/v1/ai/{%AI_MODEL_NAME%}/v1\"\n  }\n});\n\nasync function main() {\n  const response = await model.invoke(\"Hello\");\n  console.log(\"AIanswer:\", response.content);\n}\n\nmain();\n```",
                "index": 2,
                "title": "LangChain",
                "content": []
              },
              {
                "markdown": "<div class=\"tea-alert tea-alert--brand\" style=\"padding:9px calc(var(--tea-space-100)*4)\">\n<div class=\"tea-alert__info\">\ngo to <a target=\"_blank\" class=\"tea-link-external\" style=\"text-decoration:underline\" href=\"https://tcb.cloud.tencent.com/dev#/env/apikey\">EnvironmentConfiguration</a> Getserver API Key。\n</div>\n</div>\n\n**Install Dependencies**\n\n```bash\nnpm i openai\n```\n\n**Usage Example：**\n\n```js\nconst OpenAI = require(\"openai\");\n\nconst client = new OpenAI({\n  apiKey: \"<CLOUDBASE_API_KEY>\",\n  baseURL: \"https://{%ENV_ID%}.api.tcloudbasegateway.com/v1/ai/{%AI_MODEL_NAME%}/v1\"\n});\n\nasync function main() {\n  const completion = await client.chat.completions.create({\n    model: \"{%AI_SUB_MODEL_NAME%}\",\n    messages: [\n      { role: \"user\", content: \"hi\" }\n    ],\n    temperature: 0.3,\n    stream: true\n  });\n\n  for await (const chunk of completion) {\n    console.log(chunk);\n  }\n}\n\nmain();\n```",
                "index": 3,
                "title": "OpenAI SDK",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function generateImage() {\n  // Call image generation cloud function\n  const res = await cloudbase.callFunction({\n    name: \"<YOUR_FUNCTION_NAME>\",\n    data: {\n      prompt: \"A cute cat playing in the sunshine\"\n    }\n  });\n\n  const result = res.result;\n\n  if (result.success) {\n    // Generation successful\n    console.log(\"Generation successful!\");\n    console.log(\"Image URL:\", result.imageUrl);\n    console.log(\"Optimized prompt:\", result.revised_prompt);\n\n    // Use image\n    // Note: Image URL is valid for 24 hours, please save or transfer promptly\n  } else {\n    // Generation failed\n    console.error(\"Generation failed:\", result.code, result.message);\n  }\n}\n\ngenerateImage();\n```",
                "index": 4,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst { cloudbase } = require('./utils/cloudbase');\n\nasync function callAgent(input) {\n  const ai = cloudbase.ai();\n  await auth.signInAnonymously();\n\n  try {\n    console.log('currentlyinGenerateanswer...');\n    const res = await ai.bot.sendMessage({\n      botId: '{%AGENT_ID%}', // to replacefor yourAgentId\n      // Refer to frontend-backend communication protocol for input structure：\n      //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n      threadId: '550e8400-e29b-41d4-a716-446655440000',\n      runId: 'run_001',\n      messages: [\n        {\n          id: 'msg_001',\n          role: 'user',\n          content: 'Hello',\n        },\n      ],\n      tools: [],\n      context: [],\n      state: {},\n      forwardedProps: {},\n    });\n\n    let response = '';\n    for await (let str of res.textStream) {\n      process.stdout.write(str);\n      response += str;\n    }\n    console.log('\\nGenerateDone！');\n    return response;\n  } catch (err) {\n    console.error('Generation failed:', err);\n    return null;\n  }\n}\n\n// CallExample\ncallAgent('Who are you');\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```js\nconst { cloudbase } = require(\"./utils/cloudbase\");\n\nasync function callAgent(input) {\n  const ai = cloudbase.ai();\n  await auth.signInAnonymously();\n\n  try {\n    console.log(\"currentlyinGenerateanswer...\");\n    const res = await ai.bot.sendMessage({\n      botId: \"{%AGENT_ID%}\", // to replacefor yourAgentId\n      msg: input\n    });\n\n    let response = \"\";\n    for await (let str of res.textStream) {\n      process.stdout.write(str);\n      response += str;\n    }\n    console.log(\"\\nGenerateDone！\");\n    return response;\n  } catch (err) {\n    console.error(\"Generation failed:\", err);\n    return null;\n  }\n}\n\n// CallExample\ncallAgent(\"Who are you\");\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          }
        ]
      }
    ],
    "_id": "b1ab49d269a9286d0043c26d3d8cdd38",
    "_openid": "anon",
    "createdAt": 1769744602618,
    "updatedAt": 1770105393504
  },
  {
    "category": "CloudBase MCP,WeChat DevTools",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 120,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/wechat-devtools",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "<p style=\"margin-bottom: 0;font-weight: bold\">\nStep 1：Installation CodeBuddy extensions\n</p>\n<ol style=\"color: #00000080; font-size: 12px;margin-top: 0;margin-bottom: 8px;\">\n<li style=\"margin-top:0\">inWeChat DevToolsin，click the top menu bar「extensions」</li>\n<li style=\"margin-top:0\">Search in extension marketplace「CodeBuddy」</li>\n<li style=\"margin-top:0\">Installation「Tencent Cloud Code Assistant CodeBuddy」extensions\n</li>\n</ol>\n\n<p style=\"margin-bottom: 0;margin-top: 8px;font-weight: bold\">\nStep 2：Installation CloudBase MCP\n</p>\n<ol style=\"color: #00000080; font-size: 12px;margin-top: 0;\">\n<li style=\"margin-top:0\">InstallationAfter completion，infind in toolbarto CodeBuddy icon</li>\n<li style=\"margin-top:0\">Click the top-right CodeBuddy settings icon</li>\n<li style=\"margin-top:0\">in MCP marketplace searchandInstallation「CloudBase MCP」</li>\n</ol>",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b1ab49d269a9286e0043c277162f9580",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,WindSurf",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 17,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/windsurf",
    "content": [
      {
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.windsurf/mcp.json`: \n```json\n{\n  \"mcpServers\": {\n    \"cloudbase\": {\n      \"command\": \"npx\",\n      \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n      \"env\": {\n        \"INTEGRATION_IDE\": \"WindSurf\",\n        \"CLOUDBASE_MCP_PLUGINS_DISABLED\": \"interactive\"\n      }\n    }\n  }\n}\n```\n",
            "title": "Manual Configuration",
            "content": []
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be91357f6b66",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769757569583
  },
  {
    "category": "CloudBase MCP,Gemini CLI",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 9,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/gemini-cli",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.gemini/settings.json`:\n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Gemini\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be9276c995c4",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Google Antigravity",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 16,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/antigravity",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.agent/rules/`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Antigravity\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be933fcaa3c6",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,WeChat DevTools",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 0,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/wechat-devtools",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "<p style=\"margin-bottom: 0;font-weight: bold\">\nStep 1：Installation CodeBuddy extensions\n</p>\n<ol style=\"color: #00000080; font-size: 12px;margin-top: 0;margin-bottom: 8px;\">\n<li style=\"margin-top:0\">inWeChat DevToolsin，click the top menu bar「extensions」</li>\n<li style=\"margin-top:0\">Search in extension marketplace「CodeBuddy」</li>\n<li style=\"margin-top:0\">Installation「Tencent Cloud Code Assistant CodeBuddy」extensions\n</li>\n</ol>\n\n<p style=\"margin-bottom: 0;margin-top: 8px;font-weight: bold\">\nStep 2：Installation CloudBase MCP\n</p>\n<ol style=\"color: #00000080; font-size: 12px;margin-top: 0;\">\n<li style=\"margin-top:0\">InstallationAfter completion，infind in toolbarto CodeBuddy icon</li>\n<li style=\"margin-top:0\">Click the top-right CodeBuddy settings icon</li>\n<li style=\"margin-top:0\">in MCP marketplace searchandInstallation「CloudBase MCP」</li>\n</ol>",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be9473616b65",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Trae",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 6,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/trae",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.trae/mcp.json`:\n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Trae\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be956f0eb1c2",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Cursor",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 1,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/cursor",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.cursor/mcp.json`:\n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Cursor\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be9665901a4a",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,CodeBuddy",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 2,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/codebuddy",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "CodeBuddy IDE has built-in CloudBase MCP integration. We recommend using the configuration integration method first. [View BaaS integration documentation](https://www.codebuddy.ai/docs/zh/ide/User-guide/Integration)",
            "title": "Built-in Integration"
          },
          {
            "markdown": "For manual MCP configuration, please refer to [CodeBuddy Documentation](https://www.codebuddy.ai/docs/zh/ide/Config%20MCP) \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"CodeBuddyManual\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be972e6e40ad",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1770708765560
  },
  {
    "category": "CloudBase MCP,VSCode",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 5,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/github-copilot",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.vscode/mcp.json`:\n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"VSCode\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be984933c5e7",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Baidu Comate",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 8,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/baidu-comate",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.baidu-comate/mcp.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Comate\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be99797637cb",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,OpenAI Codex CLI",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 10,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/openai-codex-cli",
    "content": [
      {
        "docsUrl": "",
        "markdown": "**Prerequisites:** \n```bash\nnpm i @cloudbase/cloudbase-mcp -g\n```\n\nRun the following command in terminal based on your operating system:\n\n**MacOS, Linux, WSL:**\n```bash\ncodex mcp add cloudbase --env INTEGRATION_IDE=CodeX -- cloudbase-mcp\n```\n\n**Windows Powershell:**\n```bash\ncodex mcp add cloudbase --env INTEGRATION_IDE=CodeX -- cmd /c cloudbase-mcp\n```",
        "title": "Installation",
        "type": "",
        "content": []
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be9a52e141cf",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Augment Code",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 13,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/augment-code",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.vscode/settings.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Augment\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be9b540b278f",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,RooCode",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 12,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/roocode",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.roocode/mcp.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n\t \"disabled\": false,\n \"env\": {\n \"INTEGRATION_IDE\": \"RooCode\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be9c750adc4e",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,OpenCode",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 14,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/opencode",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.opencode.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"OpenCode\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be9d51f28b6f",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Claude Code",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 3,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/claude-code",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.mcp.json`:\n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"ClaudeCode\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be9e1b6e609d",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Qwen Code",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 11,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/qwen-code",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.qwen/settings.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Qwen\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036be9f7b2a5ab7",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Tongyi Lingma",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 7,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/tongyi-lingma",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "For manual MCP configuration, please refer to [Tongyi Lingmadocumentation](https://help.aliyun.com/zh/lingma/user-guide/guide-for-using-mcp) \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"LingMa\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036bea05616501e",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Kiro",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 19,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/kiro",
    "content": [
      {
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration toprojectdirectory `.kiro/settings/mcp.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Kiro\"\n }\n }\n }\n}\n```",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "tab",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036bea1050bb986",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Qoder",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 15,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/qoder",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `Qoder Settings > MCP`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Qorder\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036bea23df3204a",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,CodeBuddy Code",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 4,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/codebuddy-code",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "```bash\ncodebuddy mcp add --scope project cloudbase --env INTEGRATION_IDE=CodeBuddyCode -- npx @cloudbase/cloudbase-mcp@latest\n```",
            "title": "CLI Command"
          },
          {
            "markdown": "Add the following configuration to `.mcp.json`:\n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"CodeBuddyCode\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036bea32f735a8d",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Cline",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 18,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/cline",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.cline/mcp.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"autoApprove\": [],\n \"timeout\": 60,\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Cline\"\n },\n \"transportType\": \"stdio\",\n \"disabled\": false\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "b387ab55697c2e140036bea423ac7ff0",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "Framework Integration,MiniProgram / MiniGame,MiniGame,Cocos",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 3,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/api-reference/webv2/adapter",
    "content": [
      {
        "markdown": "`@cloudbase/js-sdk` Combine with `@cloudbase/adapter-cocos_native` allows you toin Cocos projectaccess CloudBase services and resources。",
        "index": 1,
        "title": "Install SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```bash\nnpm i @cloudbase/js-sdk @cloudbase/adapter-cocos_native\n```",
            "index": 1,
            "title": "npm",
            "content": []
          },
          {
            "markdown": "```bash\nyarn add @cloudbase/js-sdk @cloudbase/adapter-cocos_native\n```",
            "index": 2,
            "title": "yarn",
            "content": []
          },
          {
            "markdown": "```bash\npnpm add @cloudbase/js-sdk @cloudbase/adapter-cocos_native\n```",
            "index": 3,
            "title": "pnpm",
            "content": []
          }
        ]
      },
      {
        "markdown": "Add the following code to your Cocos project",
        "index": 2,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nimport cloudbaseSDK from \"@cloudbase/js-sdk\";\nimport adapter from \"@cloudbase/adapter-cocos_native\";\n\n// Registeradapter\ncloudbaseSDK.useAdapters(adapter);\n\nconst cloudbase = cloudbaseSDK.init({\n  // Environment ID\n  env: \"{%ENV_ID%}\",\n  // region\n  region: \"{%REGION%}\",\n  // Anonymous access token\n  accessKey: \"{%PUBLISHABLE_KEY%}\"\n});\n\nexport default cloudbase;\n```",
            "index": 1,
            "title": "scripts/services/CloudbaseService.js",
            "content": []
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Query {%TABLE_NAME%} table (limit 10 records)\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n\nconsole.log(\"Query result:\", data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Insert a record into {%TABLE_NAME%} table\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"New Post\", status: \"draft\" })\n  .select();\n\nconsole.log(\"Insert result:\", data);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Update record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ status: \"published\" })\n  .eq(\"id\", 1)\n  .select();\n\nconsole.log(\"Update result:\", data);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Upsert: update on conflict, otherwise insert\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Post Title\", status: \"published\" }, { onConflict: \"id\" })\n  .select();\n\nconsole.log(\"Upsert result:\", data);\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Delete record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", 1);\n\nconsole.log(\"Delete completed:\", error);\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('QueryData')\nexport class QueryData extends Component {\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onLoad() {\n    try {\n      const { data, error } = await cloudbase.database().from(\"{%TABLE_NAME%}\").select(\"*\").limit(10);\n\n      if (!error) {\n        this.resultLabel.string = `Querysuccessful：${JSON.stringify(data)}`;\n        console.log('QueryResult：', data);\n      } else {\n        this.resultLabel.string = 'Queryfailed';\n        console.error('Queryfailed：', error);\n      }\n    } catch (error) {\n      this.resultLabel.string = `Queryfailed: ${error.message}`;\n      console.error('Queryfailed：', error);\n    }\n  }\n}\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"Example Title\" });\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('AddData')\nexport class AddData extends Component {\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onAddButtonClick() {\n    const title = this.titleInput.string;\n    if (!title) {\n      this.resultLabel.string = 'Please enterTitle';\n      return;\n    }\n\n    try {\n      const { data, error } = await cloudbase.database().from(\"{%TABLE_NAME%}\").insert({ title });\n\n      if (!error) {\n        this.resultLabel.string = 'Insert successful';\n        this.titleInput.string = '';\n        console.log('Insert successful：', data);\n      } else {\n        this.resultLabel.string = 'Insert failed';\n        console.error('Insert failed：', error);\n      }\n    } catch (error) {\n      this.resultLabel.string = `Insert failed: ${error.message}`;\n      console.error('Insert failed：', error);\n    }\n  }\n}\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ title: \"New Title\" })\n  .eq(\"id\", dataId);\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('UpdateData')\nexport class UpdateData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onUpdateButtonClick() {\n    const dataId = this.idInput.string;\n    const newTitle = this.titleInput.string;\n\n    if (!dataId || !newTitle) {\n      this.resultLabel.string = 'Please enterDataIDandNew Title';\n      return;\n    }\n\n    try {\n      const { data, error } = await cloudbase.database().from(\"{%TABLE_NAME%}\").update({ title: newTitle }).eq(\"id\", dataId);\n\n      if (!error) {\n        this.resultLabel.string = 'Update successful';\n        this.idInput.string = '';\n        this.titleInput.string = '';\n        console.log('Update successful：', data);\n      } else {\n        this.resultLabel.string = 'Update failed';\n        console.error('Update failed：', error);\n      }\n    } catch (error) {\n      this.resultLabel.string = `Update failed: ${error.message}`;\n      console.error('Update failed：', error);\n    }\n  }\n}\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Title\" });\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('UpsertData')\nexport class UpsertData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onUpsertButtonClick() {\n    const id = parseInt(this.idInput.string);\n    const title = this.titleInput.string;\n\n    if (!id || !title) {\n      this.resultLabel.string = 'Please enterIDandTitle';\n      return;\n    }\n\n    try {\n      const { data, error } = await cloudbase.database().from(\"{%TABLE_NAME%}\").upsert({ id, title });\n\n      if (!error) {\n        this.resultLabel.string = 'Operation successful';\n        this.idInput.string = '';\n        this.titleInput.string = '';\n        console.log('Operation successful：', data);\n      } else {\n        this.resultLabel.string = 'Operation failed';\n        console.error('Operation failed：', error);\n      }\n    } catch (error) {\n      this.resultLabel.string = `Operation failed: ${error.message}`;\n      console.error('Operation failed：', error);\n    }\n  }\n}\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", dataId);\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('DeleteData')\nexport class DeleteData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onDeleteButtonClick() {\n    const dataId = this.idInput.string;\n\n    if (!dataId) {\n      this.resultLabel.string = 'Please entershouldDeleteDataID';\n      return;\n    }\n\n    try {\n      const { data, error } = await cloudbase.database().from(\"{%TABLE_NAME%}\").delete().eq(\"id\", dataId);\n\n      if (!error) {\n        this.resultLabel.string = 'Delete successful';\n        this.idInput.string = '';\n        console.log('Delete successful：', data);\n      } else {\n        this.resultLabel.string = 'Delete failed';\n        console.error('Delete failed：', error);\n      }\n    } catch (error) {\n      this.resultLabel.string = `Delete failed: ${error.message}`;\n      console.error('Delete failed：', error);\n    }\n  }\n}\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('QueryDocData')\nexport class QueryDocData extends Component {\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onLoad() {\n    try {\n      const db = cloudbase.database();\n      const res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n\n      this.resultLabel.string = `Querysuccessful：${JSON.stringify(res.data)}`;\n      console.log('QueryResult：', res.data);\n    } catch (error) {\n      this.resultLabel.string = `Queryfailed: ${error.message}`;\n      console.error('Queryfailed：', error);\n    }\n  }\n}\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({ title: \"Example Title\" });\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('AddDocData')\nexport class AddDocData extends Component {\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onAddButtonClick() {\n    const title = this.titleInput.string;\n    if (!title) {\n      this.resultLabel.string = 'Please enterTitle';\n      return;\n    }\n\n    try {\n      const db = cloudbase.database();\n      const res = await db.collection(\"{%TABLE_NAME%}\").add({ title });\n\n      this.resultLabel.string = `Insert successful! id: ${res.id}`;\n      this.titleInput.string = '';\n      console.log('Insert successful：', res);\n    } catch (error) {\n      this.resultLabel.string = `Insert failed: ${error.message}`;\n      console.error('Insert failed：', error);\n    }\n  }\n}\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(dataId).update({ title: \"New Title\" });\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('UpdateDocData')\nexport class UpdateDocData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onUpdateButtonClick() {\n    const dataId = this.idInput.string;\n    const newTitle = this.titleInput.string;\n\n    if (!dataId || !newTitle) {\n      this.resultLabel.string = 'Please enterDataIDandNew Title';\n      return;\n    }\n\n    try {\n      const db = cloudbase.database();\n      await db.collection(\"{%TABLE_NAME%}\").doc(dataId).update({ title: newTitle });\n\n      this.resultLabel.string = 'Update successful';\n      this.idInput.string = '';\n      this.titleInput.string = '';\n      console.log('Update successful');\n    } catch (error) {\n      this.resultLabel.string = `Update failed: ${error.message}`;\n      console.error('Update failed：', error);\n    }\n  }\n}\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(dataId).remove();\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('DeleteDocData')\nexport class DeleteDocData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onDeleteButtonClick() {\n    const dataId = this.idInput.string;\n\n    if (!dataId) {\n      this.resultLabel.string = 'Please entershouldDeleteDataID';\n      return;\n    }\n\n    try {\n      const db = cloudbase.database();\n      await db.collection(\"{%TABLE_NAME%}\").doc(dataId).remove();\n\n      this.resultLabel.string = 'Delete successful';\n      this.idInput.string = '';\n      console.log('Delete successful');\n    } catch (error) {\n      this.resultLabel.string = `Delete failed: ${error.message}`;\n      console.error('Delete failed：', error);\n    }\n  }\n}\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('QueryModelData')\nexport class QueryModelData extends Component {\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onLoad() {\n    try {\n      const res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({ pageNumber: 1, pagesize: 10 });\n\n      const records = res.data?.records || [];\n      this.resultLabel.string = `Querysuccessful：${JSON.stringify(records)}`;\n      console.log('QueryResult：', records);\n    } catch (error) {\n      this.resultLabel.string = `Queryfailed: ${error.message}`;\n      console.error('Queryfailed：', error);\n    }\n  }\n}\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: { title: \"Example Title\" }\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('AddModelData')\nexport class AddModelData extends Component {\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onAddButtonClick() {\n    const title = this.titleInput.string;\n    if (!title) {\n      this.resultLabel.string = 'Please enterTitle';\n      return;\n    }\n\n    try {\n      const res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({ data: { title } });\n\n      this.resultLabel.string = `Insert successful! id: ${res.data.id}`;\n      this.titleInput.string = '';\n      console.log('Insert successful：', res);\n    } catch (error) {\n      this.resultLabel.string = `Insert failed: ${error.message}`;\n      console.error('Insert failed：', error);\n    }\n  }\n}\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nawait cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: { title: \"New Title\" },\n  filter: { where: { _id: { $eq: dataId } } }\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('UpdateModelData')\nexport class UpdateModelData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(EditBox)\n  titleInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onUpdateButtonClick() {\n    const dataId = this.idInput.string;\n    const newTitle = this.titleInput.string;\n\n    if (!dataId || !newTitle) {\n      this.resultLabel.string = 'Please enterDataIDandNew Title';\n      return;\n    }\n\n    try {\n      await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n        data: { title: newTitle },\n        filter: { where: { _id: { $eq: dataId } } }\n      });\n\n      this.resultLabel.string = 'Update successful';\n      this.idInput.string = '';\n      this.titleInput.string = '';\n      console.log('Update successful');\n    } catch (error) {\n      this.resultLabel.string = `Update failed: ${error.message}`;\n      console.error('Update failed：', error);\n    }\n  }\n}\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nawait cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: { where: { _id: { $eq: dataId } } }\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('DeleteModelData')\nexport class DeleteModelData extends Component {\n  @property(EditBox)\n  idInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onDeleteButtonClick() {\n    const dataId = this.idInput.string;\n\n    if (!dataId) {\n      this.resultLabel.string = 'Please entershouldDeleteDataID';\n      return;\n    }\n\n    try {\n      await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n        filter: { where: { _id: { $eq: dataId } } }\n      });\n\n      this.resultLabel.string = 'Delete successful';\n      this.idInput.string = '';\n      console.log('Delete successful');\n    } catch (error) {\n      this.resultLabel.string = `Delete failed: ${error.message}`;\n      console.error('Delete failed：', error);\n    }\n  }\n}\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {}\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('CallFunction')\nexport class CallFunction extends Component {\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onCallButtonClick() {\n    try {\n      const res = await cloudbase.callFunction({\n        name: \"{%FUNCTION_NAME%}\",\n        data: {}\n      });\n\n      this.resultLabel.string = `Callsuccessful：${JSON.stringify(res.result)}`;\n      console.log('CallResult：', res.result);\n    } catch (error) {\n      this.resultLabel.string = `Call failed: ${error.message}`;\n      console.error('Call failed：', error);\n    }\n  }\n}\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function",
            "content": []
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\n// Call {%SERVICE_NAME%} Cloud Runservice\nconst res = await cloudbase.callContainer({\n  name: \"{%SERVICE_NAME%}\"\n  method: 'POST',\n  path: '/',\n  header:{\n    'Content-Type': 'application/json; charset=utf-8'\n  },\n  data: {},\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('CallRun')\nexport class CallRun extends Component {\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onCallButtonClick() {\n    try {\n      // Call {%SERVICE_NAME%} Cloud Runservice\n      const res = await cloudbase.callContainer({\n        name: \"{%SERVICE_NAME%}\"\n        method: 'POST',\n        path: '/',\n        header:{\n          'Content-Type': 'application/json; charset=utf-8'\n        },\n        data: {},\n      });\n\n      this.resultLabel.string = `Callsuccessful：${JSON.stringify(res)}`;\n      console.log('CallResult：', res);\n    } catch (error) {\n      this.resultLabel.string = `Call failed: ${error.message}`;\n      console.error('Call failed：', error);\n    }\n  }\n}\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run",
            "content": []
          },
          {
            "index": 6,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.uploadFile({\n  cloudPath: `images/${Date.now()}.png`,\n  filePath: filePath\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('UploadFile')\nexport class UploadFile extends Component {\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onUploadButtonClick() {\n    try {\n      // Note：actualUseneedfromuserSelectorgame resourcesGetfilePath\n      const filePath = 'path/to/your/file.png';\n      const cloudPath = `images/${Date.now()}-${Math.random()}.png`;\n\n      const res = await cloudbase.uploadFile({\n        cloudPath: cloudPath,\n        filePath: filePath\n      });\n\n      this.resultLabel.string = `Upload successful！fileID: ${res.fileID}`;\n      console.log('Upload successful：', res);\n    } catch (error) {\n      this.resultLabel.string = `Uploadfailed: ${error.message}`;\n      console.error('Uploadfailed：', error);\n    }\n  }\n}\n```",
                "index": 1,
                "title": "Upload File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.getTempFileURL({\n  fileList: [fileId]\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('GetFileUrl')\nexport class GetFileUrl extends Component {\n  @property(EditBox)\n  fileIdInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onGetUrlButtonClick() {\n    const fileId = this.fileIdInput.string;\n\n    if (!fileId) {\n      this.resultLabel.string = 'Please enterfileID';\n      return;\n    }\n\n    try {\n      const res = await cloudbase.getTempFileURL({\n        fileList: [fileId]\n      });\n\n      const fileUrl = res.fileList[0].tempFileURL;\n      this.resultLabel.string = `fileURL：${fileUrl}`;\n      console.log('fileURL：', fileUrl);\n    } catch (error) {\n      this.resultLabel.string = `Getfailed: ${error.message}`;\n      console.error('Getfailed：', error);\n    }\n  }\n}\n```",
                "index": 2,
                "title": "Get File URL"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.downloadFile({\n  fileID: fileId\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('DownloadFile')\nexport class DownloadFile extends Component {\n  @property(EditBox)\n  fileIdInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onDownloadButtonClick() {\n    const fileId = this.fileIdInput.string;\n\n    if (!fileId) {\n      this.resultLabel.string = 'Please enterfileID';\n      return;\n    }\n\n    try {\n      const res = await cloudbase.downloadFile({\n        fileID: fileId\n      });\n\n      this.resultLabel.string = `Downloadsuccessful！localPath: ${res.tempFilePath}`;\n      console.log('Downloadsuccessful：', res);\n    } catch (error) {\n      this.resultLabel.string = `Downloadfailed: ${error.message}`;\n      console.error('Downloadfailed：', error);\n    }\n  }\n}\n```",
                "index": 3,
                "title": "Download File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst res = await cloudbase.deleteFile({\n  fileList: [fileId]\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('DeleteFile')\nexport class DeleteFile extends Component {\n  @property(EditBox)\n  fileIdInput: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  async onDeleteButtonClick() {\n    const fileId = this.fileIdInput.string;\n\n    if (!fileId) {\n      this.resultLabel.string = 'Please enterfileID';\n      return;\n    }\n\n    try {\n      const res = await cloudbase.deleteFile({\n        fileList: [fileId]\n      });\n\n      if (res.fileList[0].code === \"SUCCESS\") {\n        this.resultLabel.string = 'Delete successful';\n        this.fileIdInput.string = '';\n        console.log('Delete successful');\n      } else {\n        this.resultLabel.string = 'Delete failed';\n        console.error('Delete failed');\n      }\n    } catch (error) {\n      this.resultLabel.string = `Delete failed: ${error.message}`;\n      console.error('Delete failed：', error);\n    }\n  }\n}\n```",
                "index": 4,
                "title": "Delete File"
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst ai = cloudbase.ai();\nconst model = ai.createModel(\"{%AI_MODEL_NAME%}\");\n\n// EnsurealreadyLogin\nconst loginState = await cloudbase.auth().getLoginState();\nif (!loginState) {\n  await cloudbase.auth().signInAnonymously();\n}\n\nconst res = await model.streamText({\n  model: \"{%AI_SUB_MODEL_NAME%}\",\n  messages: [\n    { role: \"system\", content: \"systemNoteword\" },\n    { role: \"user\", content: \"userInput\" }\n  ]\n});\n\nfor await (let str of res.textStream) {\n  // ProcessStreaming response\n}\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('CallAIModel')\nexport class CallAIModel extends Component {\n  @property(EditBox)\n  inputBox: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  @property(Label)\n  statusLabel: Label = null;\n\n  async onGenerateButtonClick() {\n    const input = this.inputBox.string;\n    if (!input) {\n      this.statusLabel.string = 'Please entertopic';\n      return;\n    }\n\n    this.statusLabel.string = 'Generating...';\n    this.resultLabel.string = '';\n\n    try {\n      const ai = cloudbase.ai();\n      const model = ai.createModel(\"{%AI_MODEL_NAME%}\");\n\n      // EnsurealreadyLogin\n      const loginState = await cloudbase.auth().getLoginState();\n      if (!loginState) {\n        await cloudbase.auth().signInAnonymously();\n      }\n\n      const res = await model.streamText({\n        model: \"{%AI_SUB_MODEL_NAME%}\",\n        messages: [\n          { role: \"system\", content: \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\" },\n          { role: \"user\", content: input }\n        ]\n      });\n\n      let fullText = '';\n      for await (let str of res.textStream) {\n        fullText += str;\n        this.resultLabel.string = fullText;\n      }\n\n      this.statusLabel.string = 'GenerateDone';\n      console.log('GenerateDone：', fullText);\n    } catch (err) {\n      this.statusLabel.string = 'Generation failed';\n      this.resultLabel.string = `Error: ${err.message}`;\n      console.error('Generation failed：', err);\n    }\n  }\n}\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation"
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\n// Call image generation cloud function\nconst res = await cloudbase.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: {\n    prompt: \"A cute cat playing in the sunshine\"\n  }\n});\n\nconst result = res.result;\n\nif (result.success) {\n  // Generation successful\n  console.log(\"Generation successful!\");\n  console.log(\"Image URL:\", result.imageUrl);\n  console.log(\"Optimized prompt:\", result.revised_prompt);\n\n  // Use image\n  // Note: Image URL is valid for 24 hours, please save or transfer promptly\n} else {\n  // Generation failed\n  console.error(\"Generation failed:\", result.code, result.message);\n}\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label, Sprite } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('GenerateImage')\nexport class GenerateImage extends Component {\n  @property(EditBox)\n  promptInput: EditBox = null;\n\n  @property(Label)\n  statusLabel: Label = null;\n\n  @property(Sprite)\n  imageSprite: Sprite = null;\n\n  async onGenerateButtonClick() {\n    const prompt = this.promptInput.string;\n    if (!prompt) {\n      this.statusLabel.string = 'Enter image description';\n      return;\n    }\n\n    this.statusLabel.string = 'Generating...';\n\n    try {\n      // Call image generation cloud function\n      const res = await cloudbase.callFunction({\n        name: \"<YOUR_FUNCTION_NAME>\",\n        data: {\n          prompt: prompt\n        }\n      });\n\n      const result = res.result;\n\n      if (result.success) {\n        this.statusLabel.string = 'Generation successful！';\n        console.log('Image URL:', result.imageUrl);\n        console.log('Optimized prompt:', result.revised_prompt);\n\n        // LoadImageto Sprite\n        // Note：needUsenetworkLoadImagemethod\n        // Specific implementationcanrootbased on Cocos Creator VersionAdjust\n      } else {\n        this.statusLabel.string = `Generation failed：${result.message}`;\n        console.error('Generation failed:', result.code, result.message);\n      }\n    } catch (err) {\n      this.statusLabel.string = 'Call failed';\n      console.error('Call failed:', err);\n    }\n  }\n}\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation"
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```javascript\nimport cloudbase from './services/CloudbaseService';\n\nconst ai = cloudbase.ai();\n\n// EnsurealreadyLogin\nconst loginState = await cloudbase.auth().getLoginState();\nif (!loginState) {\n  await cloudbase.auth().signInAnonymously();\n}\n\nconst res = await ai.bot.sendMessage({\n  botId: '{%AGENT_ID%}',\n  // Refer to frontend-backend communication protocol for input structure：\n  // https://docs.cloudbase.net/ai/agent/http-agent-protocol\n  threadId: '550e8400-e29b-41d4-a716-446655440000',\n  runId: 'run_001',\n  messages: [\n    {\n      id: 'msg-1',\n      role: 'user',\n      content: 'Hello',\n    },\n  ],\n  tools: [],\n  context: [],\n  state: {},\n  forwardedProps: {},\n});\n\nfor await (let str of res.textStream) {\n  // ProcessStreaming response\n}\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('CallAgent')\nexport class CallAgent extends Component {\n  @property(EditBox)\n  inputBox: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  @property(Label)\n  statusLabel: Label = null;\n\n  async onSendButtonClick() {\n    const input = this.inputBox.string;\n    if (!input) {\n      this.statusLabel.string = 'Please enterquestion';\n      return;\n    }\n\n    this.statusLabel.string = 'Send...';\n    this.resultLabel.string = '';\n\n    try {\n      const ai = cloudbase.ai();\n\n      // EnsurealreadyLogin\n      const loginState = await cloudbase.auth().getLoginState();\n      if (!loginState) {\n        await cloudbase.auth().signInAnonymously();\n      }\n\n      const res = await ai.bot.sendMessage({\n        botId: '{%AGENT_ID%}',\n        // Refer to frontend-backend communication protocol for input structure：\n        // https://docs.cloudbase.net/ai/agent/http-agent-protocol\n        threadId: '550e8400-e29b-41d4-a716-446655440000',\n        runId: 'run_001',\n        messages: [\n          {\n            id: 'msg-1',\n            role: 'user',\n            content: input,\n          },\n        ],\n        tools: [],\n        context: [],\n        state: {},\n        forwardedProps: {},\n      });\n\n      let fullText = '';\n      for await (let str of res.textStream) {\n        fullText += str;\n        this.resultLabel.string = fullText;\n      }\n\n      this.statusLabel.string = 'answerDone';\n      console.log('answerDone：', fullText);\n    } catch (err) {\n      this.statusLabel.string = 'Send failed';\n      this.resultLabel.string = `Error: ${err.message}`;\n      console.error('Send failed：', err);\n    }\n  }\n}\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst ai = cloudbase.ai();\n\n// EnsurealreadyLogin\nconst loginState = await cloudbase.auth().getLoginState();\nif (!loginState) {\n  await cloudbase.auth().signInAnonymously();\n}\n\nconst res = await ai.bot.sendMessage({\n  botId: \"{%AGENT_ID%}\",\n  msg: \"userMessage\"\n});\n\nfor await (let str of res.textStream) {\n  // ProcessStreaming response\n}\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('CallAgent')\nexport class CallAgent extends Component {\n  @property(EditBox)\n  inputBox: EditBox = null;\n\n  @property(Label)\n  resultLabel: Label = null;\n\n  @property(Label)\n  statusLabel: Label = null;\n\n  async onSendButtonClick() {\n    const input = this.inputBox.string;\n    if (!input) {\n      this.statusLabel.string = 'Please enterquestion';\n      return;\n    }\n\n    this.statusLabel.string = 'Send...';\n    this.resultLabel.string = '';\n\n    try {\n      const ai = cloudbase.ai();\n\n      // EnsurealreadyLogin\n      const loginState = await cloudbase.auth().getLoginState();\n      if (!loginState) {\n        await cloudbase.auth().signInAnonymously();\n      }\n\n      const res = await ai.bot.sendMessage({\n        botId: '{%AGENT_ID%}',\n        msg: input,\n      });\n\n      let fullText = '';\n      for await (let str of res.textStream) {\n        fullText += str;\n        this.resultLabel.string = fullText;\n      }\n\n      this.statusLabel.string = 'answerDone';\n      console.log('answerDone：', fullText);\n    } catch (err) {\n      this.statusLabel.string = 'Send failed';\n      this.resultLabel.string = `Error: ${err.message}`;\n      console.error('Send failed：', err);\n    }\n  }\n}\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 9,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "Use **SMS Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMSVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: phone });\nconst verificationId = res.verification_id;\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register\nawait auth.signUp({\n  phone_number: `+86 ${phone}`,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${phone.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('SmsRegister')\nexport class SmsRegister extends Component {\n  @property(EditBox)\n  phoneInput: EditBox = null;\n\n  @property(EditBox)\n  codeInput: EditBox = null;\n\n  @property(Label)\n  messageLabel: Label = null;\n\n  private verificationId: string = '';\n\n  // Send Code\n  async onSendCodeButtonClick() {\n    const phone = this.phoneInput.string;\n    if (!phone) {\n      this.messageLabel.string = 'Please enterPhone number';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ phone_number: phone });\n      this.verificationId = res.verification_id;\n      this.messageLabel.string = 'Verification code sent！';\n    } catch (error) {\n      this.messageLabel.string = `Send failed: ${error.message}`;\n    }\n  }\n\n  // Register\n  async onRegisterButtonClick() {\n    const phone = this.phoneInput.string;\n    const code = this.codeInput.string;\n\n    if (!this.verificationId || !code) {\n      this.messageLabel.string = 'please firstSend Code';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      // Verify the code\n      const verifyRes = await auth.verify({\n        verification_id: this.verificationId,\n        verification_code: code,\n      });\n      // Register (auto-login if user exists)\n      await auth.signUp({\n        phone_number: `+86 ${phone}`,\n        verification_code: code,\n        verification_token: verifyRes.verification_token,\n        name: `user_${phone.slice(-4)}`,\n        password: \"admin@123\"\n      });\n      this.messageLabel.string = 'Registration successful！';\n      console.log('Registration successful');\n    } catch (error) {\n      this.messageLabel.string = `Registration failed: ${error.message}`;\n      console.error('Registration failed：', error);\n    }\n  }\n}\n```",
                "index": 1,
                "title": "SMS Code Registration"
              },
              {
                "markdown": "Use **Email Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\nconst verificationId = res.verification_id;\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register\nawait auth.signUp({\n  email,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${email.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('EmailRegister')\nexport class EmailRegister extends Component {\n  @property(EditBox)\n  emailInput: EditBox = null;\n\n  @property(EditBox)\n  codeInput: EditBox = null;\n\n  @property(Label)\n  messageLabel: Label = null;\n\n  private verificationId: string = '';\n\n  // Send Code\n  async onSendCodeButtonClick() {\n    const email = this.emailInput.string;\n    if (!email) {\n      this.messageLabel.string = 'Please enterEmail';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ email });\n      this.verificationId = res.verification_id;\n      this.messageLabel.string = 'Verification code sent！';\n    } catch (error) {\n      this.messageLabel.string = `Send failed: ${error.message}`;\n    }\n  }\n\n  // Register\n  async onRegisterButtonClick() {\n    const email = this.emailInput.string;\n    const code = this.codeInput.string;\n\n    if (!this.verificationId || !code) {\n      this.messageLabel.string = 'please firstSend Code';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      // Verify the code\n      const verifyRes = await auth.verify({\n        verification_id: this.verificationId,\n        verification_code: code,\n      });\n      // Register (auto-login if user exists)\n      await auth.signUp({\n        email,\n        verification_code: code,\n        verification_token: verifyRes.verification_token,\n        name: `user_${email.slice(-4)}`,\n        password: \"admin@123\"\n      });\n      this.messageLabel.string = 'Registration successful！';\n      console.log('Registration successful');\n    } catch (error) {\n      this.messageLabel.string = `Registration failed: ${error.message}`;\n      console.error('Registration failed：', error);\n    }\n  }\n}\n```",
                "index": 2,
                "title": "Email Code Registration"
              },
              {
                "markdown": "Use **Username Password Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **UsernamePasswordLogin**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst auth = cloudbase.auth();\nawait auth.signIn({\n  username, // Can be username, phone or email\n  password\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('PasswordLogin')\nexport class PasswordLogin extends Component {\n  @property(EditBox)\n  usernameInput: EditBox = null;\n\n  @property(EditBox)\n  passwordInput: EditBox = null;\n\n  @property(Label)\n  messageLabel: Label = null;\n\n  async onLoginButtonClick() {\n    const username = this.usernameInput.string;\n    const password = this.passwordInput.string;\n\n    if (!username || !password) {\n      this.messageLabel.string = 'Please enterAccountandPassword';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      await auth.signIn({\n        username, // Can be username, phone or email\n        password,\n      });\n      this.messageLabel.string = 'Login successful！';\n      console.log('Login successful');\n    } catch (error) {\n      this.messageLabel.string = `Login failed: ${error.message}`;\n      console.error('Login failed：', error);\n    }\n  }\n}\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login"
              },
              {
                "markdown": "Use **SMS Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMS Verification Login**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: `+86 ${phone}` });\nconst verificationInfo = res;\n\n// Login\nawait auth.signInWithSms({\n  verificationInfo: verificationInfo,\n  verificationCode: code,\n  phoneNum: `+86 ${phone}`\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('SmsLogin')\nexport class SmsLogin extends Component {\n  @property(EditBox)\n  phoneInput: EditBox = null;\n\n  @property(EditBox)\n  codeInput: EditBox = null;\n\n  @property(Label)\n  messageLabel: Label = null;\n\n  private verificationInfo: any = null;\n\n  // Send Code\n  async onSendCodeButtonClick() {\n    const phone = this.phoneInput.string;\n    if (!phone) {\n      this.messageLabel.string = 'Please enterPhone number';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n      this.verificationInfo = res;\n      this.messageLabel.string = 'Verification code sent！';\n    } catch (error) {\n      this.messageLabel.string = `Send failed: ${error.message}`;\n    }\n  }\n\n  // Login\n  async onLoginButtonClick() {\n    const phone = this.phoneInput.string;\n    const code = this.codeInput.string;\n\n    if (!this.verificationInfo || !code) {\n      this.messageLabel.string = 'please firstSend Code';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInWithSms({\n        verificationInfo: this.verificationInfo,\n        verificationCode: code,\n        phoneNum: `+86 ${phone}`\n      });\n      this.messageLabel.string = 'Login successful！';\n      console.log('Login successful');\n    } catch (error) {\n      this.messageLabel.string = `Login failed: ${error.message}`;\n      console.error('Login failed：', error);\n    }\n  }\n}\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login"
              },
              {
                "markdown": "Use **Email Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\nconst verificationInfo = res;\n\n// Login\nawait auth.signInWithEmail({\n  verificationInfo: verificationInfo,\n  verificationCode: code,\n  email\n});\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, EditBox, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('EmailLogin')\nexport class EmailLogin extends Component {\n  @property(EditBox)\n  emailInput: EditBox = null;\n\n  @property(EditBox)\n  codeInput: EditBox = null;\n\n  @property(Label)\n  messageLabel: Label = null;\n\n  private verificationInfo: any = null;\n\n  // Send Code\n  async onSendCodeButtonClick() {\n    const email = this.emailInput.string;\n    if (!email) {\n      this.messageLabel.string = 'Please enterEmail';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ email });\n      this.verificationInfo = res;\n      this.messageLabel.string = 'Verification code sent！';\n    } catch (error) {\n      this.messageLabel.string = `Send failed: ${error.message}`;\n    }\n  }\n\n  // Login\n  async onLoginButtonClick() {\n    const email = this.emailInput.string;\n    const code = this.codeInput.string;\n\n    if (!this.verificationInfo || !code) {\n      this.messageLabel.string = 'please firstSend Code';\n      return;\n    }\n\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInWithEmail({\n        verificationInfo: this.verificationInfo,\n        verificationCode: code,\n        email\n      });\n      this.messageLabel.string = 'Login successful！';\n      console.log('Login successful');\n    } catch (error) {\n      this.messageLabel.string = `Login failed: ${error.message}`;\n      console.error('Login failed：', error);\n    }\n  }\n}\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./services/CloudbaseService\";\n\nconst auth = cloudbase.auth();\nawait auth.signInAnonymously();\n```\n\n**Full Example：**\n\n```js\nimport { _decorator, Component, Node, Label } from 'cc';\nimport cloudbase from './services/CloudbaseService';\n\nconst { ccclass, property } = _decorator;\n\n@ccclass('AnonymousLogin')\nexport class AnonymousLogin extends Component {\n  @property(Label)\n  messageLabel: Label = null;\n\n  async onLoginButtonClick() {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInAnonymously();\n      this.messageLabel.string = 'anonymousLogin successful！';\n      console.log('anonymousLogin successful');\n    } catch (error) {\n      this.messageLabel.string = `Login failed: ${error.message}`;\n      console.error('Login failed：', error);\n    }\n  }\n}\n```",
                "index": 6,
                "title": "anonymousLogin"
              }
            ]
          }
        ]
      }
    ],
    "_id": "b49e5b7a697c806e0044fb223b4864b0",
    "_openid": "anon",
    "createdAt": 1769767022175,
    "updatedAt": 1775130862944
  },
  {
    "category": "CloudBase MCP,Gemini CLI",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 111,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/gemini-cli",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.gemini/settings.json`:\n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Gemini\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "c1f7ac5f69a9286e0043596d146b5e20",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Cursor",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 119,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/cursor",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.cursor/mcp.json`:\n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Cursor\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "c1f7ac5f69a9286f00435975676b688c",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Claude Code",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 116,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/claude-code",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.mcp.json`:\n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"ClaudeCode\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "c1f7ac5f69a928700043597f463d8d5c",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "Framework Integration,Mobile Frameworks,Flutter",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 10,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/http-api/basic/overview",
    "content": [
      {
        "markdown": "Use **HTTP Request** in **Flutter** Callvarious CloudBase capabilities\n\nin `pubspec.yaml` Add dependencies：\n\n```yaml\ndependencies:\n  http: ^1.1.0\n  flutter_dotenv: ^5.1.0\n```\n\nThen run：\n\n```bash\nflutter pub get\n```",
        "index": 1,
        "title": "Install Dependencies",
        "content": []
      },
      {
        "markdown": "Add the following code to your **Flutter** project",
        "index": 2,
        "title": "Initialize Configuration",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```dart\nimport 'dart:convert';\nimport 'package:http/http.dart' as http;\nimport 'package:flutter_dotenv/flutter_dotenv.dart';\n\nclass CloudBaseClient {\n  late String envId;\n  late String accessToken;\n  late String baseUrl;\n  late Map<String, String> headers;\n\n  CloudBaseClient() {\n    envId = dotenv.env['CLOUDBASE_ENV_ID'] ?? '';\n    accessToken = dotenv.env['CLOUDBASE_ACCESS_TOKEN'] ?? '';\n    baseUrl = 'https://$envId.api.tcloudbasegateway.com';\n    headers = {\n      'Content-Type': 'application/json',\n      'Accept': 'application/json',\n      'Authorization': 'Bearer $accessToken',\n    };\n  }\n\n  /// UpdateAccess token\n  ///\n  /// [newToken] new access token\n  void updateAccessToken(String newToken) {\n    accessToken = newToken;\n    headers['Authorization'] = 'Bearer $newToken';\n    print('Access token has beenUpdate');\n  }\n\n  /// Unified HTTP request method\n  ///\n  /// [method] Request method (GET, POST, PUT, PATCH, DELETE)\n  /// [path] APIPath (such as /v1/rdb/rest/table_name)\n  /// [body] Request body data\n  /// [customHeaders] Customheaders\n  ///\n  /// Returns response data ornull\n  Future<dynamic> request(\n    String method,\n    String path, {\n    dynamic body,\n    Map<String, String>? customHeaders,\n  }) async {\n    final url = Uri.parse('$baseUrl$path');\n    final requestHeaders = Map<String, String>.from(headers);\n\n    if (customHeaders != null) {\n      requestHeaders.addAll(customHeaders);\n    }\n\n    try {\n      http.Response response;\n\n      switch (method.toUpperCase()) {\n        case 'GET':\n          response = await http.get(url, headers: requestHeaders);\n          break;\n        case 'POST':\n          response = await http.post(\n            url,\n            headers: requestHeaders,\n            body: body != null ? jsonEncode(body) : null,\n          );\n          break;\n        case 'PUT':\n          response = await http.put(\n            url,\n            headers: requestHeaders,\n            body: body != null ? jsonEncode(body) : null,\n          );\n          break;\n        case 'PATCH':\n          response = await http.patch(\n            url,\n            headers: requestHeaders,\n            body: body != null ? jsonEncode(body) : null,\n          );\n          break;\n        case 'DELETE':\n          response = await http.delete(url, headers: requestHeaders);\n          break;\n        default:\n          throw Exception('Unsupported HTTP method: $method');\n      }\n\n      if (response.statusCode >= 200 && response.statusCode < 300) {\n        if (response.body.isEmpty) {\n          return true;\n        }\n        return jsonDecode(response.body);\n      } else {\n        print('Requestfailed: ${response.statusCode} ${response.body}');\n        return null;\n      }\n    } catch (e) {\n      print('Requestfailed: $e');\n      return null;\n    }\n  }\n}\n\nfinal cloudbase = CloudBaseClient();\n```",
            "index": 1,
            "title": "cloudbase_client.dart"
          },
          {
            "markdown": "> 💡Note: For user permissions, refer to the \"Authentication\" module to obtain access_token\n\n```properties\n# Environment ID\nCLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Anonymous access token\nCLOUDBASE_ACCESS_TOKEN={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": ".env"
          }
        ]
      },
      {
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<List<dynamic>> getMysqlData(String tableName) async {\n  /// Query MySQL database data\n  final data = await cloudbase.request('GET', '/v1/rdb/rest/$tableName?limit=10');\n\n  if (data != null) {\n    print('Querysuccessful: $data');\n    return data as List<dynamic>;\n  }\n  return [];\n}\n\n// Usage Example\nvoid main() async {\n  final result = await getMysqlData('{%TABLE_NAME%}');\n  print(result);\n}\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<dynamic> addMysqlData(String tableName, Map<String, dynamic> data) async {\n  /// Add MySQL database data\n  final result = await cloudbase.request('POST', '/v1/rdb/rest/$tableName', body: data);\n\n  if (result != null) {\n    print('Insert successful: $result');\n  }\n  return result;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await addMysqlData('{%TABLE_NAME%}', {'title': 'Example Title'});\n  print(result);\n}\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<dynamic> updateMysqlData(String tableName, String dataId, Map<String, dynamic> data) async {\n  /// Update MySQL database data\n  final result = await cloudbase.request(\n    'PATCH',\n    '/v1/rdb/rest/$tableName?id=eq.$dataId',\n    body: data,\n  );\n\n  if (result != null) {\n    print('Update successful: $result');\n  }\n  return result;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await updateMysqlData('{%TABLE_NAME%}', '<data id>', {'title': 'New Title'});\n  print(result);\n}\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<bool> deleteMysqlData(String tableName, String dataId) async {\n  /// Delete MySQL database data\n  final result = await cloudbase.request('DELETE', '/v1/rdb/rest/$tableName?id=eq.$dataId');\n\n  if (result != null) {\n    print('Delete successful');\n    return true;\n  }\n  return false;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await deleteMysqlData('{%TABLE_NAME%}', '<data id>');\n  print(result);\n}\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<List<dynamic>> getModelData(String modelName, {String envType = 'prod'}) async {\n  /// QueryData ModelData\n  final payload = {\n    'pageSize': 10,\n    'pageNumber': 1,\n    'getCount': true,\n  };\n\n  final result = await cloudbase.request('POST', '/v1/model/$envType/$modelName/list', body: payload);\n\n  if (result != null) {\n    final records = result['data']?['records'] ?? [];\n    print('Querysuccessful: $records');\n    return records;\n  }\n  return [];\n}\n\n// Usage Example\nvoid main() async {\n  final records = await getModelData('{%TABLE_NAME%}');\n  print(records);\n}\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<dynamic> addModelData(String modelName, Map<String, dynamic> data, {String envType = 'prod'}) async {\n  /// AddData ModelData\n  final result = await cloudbase.request(\n    'POST',\n    '/v1/model/$envType/$modelName/create',\n    body: {'data': data},\n  );\n\n  if (result != null) {\n    final docId = result['data']?['id'];\n    print('Insert successful! id: $docId');\n  }\n  return result;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await addModelData('{%TABLE_NAME%}', {'title': 'Example Title'});\n  print(result);\n}\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<bool> updateModelData(String modelName, String dataId, Map<String, dynamic> data, {String envType = 'prod'}) async {\n  /// UpdateData ModelData\n  final payload = {\n    'data': data,\n    'filter': {\n      'where': {\n        '_id': {'\\$eq': dataId}\n      }\n    }\n  };\n\n  final result = await cloudbase.request('PUT', '/v1/model/$envType/$modelName/update', body: payload);\n\n  if (result != null) {\n    print('Update successful!');\n    return true;\n  }\n  return false;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await updateModelData('{%TABLE_NAME%}', '<data id>', {'title': 'New Title'});\n  print(result);\n}\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<bool> deleteModelData(String modelName, String dataId, {String envType = 'prod'}) async {\n  /// DeleteData ModelData\n  final payload = {\n    'filter': {\n      'where': {\n        '_id': {'\\$eq': dataId}\n      }\n    }\n  };\n\n  final result = await cloudbase.request('POST', '/v1/model/$envType/$modelName/delete', body: payload);\n\n  if (result != null) {\n    print('Delete successful!');\n    return true;\n  }\n  return false;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await deleteModelData('{%TABLE_NAME%}', '<data id>');\n  print(result);\n}\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<dynamic> callFunction(String functionName, {Map<String, dynamic>? data}) async {\n  /// CallCloud Function\n  final result = await cloudbase.request('POST', '/v1/functions/$functionName', body: data ?? {});\n\n  if (result != null) {\n    print('Cloud function call result: $result');\n  }\n  return result;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await callFunction('{%FUNCTION_NAME%}');\n  print(result);\n}\n```",
            "index": 3,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<dynamic> callContainer(String serviceName, {String path = '', String method = 'GET', Map<String, dynamic>? data}) async {\n  /// CallCloud Runservice\n  final fullPath = '/v1/cloudrun/$serviceName/$path'.replaceAll(RegExp(r'/+$'), '');\n  final result = await cloudbase.request(method.toUpperCase(), fullPath, body: data);\n\n  if (result != null) {\n    print('Cloud RunCallResult: $result');\n  }\n  return result;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await callContainer('{%SERVICE_NAME%}');\n  print(result);\n}\n```",
            "index": 4,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```dart\nimport 'dart:io';\nimport 'package:http/http.dart' as http;\nimport 'cloudbase_client.dart';\n\nFuture<Map<String, dynamic>?> uploadFile(String filePath, {String? objectId}) async {\n  /// Upload FiletoCloud Storage\n  final file = File(filePath);\n\n  if (!await file.exists()) {\n    print('filedoes not exist: $filePath');\n    return null;\n  }\n\n  if (objectId == null) {\n    final filename = filePath.split('/').last;\n    final timestamp = DateTime.now().millisecondsSinceEpoch;\n    objectId = 'uploads/$timestamp-$filename';\n  }\n\n  // 1. Get upload info\n  final uploadInfo = await cloudbase.request(\n    'POST',\n    '/v1/storages/get-objects-upload-info',\n    body: [{'objectId': objectId}],\n  );\n\n  if (uploadInfo == null || uploadInfo.isEmpty) {\n    return null;\n  }\n\n  final info = uploadInfo[0];\n  final uploadUrl = info['uploadUrl'];\n\n  try {\n    // 2. Upload File\n    final fileData = await file.readAsBytes();\n    final uploadHeaders = {\n      'Authorization': info['authorization'],\n      'X-Cos-Security-Token': info['token'],\n      'X-Cos-Meta-Fileid': info['cloudObjectMeta'],\n    };\n\n    final uploadResponse = await http.put(\n      Uri.parse(uploadUrl),\n      headers: uploadHeaders,\n      body: fileData,\n    );\n\n    if (uploadResponse.statusCode >= 200 && uploadResponse.statusCode < 300) {\n      final result = {\n        'cloudObjectId': info['cloudObjectId'],\n        'downloadUrl': info['downloadUrl'],\n        'objectId': objectId,\n      };\n\n      print('fileUpload successful:');\n      print('- Object ID: ${result['objectId']}');\n      print('- DownloadURL: ${result['downloadUrl']}');\n\n      return result;\n    }\n\n    print('fileUploadfailed: ${uploadResponse.statusCode}');\n    return null;\n  } catch (e) {\n    print('fileUploadfailed: $e');\n    return null;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final result = await uploadFile('./example.jpg');\n  print(result);\n}\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<String?> getFileUrl(String cloudObjectId) async {\n  /// GetCloud Storagefiletemporary accessURL\n  final result = await cloudbase.request(\n    'POST',\n    '/v1/storages/get-objects-download-info',\n    body: [{'cloudObjectId': cloudObjectId}],\n  );\n\n  if (result != null && result.isNotEmpty) {\n    final downloadUrl = result[0]['downloadUrl'];\n    print('fileURL: $downloadUrl');\n    return downloadUrl;\n  }\n  return null;\n}\n\n// Usage Example\nvoid main() async {\n  final fileUrl = await getFileUrl('cloud://xxx.png');\n  print(fileUrl);\n}\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'dart:io';\nimport 'package:http/http.dart' as http;\nimport 'cloudbase_client.dart';\n\nFuture<bool> downloadFile(String cloudObjectId, {String savePath = './'}) async {\n  /// DownloadCloud Storagefiletolocal\n  // 1. GetDownloadURL\n  final result = await cloudbase.request(\n    'POST',\n    '/v1/storages/get-objects-download-info',\n    body: [{'cloudObjectId': cloudObjectId}],\n  );\n\n  if (result == null || result.isEmpty) {\n    return false;\n  }\n\n  final downloadUrl = result[0]['downloadUrl'];\n\n  try {\n    // 2. fromURLExtractfilename\n    final uri = Uri.parse(downloadUrl);\n    final filename = uri.pathSegments.last.split('?').first;\n\n    // 3. Determine full path\n    String fullPath;\n    final saveDir = Directory(savePath);\n    if (await saveDir.exists() || savePath.endsWith('/')) {\n      fullPath = '$savePath/$filename';\n    } else {\n      fullPath = savePath;\n    }\n\n    // 4. Download File\n    final fileResponse = await http.get(Uri.parse(downloadUrl));\n\n    if (fileResponse.statusCode >= 200 && fileResponse.statusCode < 300) {\n      // 5. Save to local\n      final file = File(fullPath);\n      await file.writeAsBytes(fileResponse.bodyBytes);\n\n      print('Downloadsuccessful! filesaved to: $fullPath');\n      return true;\n    }\n\n    print('Downloadfailed: ${fileResponse.statusCode}');\n    return false;\n  } catch (e) {\n    print('Downloadfailed: $e');\n    return false;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  // Downloadto current directory，Useoriginalfilename\n  await downloadFile('cloud://xxx.png');\n\n  // Downloadto specified directory\n  await downloadFile('cloud://xxx.png', savePath: './downloads/');\n\n  // Downloadand rename\n  await downloadFile('cloud://xxx.png', savePath: './my-image.png');\n}\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<bool> deleteFile(dynamic cloudObjectIds) async {\n  /// DeleteCloud Storagefile\n  List<String> ids;\n  if (cloudObjectIds is String) {\n    ids = [cloudObjectIds];\n  } else if (cloudObjectIds is List<String>) {\n    ids = cloudObjectIds;\n  } else {\n    print('Parameter type error');\n    return false;\n  }\n\n  final data = ids.map((id) => {'cloudObjectId': id}).toList();\n  final result = await cloudbase.request('POST', '/v1/storages/delete-objects', body: data);\n\n  if (result != null) {\n    print('Delete successful!');\n    return true;\n  }\n  return false;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await deleteFile('cloud://xxx.png');\n  print(result);\n}\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```dart\nimport 'dart:convert';\nimport 'package:http/http.dart' as http;\nimport 'cloudbase_client.dart';\n\nFuture<String?> streamText(String model, String subModel, List<Map<String, String>> messages) async {\n  /// streamingtextthisGenerate\n  final payload = {\n    'model': subModel,\n    'messages': messages,\n    'stream': true,\n  };\n\n  final url = '${cloudbase.baseUrl}/v1/ai/$model/chat/completions';\n  final headers = Map<String, String>.from(cloudbase.headers);\n  headers['Accept'] = 'text/event-stream';\n\n  try {\n    final request = http.Request('POST', Uri.parse(url));\n    request.headers.addAll(headers);\n    request.body = jsonEncode(payload);\n\n    final streamedResponse = await request.send();\n\n    if (streamedResponse.statusCode >= 200 && streamedResponse.statusCode < 300) {\n      print('AI Streaming response:');\n      String fullContent = '';\n\n      await for (var chunk in streamedResponse.stream.transform(utf8.decoder)) {\n        final lines = chunk.split('\\n');\n        for (var line in lines) {\n          if (line.startsWith('data: ')) {\n            final dataStr = line.substring(6);\n            if (dataStr.trim() != '[DONE]') {\n              try {\n                final chunkData = jsonDecode(dataStr);\n                final content = chunkData['choices']?[0]?['delta']?['content'] ?? '';\n                if (content.isNotEmpty) {\n                  print(content);\n                  fullContent += content;\n                }\n              } catch (e) {\n                // Ignore JSON parsing error\n              }\n            }\n          }\n        }\n      }\n\n      return fullContent;\n    } else {\n      print('AI Call failed: ${streamedResponse.statusCode}');\n      return null;\n    }\n  } catch (e) {\n    print('AI Call failed: $e');\n    return null;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final response = await streamText(\n    '{%AI_MODEL_NAME%}',\n    '{%AI_SUB_MODEL_NAME%}',\n    [\n      {'role': 'system', 'content': 'Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create'},\n      {'role': 'user', 'content': 'Spring'}\n    ],\n  );\n  print('\\nComplete response: $response');\n}\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```dart\nimport 'cloudbase_client.dart';\n\nFuture<Map<String, dynamic>?> generateImage(String prompt) async {\n  /// Call image generation cloud function\n  final result = await cloudbase.request(\n    'POST',\n    '/v1/functions/<YOUR_FUNCTION_NAME>/invoke',\n    body: {\n      'prompt': prompt,\n    },\n  );\n\n  if (result != null) {\n    final success = result['success'] ?? false;\n    \n    if (success) {\n      // Generation successful\n      print('Generation successful!');\n      print('Image URL: ${result['imageUrl']}');\n      print('Optimized prompt: ${result['revised_prompt']}');\n\n      // Use image\n      // Note: Image URL is valid for 24 hours, please save or transfer promptly\n      return result;\n    } else {\n      // Generation failed\n      print('Generation failed: ${result['code']} ${result['message']}');\n      return null;\n    }\n  }\n  return null;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await generateImage('A cute cat playing in the sunshine');\n  if (result != null) {\n    print('Image URL: ${result['imageUrl']}');\n  }\n}\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```dart\n/**\n * Flutter Call Agent Example (AG-UI Protocol)\n * Protocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n */\nimport 'dart:convert';\nimport 'package:http/http.dart' as http;\nimport 'cloudbase_client.dart';\n\nFuture<String?> chatWithAgentStream(String botId, String userMessage) async {\n  // Build message list (AG-UI protocol format)\n  final messages = [\n    {\n      'id': 'msg_001',\n      'role': 'user',\n      'content': userMessage,\n    }\n  ];\n\n  // AG-UI Protocol request parameters\n  final payload = {\n    'messages': messages,                                    // Required: Message list\n    'threadId': '550e8400-e29b-41d4-a716-446655440000',      // Optional: Session ID for multi-turn conversation\n    'runId': 'run_001',                                       // Optional: Run ID for execution tracking\n    'tools': [],                                              // Optional: Frontend tool definitions\n    'context': [],                                            // Optional: Context information\n    'forwardedProps': {},                                     // Optional: Pass-through parameters\n  };\n\n  final url = '${cloudbase.baseUrl}/v1/aibot/bots/$botId/send-message';\n  final headers = Map<String, String>.from(cloudbase.headers);\n  headers['Accept'] = 'text/event-stream';\n\n  try {\n    final request = http.Request('POST', Uri.parse(url));\n    request.headers.addAll(headers);\n    request.body = jsonEncode(payload);\n\n    final streamedResponse = await request.send();\n\n    if (streamedResponse.statusCode >= 200 && streamedResponse.statusCode < 300) {\n      print('AI Streaming response:');\n      String fullContent = '';\n      String buffer = '';\n\n      await for (var chunk in streamedResponse.stream.transform(utf8.decoder)) {\n        buffer += chunk;\n\n        while (buffer.contains('\\n')) {\n          final newlineIndex = buffer.indexOf('\\n');\n          final line = buffer.substring(0, newlineIndex).trim();\n          buffer = buffer.substring(newlineIndex + 1);\n\n          if (line.startsWith('data: ')) {\n            final dataStr = line.substring(6).trim();\n            if (dataStr.isNotEmpty && dataStr != '[DONE]') {\n              try {\n                final chunkData = jsonDecode(dataStr);\n                final content = chunkData['content'] ??\n                    chunkData['choices']?[0]?['delta']?['content'] ??\n                    chunkData['choices']?[0]?['message']?['content'] ??\n                    '';\n                if (content.isNotEmpty) {\n                  print(content);\n                  fullContent += content;\n                }\n              } catch (e) {\n                // Ignore JSON parsing error\n              }\n            }\n          }\n        }\n      }\n\n      print('');\n      return fullContent;\n    } else {\n      print('AI Call failed: ${streamedResponse.statusCode}');\n      return null;\n    }\n  } catch (e) {\n    print('AI Call failed: $e');\n    return null;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final response = await chatWithAgentStream('{%AGENT_ID%}', 'Who are you');\n  print('\\nComplete response: $response');\n}\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```dart\nimport 'dart:convert';\nimport 'package:http/http.dart' as http;\nimport 'cloudbase_client.dart';\n\nFuture<String?> chatWithAgentStream(String botId, String msg, {List<Map<String, String>>? history}) async {\n  /// streamingCallAgent\n  final payload = {\n    'history': history ?? [],\n    'msg': msg,\n  };\n\n  final url = '${cloudbase.baseUrl}/v1/aibot/bots/$botId/send-message';\n  final headers = Map<String, String>.from(cloudbase.headers);\n  headers['Accept'] = 'text/event-stream';\n\n  try {\n    final request = http.Request('POST', Uri.parse(url));\n    request.headers.addAll(headers);\n    request.body = jsonEncode(payload);\n\n    final streamedResponse = await request.send();\n\n    if (streamedResponse.statusCode >= 200 && streamedResponse.statusCode < 300) {\n      print('AI Streaming response:');\n      String fullContent = '';\n      String buffer = '';\n\n      await for (var chunk in streamedResponse.stream.transform(utf8.decoder)) {\n        buffer += chunk;\n\n        while (buffer.contains('\\n')) {\n          final newlineIndex = buffer.indexOf('\\n');\n          final line = buffer.substring(0, newlineIndex).trim();\n          buffer = buffer.substring(newlineIndex + 1);\n\n          if (line.startsWith('data: ')) {\n            final dataStr = line.substring(6).trim();\n            if (dataStr.isNotEmpty && dataStr != '[DONE]') {\n              try {\n                final chunkData = jsonDecode(dataStr);\n                final content = chunkData['content'] ??\n                    chunkData['choices']?[0]?['delta']?['content'] ??\n                    chunkData['choices']?[0]?['message']?['content'] ??\n                    '';\n                if (content.isNotEmpty) {\n                  print(content);\n                  fullContent += content;\n                }\n              } catch (e) {\n                // Ignore JSON parsing error\n              }\n            }\n          }\n        }\n      }\n\n      print('');\n      return fullContent;\n    } else {\n      print('AI Call failed: ${streamedResponse.statusCode}');\n      return null;\n    }\n  } catch (e) {\n    print('AI Call failed: $e');\n    return null;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final response = await chatWithAgentStream('{%AGENT_ID%}', 'Who are you');\n  print('\\nComplete response: $response');\n}\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 8,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<Map<String, dynamic>?> signUpWithPhoneCode(String phoneNumber, String verificationCode, {String? username, String? password, String? captchaToken}) async {\n  try {\n    // Step1: SendSMSVerification code\n    final sendBody = {\n      'phone_number': phoneNumber.startsWith('+86') ? phoneNumber : '+86$phoneNumber',\n      'target': 'NON_USER',  // \"NON_USER\" - Accountdoes not existthenSend; \"ANY\" - No restriction\n    };\n\n    final sendHeaders = captchaToken != null ? {'x-captcha-token': captchaToken} : null;\n\n    final sendResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification',\n      body: sendBody,\n      customHeaders: sendHeaders,\n    );\n\n    if (sendResult == null) {\n      print('Send Codefailed');\n      return null;\n    }\n\n    final verificationId = sendResult['verification_id'];\n    print('Verification codeSendsuccessful! ID: $verificationId');\n\n    // Step2: Verify the code\n    final verifyResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification/verify',\n      body: {\n        'verification_id': verificationId,\n        'verification_code': verificationCode,\n      },\n    );\n\n    if (verifyResult == null) {\n      print('Verification codeError');\n      return null;\n    }\n\n    final verificationToken = verifyResult['verification_token'];\n    print('Verifysuccessful!');\n\n    // Step3: UseVerifytokenRegister\n    final signUpBody = {\n      'phone_number': phoneNumber.startsWith('+86') ? phoneNumber : '+86$phoneNumber',\n      'verification_token': verificationToken,\n    };\n\n    // Optional：AddUsernameandPassword\n    if (username != null) signUpBody['username'] = username;\n    if (password != null) signUpBody['password'] = password;\n\n    final signUpResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/signup',\n      body: signUpBody,\n    );\n\n    if (signUpResult != null) {\n      final accessToken = signUpResult['access_token'];\n      final userId = signUpResult['sub'];\n\n      print('Registration successful! User ID: $userId');\n      print('Access token: ${accessToken.substring(0, 20)}...');\n\n      // UpdateAccess token\n      cloudbase.updateAccessToken(accessToken);\n      return signUpResult;\n    }\n\n    print('Registration failed');\n    return null;\n  } catch (e) {\n    print('Registration failed: $e');\n    return null;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final result = await signUpWithPhoneCode('13800138000', '123456', username: 'myusername', password: 'mypassword');\n  if (result != null) {\n    print('Phone numberRegistration successful');\n  }\n}\n```",
                "index": 1,
                "title": "SMS Code Registration",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<Map<String, dynamic>?> signUpWithEmailCode(String email, String verificationCode, {String? username, String? password, String? captchaToken}) async {\n  try {\n    // Step1: SendEmailVerification code\n    final sendBody = {\n      'email': email,\n      'target': 'NON_USER',  // \"NON_USER\" - Accountdoes not existthenSend; \"ANY\" - No restriction\n    };\n\n    final sendHeaders = captchaToken != null ? {'x-captcha-token': captchaToken} : null;\n\n    final sendResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification',\n      body: sendBody,\n      customHeaders: sendHeaders,\n    );\n\n    if (sendResult == null) {\n      print('Send Codefailed');\n      return null;\n    }\n\n    final verificationId = sendResult['verification_id'];\n    print('Verification codeSendsuccessful! ID: $verificationId');\n\n    // Step2: Verify the code\n    final verifyResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification/verify',\n      body: {\n        'verification_id': verificationId,\n        'verification_code': verificationCode,\n      },\n    );\n\n    if (verifyResult == null) {\n      print('Verification codeError');\n      return null;\n    }\n\n    final verificationToken = verifyResult['verification_token'];\n    print('Verifysuccessful!');\n\n    // Step3: UseVerifytokenRegister\n    final signUpBody = {\n      'email': email,\n      'verification_token': verificationToken,\n    };\n\n    // Optional：AddUsernameandPassword\n    if (username != null) signUpBody['username'] = username;\n    if (password != null) signUpBody['password'] = password;\n\n    final signUpResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/signup',\n      body: signUpBody,\n    );\n\n    if (signUpResult != null) {\n      final accessToken = signUpResult['access_token'];\n      final userId = signUpResult['sub'];\n\n      print('Registration successful! User ID: $userId');\n      print('Access token: ${accessToken.substring(0, 20)}...');\n\n      // UpdateAccess token\n      cloudbase.updateAccessToken(accessToken);\n      return signUpResult;\n    }\n\n    print('Registration failed');\n    return null;\n  } catch (e) {\n    print('Registration failed: $e');\n    return null;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final result = await signUpWithEmailCode('user@example.com', '123456', username: 'myusername', password: 'mypassword');\n  if (result != null) {\n    print('EmailRegistration successful');\n  }\n}\n```",
                "index": 2,
                "title": "Email Code Registration",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<Map<String, dynamic>?> signIn(String username, String password) async {\n  /// Username Password Login\n  final result = await cloudbase.request(\n    'POST',\n    '/auth/v1/signin',\n    body: {'username': username, 'password': password},\n  );\n\n  if (result != null) {\n    final accessToken = result['access_token'];\n    final refreshToken = result['refresh_token'];\n    final userId = result['sub'];\n\n    print('Login successful! User ID: $userId');\n    print('Access token: ${accessToken.substring(0, 20)}...');\n\n    // UpdateAccess token\n    cloudbase.updateAccessToken(accessToken);\n    return result;\n  }\n  return null;\n}\n\n// Usage Example\nvoid main() async {\n  final result = await signIn('your_username', 'your_password');\n  print(result);\n}\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<bool> loginWithPhoneCode(String phoneNumber, String verificationCode, {String? captchaToken}) async {\n  try {\n    // Step1: SendSMSVerification code\n    final sendBody = {\n      'phone_number': phoneNumber.startsWith('+86') ? phoneNumber : '+86$phoneNumber',\n      'target': 'ANY',  // \"ANY\" - No restriction，Noneregardless of userYesNoexistsallSend; \"USER\" - AccountmustexiststhenSend\n    };\n\n    final sendHeaders = captchaToken != null ? {'x-captcha-token': captchaToken} : null;\n\n    final sendResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification',\n      body: sendBody,\n      customHeaders: sendHeaders,\n    );\n\n    if (sendResult == null) {\n      print('Send Codefailed');\n      return false;\n    }\n\n    final verificationId = sendResult['verification_id'];\n    print('Verification codeSendsuccessful! ID: $verificationId');\n\n    // Step2: Verify the code\n    final verifyResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification/verify',\n      body: {\n        'verification_id': verificationId,\n        'verification_code': verificationCode,\n      },\n    );\n\n    if (verifyResult == null) {\n      print('Verification codeError');\n      return false;\n    }\n\n    final verificationToken = verifyResult['verification_token'];\n    print('Verifysuccessful!');\n\n    // Step3: UseVerifytokenLogin\n    final loginResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/signin',\n      body: {\n        'phone_number': phoneNumber.startsWith('+86') ? phoneNumber : '+86$phoneNumber',\n        'verification_token': verificationToken,\n      },\n    );\n\n    if (loginResult != null) {\n      final accessToken = loginResult['access_token'];\n      print('Login successful!');\n      cloudbase.updateAccessToken(accessToken);\n      return true;\n    }\n\n    print('Login failed');\n    return false;\n  } catch (e) {\n    print('Login failed: $e');\n    return false;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final success = await loginWithPhoneCode('13800138000', '123456');\n  if (success) {\n    print('Phone numberLogin successful');\n  }\n}\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login",
                "content": []
              },
              {
                "markdown": "```dart\nimport 'cloudbase_client.dart';\n\nFuture<bool> loginWithEmailCode(String email, String verificationCode, {String? captchaToken}) async {\n  try {\n    // Step1: SendEmailVerification code\n    final sendBody = {\n      'email': email,\n      'target': 'ANY',  // \"ANY\" - No restriction，Noneregardless of userYesNoexistsallSend; \"USER\" - AccountmustexiststhenSend\n    };\n\n    final sendHeaders = captchaToken != null ? {'x-captcha-token': captchaToken} : null;\n\n    final sendResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification',\n      body: sendBody,\n      customHeaders: sendHeaders,\n    );\n\n    if (sendResult == null) {\n      print('Send Codefailed');\n      return false;\n    }\n\n    final verificationId = sendResult['verification_id'];\n    print('Verification codeSendsuccessful! ID: $verificationId');\n\n    // Step2: Verify the code\n    final verifyResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/verification/verify',\n      body: {\n        'verification_id': verificationId,\n        'verification_code': verificationCode,\n      },\n    );\n\n    if (verifyResult == null) {\n      print('Verification codeError');\n      return false;\n    }\n\n    final verificationToken = verifyResult['verification_token'];\n    print('Verifysuccessful!');\n\n    // Step3: UseVerifytokenLogin\n    final loginResult = await cloudbase.request(\n      'POST',\n      '/auth/v1/signin',\n      body: {\n        'email': email,\n        'verification_token': verificationToken,\n      },\n    );\n\n    if (loginResult != null) {\n      final accessToken = loginResult['access_token'];\n      print('Login successful!');\n      cloudbase.updateAccessToken(accessToken);\n      return true;\n    }\n\n    print('Login failed');\n    return false;\n  } catch (e) {\n    print('Login failed: $e');\n    return false;\n  }\n}\n\n// Usage Example\nvoid main() async {\n  final success = await loginWithEmailCode('user@example.com', '123456');\n  if (success) {\n    print('EmailLogin successful');\n  }\n}\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login",
                "content": []
              }
            ]
          }
        ]
      }
    ],
    "_id": "cdc9a75069a9286d00430fcf1d4ded2d",
    "_openid": "anon",
    "createdAt": 1769744598537,
    "updatedAt": 1769766696389
  },
  {
    "category": "Framework Integration,Mobile Frameworks,React Native",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 12,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/api-reference/webv2/adapter",
    "content": [
      {
        "markdown": "`@cloudbase/js-sdk` Combine with `@cloudbase/adapter-rn` allows you toin React Native project",
        "index": 1,
        "title": "Install SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```bash\nnpm i @cloudbase/js-sdk @cloudbase/adapter-rn\n```",
            "index": 1,
            "title": "npm"
          },
          {
            "markdown": "```bash\nyarn add @cloudbase/js-sdk @cloudbase/adapter-rn\n```",
            "index": 2,
            "title": "yarn"
          },
          {
            "markdown": "```bash\npnpm add @cloudbase/js-sdk @cloudbase/adapter-rn\n```\n\niOS needInstallNativeDependency：\n\n```bash\ncd ios && pod install && cd ..\n```",
            "index": 3,
            "title": "pnpm"
          }
        ]
      },
      {
        "markdown": "Add the following code to your React Native project",
        "index": 2,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nimport cloudbaseSDK from \"@cloudbase/js-sdk\";\nimport adapter from \"@cloudbase/adapter-rn\";\n\ncloudbaseSDK.useAdapters(adapter);\n\nconst cloudbase = cloudbaseSDK.init({\n  // Environment ID\n  env: \"{%ENV_ID%}\",\n  // region\n  region: \"{%REGION%}\",\n  // Anonymous access token\n  accessKey: \"{%PUBLISHABLE_KEY%}\"\n});\n\nexport default cloudbase;\n```",
            "index": 1,
            "title": "src/utils/cloudbase.js"
          }
        ]
      },
      {
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, Button, FlatList, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function QueryData() {\n  const [dataList, setDataList] = useState([]);\n\n  // Query Data\n  const getData = async () => {\n    try {\n      const { data, error } = await cloudbase\n        .database()\n        .from(\"{%TABLE_NAME%}\")\n        .select(\"*\")\n        .limit(10);\n\n      if (!error) {\n        setDataList(data);\n        Alert.alert(\"successful\", \"Querysuccessful\");\n      } else {\n        Alert.alert(\"failed\", \"Queryfailed\");\n      }\n    } catch (error) {\n      Alert.alert(\"Error\", `Queryfailed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"Query Data\" onPress={getData} />\n      {dataList.length > 0 ? (\n        <FlatList\n          data={dataList}\n          keyExtractor={(item, index) => index.toString()}\n          renderItem={({ item }) => (\n            <View style={styles.item}>\n              <Text>{JSON.stringify(item)}</Text>\n            </View>\n          )}\n        />\n      ) : (\n        <Text>temporarilyNoneData</Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  item: {\n    padding: 10,\n    marginVertical: 5,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title });\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function AddData() {\n  const [title, setTitle] = useState(\"\");\n\n  // Insert Data\n  const addData = async () => {\n    try {\n      const { data, error } = await cloudbase\n        .database()\n        .from(\"{%TABLE_NAME%}\")\n        .insert({ title });\n\n      if (!error) {\n        Alert.alert(\"successful\", \"Insert successful\");\n        setTitle(\"\");\n      } else {\n        Alert.alert(\"failed\", \"Insert failed\");\n      }\n    } catch (error) {\n      Alert.alert(\"Error\", `Insert failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={title}\n        onChangeText={setTitle}\n        placeholder=\"Please enterTitle\"\n      />\n      <Button title=\"Insert Data\" onPress={addData} disabled={!title} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ title: newTitle })\n  .eq(\"id\", dataId);\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function UpdateData() {\n  const [dataId, setDataId] = useState(\"\");\n  const [newTitle, setNewTitle] = useState(\"\");\n\n  // Update Data\n  const updateData = async () => {\n    try {\n      const { data, error } = await cloudbase\n        .database()\n        .from(\"{%TABLE_NAME%}\")\n        .update({ title: newTitle })\n        .eq(\"id\", dataId);\n\n      if (!error) {\n        Alert.alert(\"successful\", \"Update successful\");\n        setDataId(\"\");\n        setNewTitle(\"\");\n      } else {\n        Alert.alert(\"failed\", \"Update failed\");\n      }\n    } catch (error) {\n      Alert.alert(\"Error\", `Update failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>DataID：</Text>\n      <TextInput\n        style={styles.input}\n        value={dataId}\n        onChangeText={setDataId}\n        placeholder=\"Please enterDataID\"\n      />\n      <Text>New Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={newTitle}\n        onChangeText={setNewTitle}\n        placeholder=\"Please enterNew Title\"\n      />\n      <Button\n        title=\"Update Data\"\n        onPress={updateData}\n        disabled={!dataId || !newTitle}\n      />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: parseInt(id), title });\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function UpsertData() {\n  const [id, setId] = useState(\"\");\n  const [title, setTitle] = useState(\"\");\n\n  // Upsert Data\n  const upsertData = async () => {\n    try {\n      const { data, error } = await cloudbase\n        .database()\n        .from(\"{%TABLE_NAME%}\")\n        .upsert({ id: parseInt(id), title });\n\n      if (!error) {\n        Alert.alert(\"successful\", \"Operation successful\");\n        setId(\"\");\n        setTitle(\"\");\n      } else {\n        Alert.alert(\"failed\", \"Operation failed\");\n      }\n    } catch (error) {\n      Alert.alert(\"Error\", `Operation failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>ID：</Text>\n      <TextInput\n        style={styles.input}\n        value={id}\n        onChangeText={setId}\n        placeholder=\"Please enterID\"\n        keyboardType=\"numeric\"\n      />\n      <Text>Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={title}\n        onChangeText={setTitle}\n        placeholder=\"Please enterTitle\"\n      />\n      <Button\n        title=\"UpdateorCreate\"\n        onPress={upsertData}\n        disabled={!id || !title}\n      />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 4,
                "title": "Upsert Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst { data, error } = await cloudbase\n  .database()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", dataId);\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function DeleteData() {\n  const [dataId, setDataId] = useState(\"\");\n\n  // Delete Data\n  const deleteData = async () => {\n    try {\n      const { data, error } = await cloudbase\n        .database()\n        .from(\"{%TABLE_NAME%}\")\n        .delete()\n        .eq(\"id\", dataId);\n\n      if (!error) {\n        Alert.alert(\"successful\", \"Delete successful\");\n        setDataId(\"\");\n      } else {\n        Alert.alert(\"failed\", \"Delete failed\");\n      }\n    } catch (error) {\n      Alert.alert(\"Error\", `Delete failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>DataID：</Text>\n      <TextInput\n        style={styles.input}\n        value={dataId}\n        onChangeText={setDataId}\n        placeholder=\"Please entershouldDeleteDataID\"\n      />\n      <Button title=\"Delete Data\" onPress={deleteData} disabled={!dataId} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 5,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, Button, FlatList, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function QueryDocData() {\n  const [dataList, setDataList] = useState([]);\n\n  // Query Data\n  const getData = async () => {\n    try {\n      const db = cloudbase.database();\n      const res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n\n      setDataList(res.data);\n      Alert.alert(\"successful\", \"Querysuccessful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Queryfailed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"Query Data\" onPress={getData} />\n      {dataList.length > 0 ? (\n        <FlatList\n          data={dataList}\n          keyExtractor={(item, index) => index.toString()}\n          renderItem={({ item }) => (\n            <View style={styles.item}>\n              <Text>{JSON.stringify(item)}</Text>\n            </View>\n          )}\n        />\n      ) : (\n        <Text>temporarilyNoneData</Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  item: {\n    padding: 10,\n    marginVertical: 5,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({ title });\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function AddDocData() {\n  const [title, setTitle] = useState(\"\");\n\n  // Insert Data\n  const addData = async () => {\n    try {\n      const db = cloudbase.database();\n      const res = await db.collection(\"{%TABLE_NAME%}\").add({ title });\n\n      Alert.alert(\"successful\", `Insert successful! id: ${res.id}`);\n      setTitle(\"\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Insert failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={title}\n        onChangeText={setTitle}\n        placeholder=\"Please enterTitle\"\n      />\n      <Button title=\"Insert Data\" onPress={addData} disabled={!title} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(dataId).update({ title: newTitle });\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function UpdateDocData() {\n  const [dataId, setDataId] = useState(\"\");\n  const [newTitle, setNewTitle] = useState(\"\");\n\n  // Update Data\n  const updateData = async () => {\n    try {\n      const db = cloudbase.database();\n      await db\n        .collection(\"{%TABLE_NAME%}\")\n        .doc(dataId)\n        .update({ title: newTitle });\n\n      Alert.alert(\"successful\", \"Update successful\");\n      setDataId(\"\");\n      setNewTitle(\"\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Update failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>DataID：</Text>\n      <TextInput\n        style={styles.input}\n        value={dataId}\n        onChangeText={setDataId}\n        placeholder=\"Please enterDataID\"\n      />\n      <Text>New Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={newTitle}\n        onChangeText={setNewTitle}\n        placeholder=\"Please enterNew Title\"\n      />\n      <Button\n        title=\"Update Data\"\n        onPress={updateData}\n        disabled={!dataId || !newTitle}\n      />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(dataId).remove();\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function DeleteDocData() {\n  const [dataId, setDataId] = useState(\"\");\n\n  // Delete Data\n  const deleteData = async () => {\n    try {\n      const db = cloudbase.database();\n      await db.collection(\"{%TABLE_NAME%}\").doc(dataId).remove();\n\n      Alert.alert(\"successful\", \"Delete successful\");\n      setDataId(\"\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Delete failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>DataID：</Text>\n      <TextInput\n        style={styles.input}\n        value={dataId}\n        onChangeText={setDataId}\n        placeholder=\"Please entershouldDeleteDataID\"\n      />\n      <Button title=\"Delete Data\" onPress={deleteData} disabled={!dataId} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, Button, FlatList, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function QueryModelData() {\n  const [dataList, setDataList] = useState([]);\n\n  // Query Data\n  const getData = async () => {\n    try {\n      const res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n        pageNumber: 1,\n        pagesize: 10\n      });\n\n      setDataList(res.data?.records || []);\n      Alert.alert(\"successful\", \"Querysuccessful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Queryfailed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"Query Data\" onPress={getData} />\n      {dataList.length > 0 ? (\n        <FlatList\n          data={dataList}\n          keyExtractor={(item, index) => index.toString()}\n          renderItem={({ item }) => (\n            <View style={styles.item}>\n              <Text>{JSON.stringify(item)}</Text>\n            </View>\n          )}\n        />\n      ) : (\n        <Text>temporarilyNoneData</Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  item: {\n    padding: 10,\n    marginVertical: 5,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: { title }\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function AddModelData() {\n  const [title, setTitle] = useState(\"\");\n\n  // Insert Data\n  const addData = async () => {\n    try {\n      const res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n        data: { title }\n      });\n\n      Alert.alert(\"successful\", `Insert successful! id: ${res.data.id}`);\n      setTitle(\"\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Insert failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={title}\n        onChangeText={setTitle}\n        placeholder=\"Please enterTitle\"\n      />\n      <Button title=\"Insert Data\" onPress={addData} disabled={!title} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nawait cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: { title: newTitle },\n  filter: { where: { _id: { $eq: dataId } } }\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function UpdateModelData() {\n  const [dataId, setDataId] = useState(\"\");\n  const [newTitle, setNewTitle] = useState(\"\");\n\n  // Update Data\n  const updateData = async () => {\n    try {\n      await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n        data: { title: newTitle },\n        filter: { where: { _id: { $eq: dataId } } }\n      });\n\n      Alert.alert(\"successful\", \"Update successful\");\n      setDataId(\"\");\n      setNewTitle(\"\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Update failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>DataID：</Text>\n      <TextInput\n        style={styles.input}\n        value={dataId}\n        onChangeText={setDataId}\n        placeholder=\"Please enterDataID\"\n      />\n      <Text>New Title：</Text>\n      <TextInput\n        style={styles.input}\n        value={newTitle}\n        onChangeText={setNewTitle}\n        placeholder=\"Please enterNew Title\"\n      />\n      <Button\n        title=\"Update Data\"\n        onPress={updateData}\n        disabled={!dataId || !newTitle}\n      />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nawait cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: { where: { _id: { $eq: dataId } } }\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function DeleteModelData() {\n  const [dataId, setDataId] = useState(\"\");\n\n  // Delete Data\n  const deleteData = async () => {\n    try {\n      await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n        filter: { where: { _id: { $eq: dataId } } }\n      });\n\n      Alert.alert(\"successful\", \"Delete successful\");\n      setDataId(\"\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Delete failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>DataID：</Text>\n      <TextInput\n        style={styles.input}\n        value={dataId}\n        onChangeText={setDataId}\n        placeholder=\"Please entershouldDeleteDataID\"\n      />\n      <Button title=\"Delete Data\" onPress={deleteData} disabled={!dataId} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {}\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function CallFunction() {\n  const [result, setResult] = useState(null);\n\n  // CallCloud Function\n  const callFunction = async () => {\n    try {\n      const res = await cloudbase.callFunction({\n        name: \"{%FUNCTION_NAME%}\",\n        data: {}\n      });\n\n      setResult(res.result);\n      Alert.alert(\"successful\", \"Callsuccessful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Call failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"CallCloud Function\" onPress={callFunction} />\n      {result && (\n        <View style={styles.resultContainer}>\n          <Text>Return result：</Text>\n          <Text>{JSON.stringify(result)}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call {%SERVICE_NAME%} Cloud Runservice\nconst res = await cloudbase.callContainer({\n  name: \"{%SERVICE_NAME%}\"\n  method: 'POST',\n  path: '/',\n  header:{\n    'Content-Type': 'application/json; charset=utf-8'\n  },\n  data: {},\n});\n```\n\n**Full Example：**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function CallRun() {\n  const [result, setResult] = useState(null);\n\n  // CallCloud Run\n  const callRun = async () => {\n    try {\n      // Call {%SERVICE_NAME%} Cloud Runservice\n      const res = await cloudbase.callContainer({\n        name: \"{%SERVICE_NAME%}\"\n        method: 'POST',\n        path: '/',\n        header:{\n          'Content-Type': 'application/json; charset=utf-8'\n        },\n        data: {},\n      });\n\n      setResult(res);\n      Alert.alert(\"successful\", \"Callsuccessful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Call failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"CallCloud Run\" onPress={callRun} />\n      {result && (\n        <View style={styles.resultContainer}>\n          <Text>Return result：</Text>\n          <Text>{JSON.stringify(result)}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 6,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.uploadFile({\n  cloudPath: cloudPath,\n  filePath: asset.uri\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, Button, StyleSheet, Alert } from \"react-native\";\nimport { launchImageLibrary } from \"react-native-image-picker\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function UploadFile() {\n  const [fileId, setFileId] = useState(\"\");\n\n  // Upload File\n  const uploadFile = async () => {\n    try {\n      const result = await launchImageLibrary({\n        mediaType: \"photo\",\n        quality: 0.8\n      });\n\n      if (result.didCancel) {\n        return;\n      }\n\n      if (result.errorCode) {\n        Alert.alert(\"Error\", \"SelectImagefailed\");\n        return;\n      }\n\n      const asset = result.assets[0];\n      const fileExtension = asset.fileName?.split(\".\").pop() || \"jpg\";\n      const cloudPath = `images/${Date.now()}-${Math.random()}.${fileExtension}`;\n\n      const res = await cloudbase.uploadFile({\n        cloudPath: cloudPath,\n        filePath: asset.uri\n      });\n\n      setFileId(res.fileID);\n      Alert.alert(\"successful\", \"Upload successful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Uploadfailed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"SelectandUploadImage\" onPress={uploadFile} />\n      {fileId && (\n        <View style={styles.resultContainer}>\n          <Text>Upload successful！</Text>\n          <Text>fileID: {fileId}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.getTempFileURL({\n  fileList: [fileId]\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport {\n  View,\n  Text,\n  TextInput,\n  Button,\n  Image,\n  StyleSheet,\n  Alert\n} from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function GetFileUrl() {\n  const [fileId, setFileId] = useState(\"\");\n  const [fileUrl, setFileUrl] = useState(\"\");\n\n  // Get File URL\n  const getFileUrl = async () => {\n    try {\n      const res = await cloudbase.getTempFileURL({\n        fileList: [fileId]\n      });\n\n      setFileUrl(res.fileList[0].tempFileURL);\n      Alert.alert(\"successful\", \"Getsuccessful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Getfailed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>fileID：</Text>\n      <TextInput\n        style={styles.input}\n        value={fileId}\n        onChangeText={setFileId}\n        placeholder=\"Please enterfileID (cloud://xxx.png)\"\n      />\n      <Button title=\"Get File URL\" onPress={getFileUrl} disabled={!fileId} />\n      {fileUrl && (\n        <View style={styles.resultContainer}>\n          <Text>fileURL：</Text>\n          <Text>{fileUrl}</Text>\n          <Image\n            source={{ uri: fileUrl }}\n            style={styles.image}\n            resizeMode=\"contain\"\n          />\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  },\n  image: {\n    width: \"100%\",\n    height: 200,\n    marginTop: 10\n  }\n});\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.downloadFile({\n  fileID: fileId\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function DownloadFile() {\n  const [fileId, setFileId] = useState(\"\");\n  const [localPath, setLocalPath] = useState(\"\");\n\n  // Download File\n  const downloadFile = async () => {\n    try {\n      const res = await cloudbase.downloadFile({\n        fileID: fileId\n      });\n\n      setLocalPath(res.tempFilePath);\n      Alert.alert(\"successful\", \"Downloadsuccessful\");\n    } catch (error) {\n      Alert.alert(\"Error\", `Downloadfailed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>fileID：</Text>\n      <TextInput\n        style={styles.input}\n        value={fileId}\n        onChangeText={setFileId}\n        placeholder=\"Please enterfileID (cloud://xxx.png)\"\n      />\n      <Button title=\"Download File\" onPress={downloadFile} disabled={!fileId} />\n      {localPath && (\n        <View style={styles.resultContainer}>\n          <Text>Downloadsuccessful！</Text>\n          <Text>localPath: {localPath}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.deleteFile({\n  fileList: [fileId]\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function DeleteFile() {\n  const [fileId, setFileId] = useState(\"\");\n\n  // Delete File\n  const deleteFile = async () => {\n    try {\n      const res = await cloudbase.deleteFile({\n        fileList: [fileId]\n      });\n\n      if (res.fileList[0].code === \"SUCCESS\") {\n        Alert.alert(\"successful\", \"Delete successful\");\n        setFileId(\"\");\n      } else {\n        Alert.alert(\"failed\", \"Delete failed\");\n      }\n    } catch (error) {\n      Alert.alert(\"Error\", `Delete failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>fileID：</Text>\n      <TextInput\n        style={styles.input}\n        value={fileId}\n        onChangeText={setFileId}\n        placeholder=\"Please enterfileID (cloud://xxx.png)\"\n      />\n      <Button title=\"Delete File\" onPress={deleteFile} disabled={!fileId} />\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  }\n});\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst ai = cloudbase.ai();\nconst model = ai.createModel(\"{%AI_MODEL_NAME%}\");\n\n// EnsurealreadyLogin\nconst loginState = await cloudbase.auth().getLoginState();\nif (!loginState) {\n  await cloudbase.auth().signInAnonymously();\n}\n\nconst res = await model.streamText({\n  model: \"{%AI_SUB_MODEL_NAME%}\",\n  messages: [\n    {\n      role: \"system\",\n      content:\n        \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\"\n    },\n    { role: \"user\", content: input }\n  ]\n});\n\nfor await (let str of res.textStream) {\n  // ProcessStreaming response\n}\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport {\n  View,\n  Text,\n  TextInput,\n  Button,\n  StyleSheet,\n  Alert,\n  ActivityIndicator\n} from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function CallAIModel() {\n  const [input, setInput] = useState(\"\");\n  const [response, setResponse] = useState(\"\");\n  const [isGenerating, setIsGenerating] = useState(false);\n\n  // CallAI Model\n  const callAIModel = async () => {\n    setIsGenerating(true);\n    setResponse(\"\");\n\n    try {\n      const ai = cloudbase.ai();\n      const model = ai.createModel(\"{%AI_MODEL_NAME%}\");\n\n      // EnsurealreadyLogin\n      const loginState = await cloudbase.auth().getLoginState();\n      if (!loginState) {\n        await cloudbase.auth().signInAnonymously();\n      }\n\n      const res = await model.streamText({\n        model: \"{%AI_SUB_MODEL_NAME%}\",\n        messages: [\n          {\n            role: \"system\",\n            content:\n              \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\"\n          },\n          { role: \"user\", content: input }\n        ]\n      });\n\n      for await (let str of res.textStream) {\n        setResponse(prev => prev + str);\n      }\n\n      Alert.alert(\"successful\", \"GenerateDone\");\n    } catch (err) {\n      Alert.alert(\"Error\", `Generation failed: ${err.message}`);\n    } finally {\n      setIsGenerating(false);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Inputtopic：</Text>\n      <TextInput\n        style={styles.input}\n        value={input}\n        onChangeText={setInput}\n        placeholder=\"Please entertopic，such as：Spring\"\n      />\n      <Button\n        title=\"GenerateContent\"\n        onPress={callAIModel}\n        disabled={!input || isGenerating}\n      />\n      {isGenerating && <ActivityIndicator size=\"large\" style={styles.loader} />}\n      {response && (\n        <View style={styles.resultContainer}>\n          <Text>GenerateResult：</Text>\n          <Text>{response}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  loader: {\n    marginVertical: 20\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst res = await cloudbase.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: { prompt: \"A cute cat playing in the sunshine\" }\n});\n\nif (res.result.success) {\n  console.log(\"Image URL:\", res.result.imageUrl);\n  console.log(\"Optimized prompt:\", res.result.revised_prompt);\n} else {\n  console.error(\"Generation failed:\", res.result.code, res.result.message);\n}\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport {\n  View,\n  Text,\n  TextInput,\n  Button,\n  Image,\n  StyleSheet,\n  Alert,\n  ActivityIndicator\n} from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function GenerateImage() {\n  const [prompt, setPrompt] = useState(\"\");\n  const [imageUrl, setImageUrl] = useState(\"\");\n  const [revisedPrompt, setRevisedPrompt] = useState(\"\");\n  const [isGenerating, setIsGenerating] = useState(false);\n\n  // Generate Image\n  const generateImage = async () => {\n    setIsGenerating(true);\n    setImageUrl(\"\");\n    setRevisedPrompt(\"\");\n\n    try {\n      const res = await cloudbase.callFunction({\n        name: \"<YOUR_FUNCTION_NAME>\",\n        data: { prompt }\n      });\n\n      if (res.result.success) {\n        setImageUrl(res.result.imageUrl);\n        setRevisedPrompt(res.result.revised_prompt || \"\");\n        Alert.alert(\"successful\", \"ImageGeneration successful\");\n      } else {\n        Alert.alert(\n          \"failed\",\n          `Generation failed: ${res.result.code} - ${res.result.message}`\n        );\n      }\n    } catch (err) {\n      Alert.alert(\"Error\", `Generation failed: ${err.message}`);\n    } finally {\n      setIsGenerating(false);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>InputDescription：</Text>\n      <TextInput\n        style={styles.input}\n        value={prompt}\n        onChangeText={setPrompt}\n        placeholder=\"for example：A cute cat playing in the sunshine\"\n        multiline\n      />\n      <Button\n        title=\"Generate Image\"\n        onPress={generateImage}\n        disabled={!prompt || isGenerating}\n      />\n      {isGenerating && <ActivityIndicator size=\"large\" style={styles.loader} />}\n      {imageUrl && (\n        <View style={styles.resultContainer}>\n          <Text style={styles.label}>GenerateResult：</Text>\n          <Image\n            source={{ uri: imageUrl }}\n            style={styles.image}\n            resizeMode=\"contain\"\n          />\n          {revisedPrompt && (\n            <View style={styles.promptContainer}>\n              <Text style={styles.label}>Optimized prompt：</Text>\n              <Text>{revisedPrompt}</Text>\n            </View>\n          )}\n          <Text style={styles.note}>Note：Image URLValidis valid for24hours</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    minHeight: 80,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    paddingVertical: 10,\n    borderRadius: 5,\n    textAlignVertical: \"top\"\n  },\n  loader: {\n    marginVertical: 20\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  },\n  label: {\n    fontWeight: \"bold\",\n    marginBottom: 5\n  },\n  image: {\n    width: \"100%\",\n    height: 300,\n    marginVertical: 10\n  },\n  promptContainer: {\n    marginTop: 10\n  },\n  note: {\n    marginTop: 10,\n    fontSize: 12,\n    color: \"#666\",\n    fontStyle: \"italic\"\n  }\n});\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\n/**\n * React Native Call Agent Example (AG-UI Protocol)\n * Protocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n */\nimport cloudbase from './utils/cloudbase';\n\n// EnsurealreadyLogin\nconst loginState = await cloudbase.auth().getLoginState();\nif (!loginState) {\n  await cloudbase.auth().signInAnonymously();\n}\n\nconst ai = cloudbase.ai();\n\n// Build message list (AG-UI protocol format)\nconst messages = [\n  {\n    id: 'msg_001',\n    role: 'user',\n    content: input,\n  },\n];\n\n// AG-UI Protocol request parameters\nconst res = await ai.bot.sendMessage({\n  botId: '{%AGENT_ID%}',\n  data: {\n    messages,                                            // Required: Message list\n    threadId: '550e8400-e29b-41d4-a716-446655440000',   // Optional: Session ID for multi-turn conversation\n    runId: 'run_001',                                    // Optional: Run ID for execution tracking\n    tools: [],                                           // Optional: Frontend tool definitions\n    context: [],                                         // Optional: Context information\n    forwardedProps: {},                                  // Optional: Pass-through parameters\n  },\n});\n\n// ProcessStreaming response\nfor await (const str of res.textStream) {\n  console.log(str);\n}\n\n```\n\n**Full Example:**\n\n```jsx\n/**\n * React Native Call Agent Full Example（AG-UI Protocol)\n * Protocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n */\nimport React, { useState } from 'react';\nimport { View, Text, TextInput, Button, StyleSheet, Alert, ActivityIndicator } from 'react-native';\nimport cloudbase from './utils/cloudbase';\n\nexport default function CallAgent() {\n  const [input, setInput] = useState('');\n  const [response, setResponse] = useState('');\n  const [isGenerating, setIsGenerating] = useState(false);\n\n  // CallAgent（AG-UI Protocol)\n  const callAgent = async () => {\n    setIsGenerating(true);\n    setResponse('');\n\n    try {\n      const ai = cloudbase.ai();\n\n      // EnsurealreadyLogin\n      const loginState = await cloudbase.auth().getLoginState();\n      if (!loginState) {\n        await cloudbase.auth().signInAnonymously();\n      }\n\n      // Build message list (AG-UI protocol format)\n      const messages = [\n        {\n          id: 'msg_001',\n          role: 'user',\n          content: input,\n        },\n      ];\n\n      // AG-UI Protocol request parameters\n      const res = await ai.bot.sendMessage({\n        botId: '{%AGENT_ID%}',\n        data: {\n          messages,                                            // Required: Message list\n          threadId: '550e8400-e29b-41d4-a716-446655440000',   // Optional: Session ID for multi-turn conversation\n          runId: 'run_001',                                    // Optional: Run ID for execution tracking\n          tools: [],                                           // Optional: Frontend tool definitions\n          context: [],                                         // Optional: Context information\n          forwardedProps: {},                                  // Optional: Pass-through parameters\n        },\n      });\n\n      // ProcessStreaming response\n      for await (const str of res.textStream) {\n        setResponse((prev) => prev + str);\n      }\n\n      Alert.alert('successful', 'GenerateDone');\n    } catch (err) {\n      Alert.alert('Error', `Generation failed: ${err.message}`);\n    } finally {\n      setIsGenerating(false);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Inputquestion：</Text>\n      <TextInput style={styles.input} value={input} onChangeText={setInput} placeholder=\"Please enterquestion，such as：Who are you\" />\n      <Button title=\"SendMessage\" onPress={callAgent} disabled={!input || isGenerating} />\n      {isGenerating && <ActivityIndicator size=\"large\" style={styles.loader} />}\n      {response && (\n        <View style={styles.resultContainer}>\n          <Text>answer：</Text>\n          <Text>{response}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20,\n  },\n  input: {\n    height: 40,\n    borderColor: '#ccc',\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5,\n  },\n  loader: {\n    marginVertical: 20,\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: '#f9f9f9',\n    borderRadius: 5,\n  },\n});\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst ai = cloudbase.ai();\n\n// EnsurealreadyLogin\nconst loginState = await cloudbase.auth().getLoginState();\nif (!loginState) {\n  await cloudbase.auth().signInAnonymously();\n}\n\nconst res = await ai.bot.sendMessage({\n  botId: \"{%AGENT_ID%}\",\n  msg: input\n});\n\nfor await (let str of res.textStream) {\n  // ProcessStreaming response\n}\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport {\n  View,\n  Text,\n  TextInput,\n  Button,\n  StyleSheet,\n  Alert,\n  ActivityIndicator\n} from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function CallAgent() {\n  const [input, setInput] = useState(\"\");\n  const [response, setResponse] = useState(\"\");\n  const [isGenerating, setIsGenerating] = useState(false);\n\n  // CallAgent\n  const callAgent = async () => {\n    setIsGenerating(true);\n    setResponse(\"\");\n\n    try {\n      const ai = cloudbase.ai();\n\n      // EnsurealreadyLogin\n      const loginState = await cloudbase.auth().getLoginState();\n      if (!loginState) {\n        await cloudbase.auth().signInAnonymously();\n      }\n\n      const res = await ai.bot.sendMessage({\n        botId: \"{%AGENT_ID%}\",\n        msg: input\n      });\n\n      for await (let str of res.textStream) {\n        setResponse(prev => prev + str);\n      }\n\n      Alert.alert(\"successful\", \"GenerateDone\");\n    } catch (err) {\n      Alert.alert(\"Error\", `Generation failed: ${err.message}`);\n    } finally {\n      setIsGenerating(false);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Inputquestion：</Text>\n      <TextInput\n        style={styles.input}\n        value={input}\n        onChangeText={setInput}\n        placeholder=\"Please enterquestion，such as：Who are you\"\n      />\n      <Button\n        title=\"SendMessage\"\n        onPress={callAgent}\n        disabled={!input || isGenerating}\n      />\n      {isGenerating && <ActivityIndicator size=\"large\" style={styles.loader} />}\n      {response && (\n        <View style={styles.resultContainer}>\n          <Text>answer：</Text>\n          <Text>{response}</Text>\n        </View>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  loader: {\n    marginVertical: 20\n  },\n  resultContainer: {\n    marginTop: 20,\n    padding: 10,\n    backgroundColor: \"#f9f9f9\",\n    borderRadius: 5\n  }\n});\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 9,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "Use **SMS Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMSVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: phone });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  phone_number: `+86 ${phone}`,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${phone.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function SmsRegister() {\n  const [phone, setPhone] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationId, setVerificationId] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ phone_number: phone });\n      setVerificationId(res.verification_id);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(`Send failed: ${error.message}`);\n    }\n  };\n\n  // Register\n  const register = async () => {\n    try {\n      const auth = cloudbase.auth();\n      // Verify the code\n      const verifyRes = await auth.verify({\n        verification_id: verificationId,\n        verification_code: code\n      });\n      // Register (auto-login if user exists)\n      await auth.signUp({\n        phone_number: `+86 ${phone}`,\n        verification_code: code,\n        verification_token: verifyRes.verification_token,\n        name: `user_${phone.slice(-4)}`,\n        password: \"admin@123\"\n      });\n      setMessage(\"Registration successful！\");\n      Alert.alert(\"successful\", \"Registration successful\");\n    } catch (error) {\n      setMessage(`Registration failed: ${error.message}`);\n      Alert.alert(\"failed\", `Registration failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Phone number：</Text>\n      <TextInput\n        style={styles.input}\n        value={phone}\n        onChangeText={setPhone}\n        placeholder=\"13800000000\"\n        keyboardType=\"phone-pad\"\n      />\n      <Text>Verification code：</Text>\n      <View style={styles.row}>\n        <TextInput\n          style={[styles.input, styles.codeInput]}\n          value={code}\n          onChangeText={setCode}\n          placeholder=\"Verification code\"\n          keyboardType=\"numeric\"\n        />\n        <Button title=\"Send Code\" onPress={sendCode} disabled={!phone} />\n      </View>\n      <Button\n        title=\"Register\"\n        onPress={register}\n        disabled={!verificationId || !code}\n      />\n      {message && (\n        <Text\n          style={[\n            styles.message,\n            { color: message.includes(\"successful\") ? \"green\" : \"red\" }\n          ]}\n        >\n          {message}\n        </Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  row: {\n    flexDirection: \"row\",\n    alignItems: \"center\"\n  },\n  codeInput: {\n    flex: 1,\n    marginRight: 10\n  },\n  message: {\n    marginTop: 20,\n    textAlign: \"center\"\n  }\n});\n```",
                "index": 1,
                "title": "SMS Code Registration",
                "content": []
              },
              {
                "markdown": "Use **Email Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  email,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${email.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function EmailRegister() {\n  const [email, setEmail] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationId, setVerificationId] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ email });\n      setVerificationId(res.verification_id);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(`Send failed: ${error.message}`);\n    }\n  };\n\n  // Register\n  const register = async () => {\n    try {\n      const auth = cloudbase.auth();\n      // Verify the code\n      const verifyRes = await auth.verify({\n        verification_id: verificationId,\n        verification_code: code\n      });\n      // Register (auto-login if user exists)\n      await auth.signUp({\n        email,\n        verification_code: code,\n        verification_token: verifyRes.verification_token,\n        name: `user_${email.slice(-4)}`,\n        password: \"admin@123\"\n      });\n      setMessage(\"Registration successful！\");\n      Alert.alert(\"successful\", \"Registration successful\");\n    } catch (error) {\n      setMessage(`Registration failed: ${error.message}`);\n      Alert.alert(\"failed\", `Registration failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Email：</Text>\n      <TextInput\n        style={styles.input}\n        value={email}\n        onChangeText={setEmail}\n        placeholder=\"example@email.com\"\n        keyboardType=\"email-address\"\n      />\n      <Text>Verification code：</Text>\n      <View style={styles.row}>\n        <TextInput\n          style={[styles.input, styles.codeInput]}\n          value={code}\n          onChangeText={setCode}\n          placeholder=\"Verification code\"\n          keyboardType=\"numeric\"\n        />\n        <Button title=\"Send Code\" onPress={sendCode} disabled={!email} />\n      </View>\n      <Button\n        title=\"Register\"\n        onPress={register}\n        disabled={!verificationId || !code}\n      />\n      {message && (\n        <Text\n          style={[\n            styles.message,\n            { color: message.includes(\"successful\") ? \"green\" : \"red\" }\n          ]}\n        >\n          {message}\n        </Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  row: {\n    flexDirection: \"row\",\n    alignItems: \"center\"\n  },\n  codeInput: {\n    flex: 1,\n    marginRight: 10\n  },\n  message: {\n    marginTop: 20,\n    textAlign: \"center\"\n  }\n});\n```",
                "index": 2,
                "title": "Email Code Registration",
                "content": []
              },
              {
                "markdown": "Use **Username Password Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **UsernamePasswordLogin**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\nawait auth.signIn({\n  username, // Can be username, phone or email\n  password\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function PasswordLogin() {\n  const [username, setUsername] = useState(\"\");\n  const [password, setPassword] = useState(\"\");\n  const [message, setMessage] = useState(\"\");\n\n  // Login\n  const login = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signIn({\n        username, // Can be username, phone or email\n        password\n      });\n      setMessage(\"Login successful！\");\n      Alert.alert(\"successful\", \"Login successful\");\n    } catch (error) {\n      setMessage(`Login failed: ${error.message}`);\n      Alert.alert(\"failed\", `Login failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Account：</Text>\n      <TextInput\n        style={styles.input}\n        value={username}\n        onChangeText={setUsername}\n        placeholder=\"Username/Phone/Email\"\n      />\n      <Text style={styles.note}>Note: Add country code for phone login +86</Text>\n      <Text>Password：</Text>\n      <TextInput\n        style={styles.input}\n        value={password}\n        onChangeText={setPassword}\n        placeholder=\"Enter password\"\n        secureTextEntry\n      />\n      <Button title=\"Login\" onPress={login} disabled={!username || !password} />\n      {message && (\n        <Text\n          style={[\n            styles.message,\n            { color: message.includes(\"successful\") ? \"green\" : \"red\" }\n          ]}\n        >\n          {message}\n        </Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  note: {\n    fontSize: 12,\n    color: \"#666\",\n    marginBottom: 10\n  },\n  message: {\n    marginTop: 20,\n    textAlign: \"center\"\n  }\n});\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login",
                "content": []
              },
              {
                "markdown": "Use **SMS Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMS Verification Login**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n\n// Login\nawait auth.signInWithSms({\n  verificationInfo: res,\n  verificationCode: code,\n  phoneNum: `+86 ${phone}`\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function SmsLogin() {\n  const [phone, setPhone] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationInfo, setVerificationInfo] = useState(null);\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n      setVerificationInfo(res);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(`Send failed: ${error.message}`);\n    }\n  };\n\n  // Login\n  const login = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInWithSms({\n        verificationInfo,\n        verificationCode: code,\n        phoneNum: `+86 ${phone}`\n      });\n      setMessage(\"Login successful！\");\n      Alert.alert(\"successful\", \"Login successful\");\n    } catch (error) {\n      setMessage(`Login failed: ${error.message}`);\n      Alert.alert(\"failed\", `Login failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Phone number：</Text>\n      <TextInput\n        style={styles.input}\n        value={phone}\n        onChangeText={setPhone}\n        placeholder=\"13800000000\"\n        keyboardType=\"phone-pad\"\n      />\n      <Text>Verification code：</Text>\n      <View style={styles.row}>\n        <TextInput\n          style={[styles.input, styles.codeInput]}\n          value={code}\n          onChangeText={setCode}\n          placeholder=\"Verification code\"\n          keyboardType=\"numeric\"\n        />\n        <Button title=\"Send Code\" onPress={sendCode} disabled={!phone} />\n      </View>\n      <Button\n        title=\"Login\"\n        onPress={login}\n        disabled={!verificationInfo || !code}\n      />\n      {message && (\n        <Text\n          style={[\n            styles.message,\n            { color: message.includes(\"successful\") ? \"green\" : \"red\" }\n          ]}\n        >\n          {message}\n        </Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  row: {\n    flexDirection: \"row\",\n    alignItems: \"center\"\n  },\n  codeInput: {\n    flex: 1,\n    marginRight: 10\n  },\n  message: {\n    marginTop: 20,\n    textAlign: \"center\"\n  }\n});\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login",
                "content": []
              },
              {
                "markdown": "Use **Email Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Login\nawait auth.signInWithEmail({\n  verificationInfo: res,\n  verificationCode: code,\n  email\n});\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Text, TextInput, Button, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function EmailLogin() {\n  const [email, setEmail] = useState(\"\");\n  const [code, setCode] = useState(\"\");\n  const [verificationInfo, setVerificationInfo] = useState(null);\n  const [message, setMessage] = useState(\"\");\n\n  // Send Code\n  const sendCode = async () => {\n    try {\n      const auth = cloudbase.auth();\n      const res = await auth.getVerification({ email });\n      setVerificationInfo(res);\n      setMessage(\"Verification code sent！\");\n    } catch (error) {\n      setMessage(`Send failed: ${error.message}`);\n    }\n  };\n\n  // Login\n  const login = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInWithEmail({\n        verificationInfo,\n        verificationCode: code,\n        email\n      });\n      setMessage(\"Login successful！\");\n      Alert.alert(\"successful\", \"Login successful\");\n    } catch (error) {\n      setMessage(`Login failed: ${error.message}`);\n      Alert.alert(\"failed\", `Login failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Text>Email：</Text>\n      <TextInput\n        style={styles.input}\n        value={email}\n        onChangeText={setEmail}\n        placeholder=\"example@email.com\"\n        keyboardType=\"email-address\"\n      />\n      <Text>Verification code：</Text>\n      <View style={styles.row}>\n        <TextInput\n          style={[styles.input, styles.codeInput]}\n          value={code}\n          onChangeText={setCode}\n          placeholder=\"Verification code\"\n          keyboardType=\"numeric\"\n        />\n        <Button title=\"Send Code\" onPress={sendCode} disabled={!email} />\n      </View>\n      <Button\n        title=\"Login\"\n        onPress={login}\n        disabled={!verificationInfo || !code}\n      />\n      {message && (\n        <Text\n          style={[\n            styles.message,\n            { color: message.includes(\"successful\") ? \"green\" : \"red\" }\n          ]}\n        >\n          {message}\n        </Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20\n  },\n  input: {\n    height: 40,\n    borderColor: \"#ccc\",\n    borderWidth: 1,\n    marginVertical: 10,\n    paddingHorizontal: 10,\n    borderRadius: 5\n  },\n  row: {\n    flexDirection: \"row\",\n    alignItems: \"center\"\n  },\n  codeInput: {\n    flex: 1,\n    marginRight: 10\n  },\n  message: {\n    marginTop: 20,\n    textAlign: \"center\"\n  }\n});\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login",
                "content": []
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport cloudbase from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\nawait auth.signInAnonymously();\n```\n\n**Full Example:**\n\n```jsx\nimport React, { useState } from \"react\";\nimport { View, Button, Text, StyleSheet, Alert } from \"react-native\";\nimport cloudbase from \"./utils/cloudbase\";\n\nexport default function AnonymousLogin() {\n  const [message, setMessage] = useState(\"\");\n\n  // anonymousLogin\n  const anonymousLogin = async () => {\n    try {\n      const auth = cloudbase.auth();\n      await auth.signInAnonymously();\n      setMessage(\"anonymousLogin successful！\");\n      Alert.alert(\"successful\", \"anonymousLogin successful\");\n    } catch (error) {\n      setMessage(`Login failed: ${error.message}`);\n      Alert.alert(\"failed\", `Login failed: ${error.message}`);\n    }\n  };\n\n  return (\n    <View style={styles.container}>\n      <Button title=\"anonymousLogin\" onPress={anonymousLogin} />\n      {message && (\n        <Text\n          style={[\n            styles.message,\n            { color: message.includes(\"successful\") ? \"green\" : \"red\" }\n          ]}\n        >\n          {message}\n        </Text>\n      )}\n    </View>\n  );\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    padding: 20,\n    justifyContent: \"center\"\n  },\n  message: {\n    marginTop: 20,\n    textAlign: \"center\"\n  }\n});\n```",
                "index": 6,
                "title": "anonymousLogin",
                "content": []
              }
            ]
          }
        ]
      }
    ],
    "_id": "cdc9a75069a9286e00430fd91d28824c",
    "_openid": "anon",
    "createdAt": 1769744604736,
    "updatedAt": 1769766702609
  },
  {
    "category": "Framework Integration,Web Frameworks,Vue(Vite)",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 11,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/api-reference/webv2/initialization",
    "content": [
      {
        "markdown": "`@cloudbase/js-sdk` allows you to use JavaScript on Web (such as PC web pages, WeChat H5, etc.) to access CloudBase services and resources.()",
        "index": 1,
        "title": "Install SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```bash\nnpm i @cloudbase/js-sdk\n```",
            "index": 1,
            "title": "npm",
            "content": []
          },
          {
            "markdown": "```bash\nyarn add @cloudbase/js-sdk\n```",
            "index": 2,
            "title": "yarn",
            "content": []
          },
          {
            "markdown": "```bash\npnpm add @cloudbase/js-sdk\n```",
            "index": 3,
            "title": "pnpm",
            "content": []
          }
        ]
      },
      {
        "markdown": "Add the following code to your Vue project",
        "index": 2,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nimport cloudbaseSDK from \"@cloudbase/js-sdk\";\n\nexport const cloudbase = cloudbaseSDK.init({\n  env: import.meta.env.VITE_CLOUDBASE_ENV_ID,\n  region: import.meta.env.VITE_CLOUDBASE_REGION,\n  accessKey: import.meta.env.VITE_CLOUDBASE_ACCESS_KEY\n});\n```",
            "index": 1,
            "title": "src/utils/cloudbase.js",
            "content": []
          },
          {
            "markdown": "```properties\n# Environment ID\nVITE_CLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Region\nVITE_CLOUDBASE_REGION={%REGION%}\n\n# Anonymous access token\nVITE_CLOUDBASE_ACCESS_KEY={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": ".env",
            "content": []
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table (limit 10 records)\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n\nconsole.log(\"Query result:\", data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Insert a record into {%TABLE_NAME%} table\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"New Post\", status: \"draft\" })\n  .select();\n\nconsole.log(\"Insert result:\", data);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ status: \"published\" })\n  .eq(\"id\", 1)\n  .select();\n\nconsole.log(\"Update result:\", data);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Upsert: update on conflict, otherwise insert\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Post Title\", status: \"published\" }, { onConflict: \"id\" })\n  .select();\n\nconsole.log(\"Upsert result:\", data);\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await cloudbase.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", 1);\n\nconsole.log(\"Delete completed:\", error);\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table first 10 records\nconst { data: result, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\nif (!error) {\n  console.log(result);\n}\n```\n\n**Full Example:**\n\n```vue\n<template>\n  <ul>\n    <li v-for=\"item in data\" :key=\"item.id\">{{ item.title }}</li>\n  </ul>\n</template>\n\n<script setup>\nimport { ref, onMounted } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref([]);\n\nconst getData = async () => {\n  // Query {%TABLE_NAME%} table first 10 records\n  const { data: result, error } = await cloudbase\n    .rdb()\n    .from(\"{%TABLE_NAME%}\")\n    .select(\"*\")\n    .limit(10);\n  if (!error) data.value = result || [];\n};\n\nonMounted(() => {\n  getData();\n});\n</script>\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} table data\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"Example Title\" });\nif (!error) {\n  console.log(\"Insert successful\");\n}\n```\n\n**Full Example:**\n\n```vue\n<template>\n  <div>\n    <input v-model=\"title\" />\n    <button @click=\"addData\">Add</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst title = ref(\"\");\nconst message = ref(\"\");\n\nconst addData = async () => {\n  // Add {%TABLE_NAME%} table data\n  const { error } = await cloudbase.rdb().from(\"{%TABLE_NAME%}\").insert({ title: title.value });\n  if (!error) {\n    title.value = \"\";\n    message.value = \"Insert successful！\";\n  } else {\n    message.value = \"Insert failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} table id with specified value\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ title: \"New Title\" })\n  .eq(\"id\", \"<data id>\");\nif (!error) {\n  console.log(\"Update successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"updateData\">Update</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst updateData = async () => {\n  // Update {%TABLE_NAME%} table id with specified value\n  const { error } = await cloudbase.rdb().from(\"{%TABLE_NAME%}\").update({ title: \"New Title\" }).eq(\"id\", \"<data id>\");\n  if (!error) {\n    message.value = \"Update successful！\";\n  } else {\n    message.value = \"Update failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Example Title\" });\nif (!error) {\n  console.log(\"Operation successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"upsertData\">UpdateorCreate</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst upsertData = async () => {\n  // If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\n  const { error } = await cloudbase.rdb().from(\"{%TABLE_NAME%}\").upsert({ id: 1, title: \"Example Title\" });\n  if (!error) {\n    message.value = \"Operation successful！\";\n  } else {\n    message.value = \"Operation failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} table id with specified value\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", \"<data id>\");\nif (!error) {\n  console.log(\"Delete successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"deleteData\">Delete</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst deleteData = async () => {\n  // Delete {%TABLE_NAME%} table id with specified value\n  const { error } = await cloudbase.rdb().from(\"{%TABLE_NAME%}\").delete().eq(\"id\", \"<data id>\");\n  if (!error) {\n    message.value = \"Delete successful！\";\n  } else {\n    message.value = \"Delete failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table first 10 records\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\nconsole.log(res.data);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <ul>\n    <li v-for=\"item in data\" :key=\"item._id\">{{ item.title }}</li>\n  </ul>\n</template>\n\n<script setup>\nimport { ref, onMounted } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref([]);\n\nconst getData = async () => {\n  // Query {%TABLE_NAME%} table first 10 records\n  const db = cloudbase.database();\n  const res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n  data.value = res.data || [];\n};\n\nonMounted(() => {\n  getData();\n});\n</script>\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} table data\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({ title: \"Example Title\" });\nconsole.log(`Insert successful! id: ${res.id}`);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"addData\">Add</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst addData = async () => {\n  try {\n    // Add {%TABLE_NAME%} table data\n    const db = cloudbase.database();\n    const res = await db.collection(\"{%TABLE_NAME%}\").add({ title: \"Example Title\" });\n    message.value = `Insert successful! id: ${res.id}`;\n  } catch (error) {\n    message.value = \"Insert failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} table id with specified value\nconst db = cloudbase.database();\nawait db\n  .collection(\"{%TABLE_NAME%}\")\n  .doc(\"<data id>\")\n  .update({ title: \"New Title\" });\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"updateData\">Update</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst updateData = async () => {\n  try {\n    // Update {%TABLE_NAME%} table id with specified value\n    const db = cloudbase.database();\n    await db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").update({ title: \"New Title\" });\n    message.value = \"Update successful！\";\n  } catch (error) {\n    message.value = \"Update failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} table id with specified value\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").remove();\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"deleteData\">Delete</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst deleteData = async () => {\n  try {\n    // Delete {%TABLE_NAME%} table id with specified value\n    const db = cloudbase.database();\n    await db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").remove();\n    message.value = \"Delete successful！\";\n  } catch (error) {\n    message.value = \"Delete failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} Data Modelbefore10recordsData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\nconsole.log(res.data?.records);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <ul>\n    <li v-for=\"item in data\" :key=\"item._id\">{{ item.title }}</li>\n  </ul>\n</template>\n\n<script setup>\nimport { ref, onMounted } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref([]);\n\nconst getData = async () => {\n  // Query {%TABLE_NAME%} Data Modelbefore10recordsData\n  const res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n    pageNumber: 1,\n    pagesize: 10\n  });\n  data.value = res.data?.records || [];\n};\n\nonMounted(() => {\n  getData();\n});\n</script>\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} Data ModelData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: { title: \"Example Title\" }\n});\nconsole.log(`Insert successful! id: ${res.data.id}`);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"addData\">Add</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst addData = async () => {\n  try {\n    // Add {%TABLE_NAME%} Data ModelData\n    const res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({ data: { title: \"Example Title\" } });\n    message.value = `Insert successful! id: ${res.data.id}`;\n  } catch (error) {\n    message.value = \"Insert failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} Data Model _id with specified value\nawait cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: { title: \"New Title\" },\n  filter: { where: { _id: { $eq: \"<data id>\" } } }\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"updateData\">Update</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst updateData = async () => {\n  try {\n    // Update {%TABLE_NAME%} Data Model _id with specified value\n    await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n      data: { title: \"New Title\" },\n      filter: { where: { _id: { $eq: \"<data id>\" } } }\n    });\n    message.value = \"Update successful！\";\n  } catch (error) {\n    message.value = \"Update failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} Data Model _id with specified value\nawait cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: { where: { _id: { $eq: \"<data id>\" } } }\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"deleteData\">Delete</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst deleteData = async () => {\n  try {\n    // Delete {%TABLE_NAME%} Data Model _id with specified value\n    await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n      filter: { where: { _id: { $eq: \"<data id>\" } } }\n    });\n    message.value = \"Delete successful！\";\n  } catch (error) {\n    message.value = \"Delete failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call {%FUNCTION_NAME%} Cloud Function\nconst res = await cloudbase.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {}\n});\nconsole.log(res.result);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"getData\">CallCloud Function</button>\n    <pre v-if=\"data\">{{ JSON.stringify(data, null, 2) }}</pre>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref(null);\n\nconst getData = async () => {\n  // Call {%FUNCTION_NAME%} Cloud Function\n  const res = await cloudbase.callFunction({\n    name: \"{%FUNCTION_NAME%}\",\n    data: {}\n  });\n  data.value = res.result;\n};\n</script>\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function",
            "content": []
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call {%SERVICE_NAME%} Cloud Runservice\nconst res = await cloudbase.callContainer({\n  name: \"{%SERVICE_NAME%}\"\n  method: 'POST',\n  path: '/',\n  header:{\n    'Content-Type': 'application/json; charset=utf-8'\n  },\n  data: {},\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"getData\">CallCloud Run</button>\n    <pre v-if=\"data\">{{ JSON.stringify(data, null, 2) }}</pre>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref(null);\n\nconst getData = async () => {\n  // Call {%SERVICE_NAME%} Cloud Runservice\n  const res = await cloudbase.callContainer({\n    name: \"{%SERVICE_NAME%}\"\n    method: 'POST',\n    path: '/',\n    header:{\n      'Content-Type': 'application/json; charset=utf-8'\n    },\n    data: {},\n  });\n  data.value = res;\n};\n</script>\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run",
            "content": []
          },
          {
            "index": 6,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.uploadFile({\n  cloudPath: `images/${Date.now()}-${file.name}`, // Path to upload in cloud\n  filePath: file\n});\nconsole.log(res.fileID);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <input type=\"file\" @change=\"uploadFile\" />\n    <p v-if=\"fileID\">Upload successful: {{ fileID }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst fileID = ref(\"\");\n\nconst uploadFile = async e => {\n  const file = e.target.files[0];\n  const res = await cloudbase.uploadFile({\n    cloudPath: `images/${Date.now()}-${file.name}`, // Path to upload in cloud\n    filePath: file\n  });\n  fileID.value = res.fileID;\n};\n</script>\n```",
                "index": 1,
                "title": "Upload File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.getTempFileURL({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\nconsole.log(res.fileList[0].tempFileURL);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"getData\">GetURL</button>\n    <p v-if=\"fileUrl\">URL: {{ fileUrl }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst fileUrl = ref(\"\");\n\nconst getData = async () => {\n  const res = await cloudbase.getTempFileURL({\n    fileList: [\"cloud://xxx.png\"] // File fileID list\n  });\n  fileUrl.value = res.fileList[0].tempFileURL;\n};\n</script>\n```",
                "index": 2,
                "title": "Get File URL"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nawait cloudbase.downloadFile({\n  fileID: \"cloud://xxx.png\" // File fileID\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <button @click=\"downloadFile\">Download File</button>\n</template>\n\n<script setup>\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst downloadFile = async () => {\n  await cloudbase.downloadFile({\n    fileID: \"cloud://xxx.png\" // File fileID\n  });\n};\n</script>\n```",
                "index": 3,
                "title": "Download File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.deleteFile({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\nif (res.fileList[0].code === \"SUCCESS\") {\n  console.log(\"Delete successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"deleteFile\">Delete File</button>\n    <p v-if=\"message\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst deleteFile = async () => {\n  const res = await cloudbase.deleteFile({\n    fileList: [\"cloud://xxx.png\"] // File fileID list\n  });\n  if (res.fileList[0].code === \"SUCCESS\") {\n    message.value = \"Delete successful！\";\n  } else {\n    ((message.value = \"Delete failed！\"), res.fileList);\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Delete File"
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase\n  .ai()\n  .createModel(\"{%AI_MODEL_NAME%}\")\n  .streamText({\n    model: \"{%AI_SUB_MODEL_NAME%}\",\n    messages: [{ role: \"user\", content: \"Hello\" }]\n  });\n\nfor await (let data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data?.choices?.[0]?.delta?.reasoning_content;\n  if (think) console.log(think);\n\n  // Print generated text content\n  const text = data?.choices?.[0]?.delta?.content;\n  if (text) console.log(text);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <input v-model=\"input\" placeholder=\"Enter AI conversation content\" />\n    <button @click=\"getData\">Send</button>\n    <p>{{ data }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref(\"\");\nconst input = ref(\"\");\n\nconst getData = async () => {\n  const res = await cloudbase\n    .ai()\n    .createModel(\"{%AI_MODEL_NAME%}\")\n    .streamText({\n      model: \"{%AI_SUB_MODEL_NAME%}\",\n      messages: [{ role: \"user\", content: input.value }]\n    });\n\n  let result = \"\";\n  for await (let item of res.dataStream) {\n    // Print reasoning content if available\n    const think = item?.choices?.[0]?.delta?.reasoning_content;\n    if (think) {\n      result += think;\n    }\n\n    // Print generated text content\n    const text = item?.choices?.[0]?.delta?.content;\n    if (text) result += text;\n\n    data.value = result;\n  }\n};\n</script>\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation"
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call image generation cloud function\nconst res = await cloudbase.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: {\n    prompt: \"A cute cat playing in the sunshine\"\n  }\n});\n\nconst result = res.result;\n\nif (result.success) {\n  // Generation successful\n  console.log(\"Generation successful!\");\n  console.log(\"Image URL:\", result.imageUrl);\n  console.log(\"Optimized prompt:\", result.revised_prompt);\n\n  // Use image\n  // Note: Image URL is valid for 24 hours, please save or transfer promptly\n} else {\n  // Generation failed\n  console.error(\"Generation failed:\", result.code, result.message);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <input v-model=\"prompt\" placeholder=\"Enter image description\" />\n    <button @click=\"generateImage\" :disabled=\"!prompt || loading\">\n      {{ loading ? \"Generating...\" : \"Generate Image\" }}\n    </button>\n    <p v-if=\"message\" :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\">\n      {{ message }}\n    </p>\n    <div v-if=\"imageUrl\">\n      <img :src=\"imageUrl\" alt=\"Generated image\" style=\"max-width: 100%\" />\n      <p style=\"font-size: 12px; color: #666\">\n        Note: Image URL is valid for 24 hours, please save promptly\n      </p>\n    </div>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst prompt = ref(\"\");\nconst imageUrl = ref(\"\");\nconst message = ref(\"\");\nconst loading = ref(false);\n\nconst generateImage = async () => {\n  loading.value = true;\n  message.value = \"\";\n  imageUrl.value = \"\";\n\n  try {\n    // Call image generation cloud function\n    const res = await cloudbase.callFunction({\n      name: \"<YOUR_FUNCTION_NAME>\",\n      data: {\n        prompt: prompt.value\n      }\n    });\n\n    const result = res.result;\n\n    if (result.success) {\n      imageUrl.value = result.imageUrl;\n      message.value = \"Generation successful！\";\n    } else {\n      message.value = `Generation failed：${result.message}`;\n    }\n  } catch (error) {\n    message.value = \"Call failed：\" + error.message;\n  } finally {\n    loading.value = false;\n  }\n};\n</script>\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation"
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from './utils/cloudbase';\n\nconst res = await cloudbase.ai().bot.sendMessage({\n  botId: '{%AGENT_ID%}',\n  // Refer to frontend-backend communication protocol for input structure：\n  //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n  threadId: '550e8400-e29b-41d4-a716-446655440000',\n  runId: 'run_001',\n  messages: [\n    {\n      id: 'msg_001',\n      role: 'user',\n      content: 'Hello',\n    },\n  ],\n  tools: [],\n  context: [],\n  state: {},\n  forwardedProps: {},\n});\n\nfor await (const data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data.reasoning_content;\n  if (think) console.log(think);\n\n  // Print output content\n  const content = data.content;\n  if (content) console.log(content);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <input v-model=\"input\" placeholder=\"Enter Agent conversation content\" />\n    <button @click=\"getData\">Send</button>\n    <p>{{ data }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref(\"\");\nconst input = ref(\"\");\n\nconst getData = async () => {\n  const res = await cloudbase.ai().bot.sendMessage({\n    botId: \"{%AGENT_ID%}\",\n    // Refer to frontend-backend communication protocol for input structure：\n    //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n    threadId: '550e8400-e29b-41d4-a716-446655440000',\n    runId: 'run_001',\n    messages: [\n      {\n        id: 'msg_001',\n        role: 'user',\n        content: input.value,\n      },\n    ],\n    tools: [],\n    context: [],\n    state: {},\n    forwardedProps: {},\n    });\n\n  let result = \"\";\n  for await (const item of res.dataStream) {\n    // Print reasoning content if available\n    const think = item.reasoning_content;\n    if (think) {\n      result += think;\n    }\n\n    // Print output content\n    const content = item.content;\n    if (content) result += content;\n\n    data.value = result;\n  }\n};\n</script>\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.ai().bot.sendMessage({\n  botId: \"{%AGENT_ID%}\",\n  msg: \"Hello\"\n});\n\nfor await (const data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data.reasoning_content;\n  if (think) console.log(think);\n\n  // Print output content\n  const content = data.content;\n  if (content) console.log(content);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <input v-model=\"input\" placeholder=\"Enter Agent conversation content\" />\n    <button @click=\"getData\">Send</button>\n    <p>{{ data }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref(\"\");\nconst input = ref(\"\");\n\nconst getData = async () => {\n  const res = await cloudbase.ai().bot.sendMessage({\n    botId: \"{%AGENT_ID%}\",\n    msg: input.value\n  });\n\n  let result = \"\";\n  for await (const item of res.dataStream) {\n    // Print reasoning content if available\n    const think = item.reasoning_content;\n    if (think) {\n      result += think;\n    }\n\n    // Print output content\n    const content = item.content;\n    if (content) result += content;\n\n    data.value = result;\n  }\n};\n</script>\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 9,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "Use **SMS Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMSVerification code**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: phone });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  phone_number: `+86 ${phone}`,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${phone.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <label>Phone number：</label>\n    <input v-model=\"phone\" placeholder=\"13800000000\" />\n    <div>\n      <label>Verification code：</label>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button :disabled=\"!phone\" @click=\"sendCode\">Send Code</button>\n    </div>\n    <button :disabled=\"!verificationId || !code\" @click=\"register\">Register</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst phone = ref(\"\");\nconst code = ref(\"\");\nconst verificationId = ref(\"\");\nconst message = ref(\"\");\n\n// Send Code\nconst sendCode = async () => {\n  try {\n    const auth = cloudbase.auth();\n    const res = await auth.getVerification({ phone_number: phone.value });\n    verificationId.value = res.verification_id;\n    message.value = \"Verification code sent！\";\n  } catch (error) {\n    message.value = \"Send failed：\" + error.message;\n  }\n};\n\n// Register\nconst register = async () => {\n  try {\n    const auth = cloudbase.auth();\n    // Verify the code\n    const verifyRes = await auth.verify({\n      verification_id: verificationId.value,\n      verification_code: code.value,\n    });\n    // Register (auto-login if user exists)\n    await auth.signUp({\n      phone_number: `+86 ${phone.value}`,\n      verification_code: code.value,\n      verification_token: verifyRes.verification_token,\n      name: `user_${phone.value.slice(-4)}`,\n      password: \"admin@123\"\n    });\n    message.value = \"Registration successful！\";\n  } catch (error) {\n    message.value = \"Registration failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 1,
                "title": "SMS Code Registration"
              },
              {
                "markdown": "Use **Email Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  email,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${email.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <label>Email：</label>\n    <input v-model=\"email\" placeholder=\"example@email.com\" />\n    <div>\n      <label>Verification code：</label>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button :disabled=\"!email\" @click=\"sendCode\">Send Code</button>\n    </div>\n    <button :disabled=\"!verificationId || !code\" @click=\"register\">Register</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst email = ref(\"\");\nconst code = ref(\"\");\nconst verificationId = ref(\"\");\nconst message = ref(\"\");\n\n// Send Code\nconst sendCode = async () => {\n  try {\n    const auth = cloudbase.auth();\n    const res = await auth.getVerification({ email: email.value });\n    verificationId.value = res.verification_id;\n    message.value = \"Verification code sent！\";\n  } catch (error) {\n    message.value = \"Send failed：\" + error.message;\n  }\n};\n\n// Register\nconst register = async () => {\n  try {\n    const auth = cloudbase.auth();\n    // Verify the code\n    const verifyRes = await auth.verify({\n      verification_id: verificationId.value,\n      verification_code: code.value,\n    });\n    // Register (auto-login if user exists)\n    await auth.signUp({\n      email: email.value,\n      verification_code: code.value,\n      verification_token: verifyRes.verification_token,\n      name: `user_${email.value.slice(-4)}`,\n      password: \"admin@123\"\n    });\n    message.value = \"Registration successful！\";\n  } catch (error) {\n    message.value = \"Registration failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Email Code Registration"
              },
              {
                "markdown": "Use **Username Password Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **UsernamePasswordLogin**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\nawait auth.signIn({\n  username, // Can be username, phone or email\n  password\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <label>Account：</label>\n    <input v-model=\"username\" placeholder=\"Username/Phone/Email\" />\n    Note: Add country code for phone login +86\n    <br />\n    <label>Password：</label>\n    <input\n      type=\"password\"\n      v-model=\"password\"\n      placeholder=\"Enter password\"\n    />\n    <br />\n    <button :disabled=\"!username || !password\" @click=\"login\">Login</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst username = ref(\"\");\nconst password = ref(\"\");\nconst message = ref(\"\");\n\n// Login\nconst login = async () => {\n  try {\n    const auth = cloudbase.auth();\n    await auth.signIn({\n      username: username.value, // Can be username, phone or email\n      password: password.value,\n    });\n    message.value = \"Login successful！\";\n  } catch (error) {\n    message.value = \"Login failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login"
              },
              {
                "markdown": "Use **SMS Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMS Verification Login**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n\n// Login\nawait auth.signInWithSms({\n  verificationInfo: res,\n  verificationCode: code,\n  phoneNum: `+86 ${phone}`\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <label>Phone number：</label>\n    <input v-model=\"phone\" placeholder=\"13800000000\" />\n    <div>\n      <label>Verification code：</label>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button @click=\"sendCode\" :disabled=\"!phone\">Send Code</button>\n    </div>\n    <button @click=\"login\" :disabled=\"!verificationInfo || !code\">Login</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst phone = ref(\"\");\nconst code = ref(\"\");\nconst verificationInfo = ref(null);\nconst message = ref(\"\");\n\n// Send Code\nconst sendCode = async () => {\n  try {\n    const auth = cloudbase.auth();\n    const res = await auth.getVerification({ phone_number: `+86 ${phone.value}` });\n    verificationInfo.value = res;\n    message.value = \"Verification code sent！\";\n  } catch (error) {\n    message.value = \"Send failed：\" + error.message;\n  }\n};\n\n// Login\nconst login = async () => {\n  try {\n    const auth = cloudbase.auth();\n    await auth.signInWithSms({\n      verificationInfo: verificationInfo.value,\n      verificationCode: code.value,\n      phoneNum: `+86 ${phone.value}`\n    });\n    message.value = \"Login successful！\";\n  } catch (error) {\n    message.value = \"Login failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login"
              },
              {
                "markdown": "Use **Email Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Login\nawait auth.signInWithEmail({\n  verificationInfo: res,\n  verificationCode: code,\n  email\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <label>Email：</label>\n    <input v-model=\"email\" placeholder=\"example@email.com\" />\n    <div>\n      <label>Verification code：</label>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button @click=\"sendCode\" :disabled=\"!email\">Send Code</button>\n    </div>\n    <button @click=\"login\" :disabled=\"!verificationInfo || !code\">Login</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst email = ref(\"\");\nconst code = ref(\"\");\nconst verificationInfo = ref(null);\nconst message = ref(\"\");\n\n// Send Code\nconst sendCode = async () => {\n  try {\n    const auth = cloudbase.auth();\n    const res = await auth.getVerification({ email: email.value });\n    verificationInfo.value = res;\n    message.value = \"Verification code sent！\";\n  } catch (error) {\n    message.value = \"Send failed：\" + error.message;\n  }\n};\n\n// Login\nconst login = async () => {\n  try {\n    const auth = cloudbase.auth();\n    await auth.signInWithEmail({\n      verificationInfo: verificationInfo.value,\n      verificationCode: code.value,\n      email: email.value\n    });\n    message.value = \"Login successful！\";\n  } catch (error) {\n    message.value = \"Login failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login"
              },
              {
                "markdown": "Use **Google OAuth Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **Google OAuth Login**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Step1：GenerateGoogleauthorization URLandRedirect\nconst state = Date.now().toString();\nlocalStorage.setItem(\"google_login_state\", state);\nconst { uri } = await auth.genProviderRedirectUri({\n  provider_id: \"google\",\n  provider_redirect_uri: window.location.href,\n  state: state\n});\nwindow.location.href = uri;\n\n// Step2：Usecodeexchange forprovider_token\nconst { provider_token } = await auth.grantProviderToken({\n  provider_id: \"google\",\n  provider_redirect_uri: window.location.origin + window.location.pathname,\n  provider_code: code\n});\n\n// Step3：Useprovider_tokenLogin\nawait auth.signInWithProvider({\n  provider_token: provider_token\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button v-if=\"!isCallback\" @click=\"startGoogleLogin\">GoogleLogin</button>\n    <p v-if=\"isCallback\">ProcessingGoogleLogin...</p>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">\n      {{ message }}\n    </p>\n  </div>\n</template>\n\n<script setup>\nimport { ref, onMounted } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\nconst isCallback = ref(false);\n\nonMounted(() => {\n  // CheckYesNoYesGoogleCallbackPage\n  const urlParams = new URLSearchParams(window.location.search);\n  const code = urlParams.get(\"code\");\n  const state = urlParams.get(\"state\");\n\n  if (code && state) {\n    isCallback.value = true;\n    handleGoogleCallback(code, state);\n  }\n});\n\n// Step1：Redirect toGoogleauthorization page\nconst startGoogleLogin = async () => {\n  try {\n    const auth = cloudbase.auth();\n    const state = Date.now().toString(); // Generate unique identifier to prevent CSRF attacks\n\n    // Save state locally for callback verification\n    localStorage.setItem(\"google_login_state\", state);\n\n    // GenerateGoogleauthorization URL\n    const { uri } = await auth.genProviderRedirectUri({\n      provider_id: \"google\", // Fixed value, representingGoogleOpen Platform\n      provider_redirect_uri: window.location.href, // Callback to current page after authorization\n      state: state,\n    });\n\n    // Redirect toGoogleauthorization page\n    window.location.href = uri;\n  } catch (error) {\n    message.value = \"Redirect failed：\" + error.message;\n  }\n};\n\n// Step2and3：ProcessGoogleCallbackandDoneLogin\nconst handleGoogleCallback = async (code, state) => {\n  try {\n    // Verify state matches to prevent CSRF attacks\n    const savedState = localStorage.getItem(\"google_login_state\");\n    if (savedState !== state) {\n      message.value = \"Login failed：State verification failed\";\n      return;\n    }\n\n    const auth = cloudbase.auth();\n\n    // Usecodeexchange forprovider_token\n    const { provider_token } = await auth.grantProviderToken({\n      provider_id: \"google\",\n      provider_redirect_uri: window.location.origin + window.location.pathname,\n      provider_code: code,\n    });\n\n    try {\n      // Try direct login\n      await auth.signInWithProvider({\n        provider_token: provider_token,\n      });\n\n      message.value = \"Login successful！\";\n\n      // Clear URL parameters and local storage\n      localStorage.removeItem(\"google_login_state\");\n      window.history.replaceState({}, document.title, window.location.pathname);\n\n    } catch (loginError) {\n      // IfYesfirst-timeGoogleLogin，needfirstRegisterandbindthe\n      if (loginError.error === \"not_found\") {\n        message.value = \"Detected first-timeGoogleLogin，Need to bindaccount...\";\n\n        // Here you need to guide the user to complete the registration process\n        // For example: collect phone verification code for registration\n        // After successful registration, call bindWithProvider bindtheGoogleidentity\n\n        // Example: Assuming an account registered via other methods, bindirect\n        await auth.bindWithProvider({\n          provider_token: provider_token,\n        });\n\n        // Re-login after successful bindng\n        await auth.signInWithProvider({\n          provider_token: provider_token,\n        });\n\n        message.value = \"bindand login successful！\";\n\n        // Clear URL parameters and local storage\n        localStorage.removeItem(\"google_login_state\");\n        window.history.replaceState({}, document.title, window.location.pathname);\n\n      } else {\n        throw loginError;\n      }\n    }\n  } catch (error) {\n    message.value = \"Login failed：\" + error.message;\n    localStorage.removeItem(\"google_login_state\");\n  }\n};\n</script>\n```",
                "index": 6,
                "id": "google",
                "title": "Google OAuth Login"
              }
            ]
          }
        ]
      }
    ],
    "_id": "d12f925c697c80800042bb7d5be913a5",
    "_openid": "anon",
    "createdAt": 1769767040475,
    "updatedAt": 1769767040475
  },
  {
    "category": "CloudBase MCP,OpenClaw",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": -1,
    "hasTemplate": false,
    "content": [
      {
        "markdown": "Operate CloudBase resources through AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "tab",
        "content": []
      }
    ],
    "_id": "da3d566169c0dbc50139f63b3a633cd4",
    "_openid": "1524963278340493312",
    "createdAt": 1774246853213,
    "updatedAt": 1774249057334
  },
  {
    "category": "Framework Integration,Backend Frameworks,Java",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 7,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/http-api/basic/overview",
    "content": [
      {
        "markdown": "Use **HTTP Request** in **Java** Callvarious CloudBase capabilities",
        "index": 1,
        "title": "Install Dependencies",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```xml\n<dependencies>\n    <!-- HTTP client -->\n    <dependency>\n        <groupId>com.squareup.okhttp3</groupId>\n        <artifactId>okhttp</artifactId>\n        <version>4.12.0</version>\n    </dependency>\n\n    <!-- JSON Process -->\n    <dependency>\n        <groupId>com.google.code.gson</groupId>\n        <artifactId>gson</artifactId>\n        <version>2.10.1</version>\n    </dependency>\n\n    <!-- Environment variableLoad -->\n    <dependency>\n        <groupId>io.github.cdimascio</groupId>\n        <artifactId>dotenv-java</artifactId>\n        <version>3.0.0</version>\n    </dependency>\n</dependencies>\n```",
            "index": 1,
            "title": "Maven"
          },
          {
            "markdown": "```groovy\ndependencies {\n    implementation 'com.squareup.okhttp3:okhttp:4.12.0'\n    implementation 'com.google.code.gson:gson:2.10.1'\n    implementation 'io.github.cdimascio:dotenv-java:3.0.0'\n}\n```",
            "index": 2,
            "title": "Gradle"
          }
        ]
      },
      {
        "markdown": "Add the following code to your **Java** project",
        "index": 2,
        "title": "Initialize Configuration",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```java\npackage com.cloudbase;\n\nimport com.google.gson.Gson;\nimport com.google.gson.JsonObject;\nimport io.github.cdimascio.dotenv.Dotenv;\nimport okhttp3.*;\n\nimport java.io.IOException;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class CloudBaseClient {\n    private final String envId;\n    private final String accessToken;\n    private final String baseUrl;\n    private final OkHttpClient client;\n    private final Gson gson;\n    private final Map<String, String> defaultHeaders;\n\n    public CloudBaseClient() {\n        // LoadEnvironment variable\n        Dotenv dotenv = Dotenv.configure().ignoreIfMissing().load();\n        this.envId = dotenv.get(\"CLOUDBASE_ENV_ID\");\n        this.accessToken = dotenv.get(\"CLOUDBASE_ACCESS_TOKEN\");\n        this.baseUrl = \"https://\" + envId + \".api.tcloudbasegateway.com\";\n\n        this.client = new OkHttpClient();\n        this.gson = new Gson();\n\n        // SetDefaultRequest header\n        this.defaultHeaders = new HashMap<>();\n        this.defaultHeaders.put(\"Content-Type\", \"application/json\");\n        this.defaultHeaders.put(\"Accept\", \"application/json\");\n        this.defaultHeaders.put(\"Authorization\", \"Bearer \" + accessToken);\n    }\n\n    public String getEnvId() {\n        return envId;\n    }\n\n    public String getAccessToken() {\n        return accessToken;\n    }\n\n    public OkHttpClient getClient() {\n        return client;\n    }\n\n    public Gson getGson() {\n        return gson;\n    }\n\n    /**\n     * Unified HTTP request method\n     *\n     * @param method Request method (GET, POST, PUT, PATCH, DELETE)\n     * @param path APIPath (such as /v1/rdb/rest/table_name)\n     * @param body Requestbody (Optional)\n     * @param customHeaders CustomRequest header (Optional)\n     * @return ResponseDataornull\n     */\n    public JsonObject request(String method, String path, Object body, Map<String, String> customHeaders) {\n        try {\n            String url = baseUrl + path;\n\n            // BuildRequest header\n            Headers.Builder headersBuilder = new Headers.Builder();\n            defaultHeaders.forEach(headersBuilder::add);\n            if (customHeaders != null) {\n                customHeaders.forEach(headersBuilder::add);\n            }\n\n            // BuildRequestbody\n            RequestBody requestBody = null;\n            if (body != null) {\n                String jsonBody = gson.toJson(body);\n                requestBody = RequestBody.create(jsonBody, MediaType.parse(\"application/json\"));\n            } else if (method.equals(\"POST\") || method.equals(\"PUT\") || method.equals(\"PATCH\")) {\n                requestBody = RequestBody.create(\"\", MediaType.parse(\"application/json\"));\n            }\n\n            // BuildRequest\n            Request.Builder requestBuilder = new Request.Builder()\n                    .url(url)\n                    .headers(headersBuilder.build())\n                    .method(method, requestBody);\n\n            // SendRequest\n            try (Response response = client.newCall(requestBuilder.build()).execute()) {\n                if (!response.isSuccessful()) {\n                    System.err.println(\"Requestfailed: \" + response.code() + \" \" + response.message());\n                    return null;\n                }\n\n                // IfResponseis empty，Returnsuccessfulidentifier\n                String responseBody = response.body().string();\n                if (responseBody == null || responseBody.isEmpty()) {\n                    JsonObject result = new JsonObject();\n                    result.addProperty(\"success\", true);\n                    return result;\n                }\n\n                return gson.fromJson(responseBody, JsonObject.class);\n            }\n        } catch (IOException e) {\n            System.err.println(\"Requestfailed: \" + e.getMessage());\n            return null;\n        }\n    }\n\n    public JsonObject request(String method, String path, Object body) {\n        return request(method, path, body, null);\n    }\n\n    public JsonObject request(String method, String path) {\n        return request(method, path, null, null);\n    }\n}\n```",
            "index": 1,
            "title": "CloudBaseClient.java"
          },
          {
            "markdown": "> 💡Note: If admin permission is needed, obtain the APIKey from the [CloudBase Platform/ApiKeymanagement page](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}&#/env/apikey) Get APIKey to replace CLOUDBASE_ACCESS_TOKEN\n\n```properties\n# Environment ID\nCLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Anonymous access token\nCLOUDBASE_ACCESS_TOKEN={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": ".env"
          }
        ]
      },
      {
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // Query MySQL database data\n        JsonObject data = cloudbase.request(\"GET\", \"/v1/rdb/rest/{%TABLE_NAME%}?limit=10\");\n\n        if (data != null) {\n            System.out.println(\"Querysuccessful: \" + data);\n        }\n    }\n}\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // PrepareData\n        Map<String, Object> data = new HashMap<>();\n        data.put(\"title\", \"Example Title\");\n\n        // Add MySQL database data\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/rdb/rest/{%TABLE_NAME%}\", data);\n\n        if (result != null) {\n            System.out.println(\"Insert successful: \" + result);\n        }\n    }\n}\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // PrepareUpdate Data\n        Map<String, Object> data = new HashMap<>();\n        data.put(\"title\", \"New Title\");\n\n        // Update MySQL database data\n        String dataId = \"<data id>\";\n        JsonObject result = cloudbase.request(\"PATCH\", \"/v1/rdb/rest/{%TABLE_NAME%}?id=eq.\" + dataId, data);\n\n        if (result != null) {\n            System.out.println(\"Update successful: \" + result);\n        }\n    }\n}\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // Delete MySQL database data\n        String dataId = \"<data id>\";\n        JsonObject result = cloudbase.request(\"DELETE\", \"/v1/rdb/rest/{%TABLE_NAME%}?id=eq.\" + dataId);\n\n        if (result != null) {\n            System.out.println(\"Delete successful\");\n        }\n    }\n}\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "index": 2,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // PrepareQueryparameter\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"pageSize\", 10);\n        payload.put(\"pageNumber\", 1);\n        payload.put(\"getCount\", true);\n\n        // QueryData ModelData\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/model/prod/{%TABLE_NAME%}/list\", payload);\n\n        if (result != null) {\n            JsonArray records = result.getAsJsonObject(\"data\").getAsJsonArray(\"records\");\n            System.out.println(\"Querysuccessful: \" + records);\n        }\n    }\n}\n```",
                "index": 1,
                "title": "Query Data",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // PrepareData\n        Map<String, Object> data = new HashMap<>();\n        data.put(\"title\", \"Example Title\");\n\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"data\", data);\n\n        // AddData ModelData\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/model/prod/{%TABLE_NAME%}/create\", payload);\n\n        if (result != null) {\n            String docId = result.getAsJsonObject(\"data\").get(\"id\").getAsString();\n            System.out.println(\"Insert successful! id: \" + docId);\n        }\n    }\n}\n```",
                "index": 2,
                "title": "Insert Data",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // PrepareUpdate Data\n        Map<String, Object> data = new HashMap<>();\n        data.put(\"title\", \"New Title\");\n\n        // PrepareFiltercondition\n        Map<String, Object> eqCondition = new HashMap<>();\n        eqCondition.put(\"$eq\", \"<data id>\");\n\n        Map<String, Object> whereCondition = new HashMap<>();\n        whereCondition.put(\"_id\", eqCondition);\n\n        Map<String, Object> filter = new HashMap<>();\n        filter.put(\"where\", whereCondition);\n\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"data\", data);\n        payload.put(\"filter\", filter);\n\n        // UpdateData ModelData\n        JsonObject result = cloudbase.request(\"PUT\", \"/v1/model/prod/{%TABLE_NAME%}/update\", payload);\n\n        if (result != null) {\n            System.out.println(\"Update successful!\");\n        }\n    }\n}\n```",
                "index": 3,
                "title": "Update Data",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // PrepareFiltercondition\n        Map<String, Object> eqCondition = new HashMap<>();\n        eqCondition.put(\"$eq\", \"<data id>\");\n\n        Map<String, Object> whereCondition = new HashMap<>();\n        whereCondition.put(\"_id\", eqCondition);\n\n        Map<String, Object> filter = new HashMap<>();\n        filter.put(\"where\", whereCondition);\n\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"filter\", filter);\n\n        // DeleteData ModelData\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/model/prod/{%TABLE_NAME%}/delete\", payload);\n\n        if (result != null) {\n            System.out.println(\"Delete successful!\");\n        }\n    }\n}\n```",
                "index": 4,
                "title": "Delete Data",
                "content": []
              }
            ]
          },
          {
            "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // CallCloud Function\n        Map<String, Object> data = new HashMap<>();\n        // data.put(\"key\", \"value\"); // Optionalparameter\n\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/functions/{%FUNCTION_NAME%}\", data);\n\n        if (result != null) {\n            System.out.println(\"Cloud function call result: \" + result);\n        }\n    }\n}\n```",
            "index": 3,
            "id": "scf",
            "title": "Cloud Function"
          },
          {
            "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // CallCloud Runservice\n        String serviceName = \"{%SERVICE_NAME%}\";\n        String path = \"\"; // OptionalPath\n        String fullPath = \"/v1/cloudrun/\" + serviceName + (path.isEmpty() ? \"\" : \"/\" + path);\n\n        JsonObject result = cloudbase.request(\"GET\", fullPath);\n\n        if (result != null) {\n            System.out.println(\"Cloud RunCallResult: \" + result);\n        }\n    }\n}\n```",
            "index": 4,
            "id": "run",
            "title": "Cloud Run"
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonObject;\nimport okhttp3.*;\n\nimport java.io.File;\nimport java.io.IOException;\nimport java.nio.file.Files;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) throws IOException {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // Upload FiletoCloud Storage\n        String filePath = \"./example.jpg\";\n        String objectId = \"uploads/\" + System.currentTimeMillis() + \"-\" + new File(filePath).getName();\n\n        // 1. Get upload info\n        List<Map<String, String>> uploadInfoRequest = new ArrayList<>();\n        Map<String, String> objectInfo = new HashMap<>();\n        objectInfo.put(\"objectId\", objectId);\n        uploadInfoRequest.add(objectInfo);\n\n        JsonObject uploadInfoResponse = cloudbase.request(\"POST\", \"/v1/storages/get-objects-upload-info\", uploadInfoRequest);\n\n        if (uploadInfoResponse == null) {\n            System.err.println(\"Get upload infofailed\");\n            return;\n        }\n\n        JsonObject uploadInfo = uploadInfoResponse.getAsJsonArray().get(0).getAsJsonObject();\n        String uploadUrl = uploadInfo.get(\"uploadUrl\").getAsString();\n        String authorization = uploadInfo.get(\"authorization\").getAsString();\n        String token = uploadInfo.get(\"token\").getAsString();\n        String cloudObjectMeta = uploadInfo.get(\"cloudObjectMeta\").getAsString();\n\n        // 2. Upload File\n        File file = new File(filePath);\n        byte[] fileData = Files.readAllBytes(file.toPath());\n\n        OkHttpClient client = new OkHttpClient();\n        RequestBody requestBody = RequestBody.create(fileData, MediaType.parse(\"application/octet-stream\"));\n\n        Request uploadRequest = new Request.Builder()\n                .url(uploadUrl)\n                .put(requestBody)\n                .addHeader(\"Authorization\", authorization)\n                .addHeader(\"X-Cos-Security-Token\", token)\n                .addHeader(\"X-Cos-Meta-Fileid\", cloudObjectMeta)\n                .build();\n\n        try (Response response = client.newCall(uploadRequest).execute()) {\n            if (response.isSuccessful()) {\n                String cloudObjectId = uploadInfo.get(\"cloudObjectId\").getAsString();\n                String downloadUrl = uploadInfo.get(\"downloadUrl\").getAsString();\n\n                System.out.println(\"fileUpload successful:\");\n                System.out.println(\"- Object ID: \" + objectId);\n                System.out.println(\"- cloudObject ID: \" + cloudObjectId);\n                System.out.println(\"- DownloadURL: \" + downloadUrl);\n            } else {\n                System.err.println(\"fileUploadfailed: \" + response.code());\n            }\n        }\n    }\n}\n```",
                "index": 1,
                "title": "Upload File",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonObject;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // GetCloud Storagefiletemporary accessURL\n        String cloudObjectId = \"cloud://xxx.png\";\n\n        List<Map<String, String>> request = new ArrayList<>();\n        Map<String, String> objectInfo = new HashMap<>();\n        objectInfo.put(\"cloudObjectId\", cloudObjectId);\n        request.add(objectInfo);\n\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/storages/get-objects-download-info\", request);\n\n        if (result != null) {\n            String downloadUrl = result.getAsJsonArray().get(0).getAsJsonObject().get(\"downloadUrl\").getAsString();\n            System.out.println(\"fileURL: \" + downloadUrl);\n        }\n    }\n}\n```",
                "index": 2,
                "title": "Get File URL",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.Response;\n\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) throws IOException {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // DownloadCloud Storagefiletolocal\n        String cloudObjectId = \"cloud://xxx.png\";\n        String savePath = \"./downloaded.png\";\n\n        // 1. GetDownloadURL\n        List<Map<String, String>> request = new ArrayList<>();\n        Map<String, String> objectInfo = new HashMap<>();\n        objectInfo.put(\"cloudObjectId\", cloudObjectId);\n        request.add(objectInfo);\n\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/storages/get-objects-download-info\", request);\n\n        if (result == null) {\n            System.err.println(\"GetDownloadURLfailed\");\n            return;\n        }\n\n        String downloadUrl = result.getAsJsonArray().get(0).getAsJsonObject().get(\"downloadUrl\").getAsString();\n\n        // 2. Download File\n        OkHttpClient client = new OkHttpClient();\n        Request downloadRequest = new Request.Builder().url(downloadUrl).build();\n\n        try (Response response = client.newCall(downloadRequest).execute()) {\n            if (response.isSuccessful() && response.body() != null) {\n                try (FileOutputStream fos = new FileOutputStream(savePath)) {\n                    fos.write(response.body().bytes());\n                }\n                System.out.println(\"Downloadsuccessful! filesaved to: \" + savePath);\n            } else {\n                System.err.println(\"Downloadfailed: \" + response.code());\n            }\n        }\n    }\n}\n```",
                "index": 3,
                "title": "Download File",
                "content": []
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // DeleteCloud Storagefile\n        String cloudObjectId = \"cloud://xxx.png\";\n\n        List<Map<String, String>> request = new ArrayList<>();\n        Map<String, String> objectInfo = new HashMap<>();\n        objectInfo.put(\"cloudObjectId\", cloudObjectId);\n        request.add(objectInfo);\n\n        JsonObject result = cloudbase.request(\"POST\", \"/v1/storages/delete-objects\", request);\n\n        if (result != null) {\n            System.out.println(\"Delete successful!\");\n        }\n    }\n}\n```",
                "index": 4,
                "title": "Delete File",
                "content": []
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport okhttp3.*;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.nio.charset.StandardCharsets;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) throws IOException {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // streamingtextthisGenerate\n        String model = \"{%AI_MODEL_NAME%}\";\n        String subModel = \"{%AI_SUB_MODEL_NAME%}\";\n\n        // PrepareMessage\n        List<Map<String, String>> messages = new ArrayList<>();\n        Map<String, String> systemMsg = new HashMap<>();\n        systemMsg.put(\"role\", \"system\");\n        systemMsg.put(\"content\", \"Please strictly follow the metrical requirements of a seven-character quatrain or regulated verse to create，tonal patternneedfollow thethen，Rhyming should be harmonious and natural，rhyme characterneedinsamerhyme group。\");\n        messages.add(systemMsg);\n\n        Map<String, String> userMsg = new HashMap<>();\n        userMsg.put(\"role\", \"user\");\n        userMsg.put(\"content\", \"Spring\");\n        messages.add(userMsg);\n\n        // PrepareRequestbody\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"model\", subModel);\n        payload.put(\"messages\", messages);\n        payload.put(\"stream\", true);\n\n        // Use CloudBaseClient ConfigurationBuildstreamingRequest\n        String url = \"https://\" + cloudbase.getEnvId() + \".api.tcloudbasegateway.com/v1/ai/\" + model + \"/chat/completions\";\n        String jsonPayload = cloudbase.getGson().toJson(payload);\n\n        RequestBody requestBody = RequestBody.create(jsonPayload, MediaType.parse(\"application/json\"));\n\n        Request request = new Request.Builder()\n                .url(url)\n                .post(requestBody)\n                .addHeader(\"Content-Type\", \"application/json\")\n                .addHeader(\"Accept\", \"text/event-stream\")\n                .addHeader(\"Authorization\", \"Bearer \" + cloudbase.getAccessToken())\n                .build();\n\n        System.out.println(\"AI Streaming response:\");\n        StringBuilder fullContent = new StringBuilder();\n\n        try (Response response = cloudbase.getClient().newCall(request).execute()) {\n            if (response.isSuccessful() && response.body() != null) {\n                BufferedReader reader = new BufferedReader(\n                    new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8)\n                );\n                String line;\n\n                while ((line = reader.readLine()) != null) {\n                    if (line.startsWith(\"data: \")) {\n                        String dataStr = line.substring(6);\n                        if (!dataStr.trim().equals(\"[DONE]\")) {\n                            try {\n                                JsonObject chunkData = cloudbase.getGson().fromJson(dataStr, JsonObject.class);\n                                if (chunkData.has(\"choices\") && chunkData.getAsJsonArray(\"choices\").size() > 0) {\n                                    JsonObject choice = chunkData.getAsJsonArray(\"choices\").get(0).getAsJsonObject();\n                                    if (choice.has(\"delta\") && choice.getAsJsonObject(\"delta\").has(\"content\")) {\n                                        String content = choice.getAsJsonObject(\"delta\").get(\"content\").getAsString();\n                                        System.out.print(content);\n                                        fullContent.append(content);\n                                    }\n                                }\n                            } catch (Exception e) {\n                                // Ignore JSON parsing error\n                            }\n                        }\n                    }\n                }\n                System.out.println(); // newline\n            }\n        }\n    }\n}\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation",
                "content": []
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        try {\n            // PrepareCallparameter\n            Map<String, Object> data = new HashMap<>();\n            data.put(\"prompt\", \"A cute cat playing in the sunshine\");\n\n            // CallCloud FunctionGenerate Image\n            JsonObject result = cloudbase.request(\"POST\", \"/v1/functions/<YOUR_FUNCTION_NAME>\", data);\n\n            if (result != null) {\n                boolean success = result.has(\"success\") && result.get(\"success\").getAsBoolean();\n                \n                if (success) {\n                    String imageUrl = result.get(\"imageUrl\").getAsString();\n                    String revisedPrompt = result.has(\"revised_prompt\") \n                        ? result.get(\"revised_prompt\").getAsString() \n                        : \"\";\n                    \n                    System.out.println(\"Generation successful!\");\n                    System.out.println(\"Image URL: \" + imageUrl);\n                    System.out.println(\"Optimized prompt: \" + revisedPrompt);\n                    System.out.println(\"Note: Image URLValidis valid for24hours\");\n                } else {\n                    String code = result.has(\"code\") ? result.get(\"code\").getAsString() : \"\";\n                    String message = result.has(\"message\") ? result.get(\"message\").getAsString() : \"\";\n                    System.err.println(\"Generation failed: \" + code + \" - \" + message);\n                }\n            } else {\n                System.err.println(\"Requestfailed\");\n            }\n        } catch (Exception e) {\n            System.err.println(\"Generate Imagewhenerror: \" + e.getMessage());\n        }\n    }\n}\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation",
                "content": []
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```java\n/**\n * Java Call Agent Example (AG-UI Protocol)\n * Protocol documentation：https://docs.cloudbase.net/ai/agent-development/protocol\n */\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport okhttp3.*;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.nio.charset.StandardCharsets;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) throws IOException {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // streamingCallAgent（AG-UI Protocol)\n        String botId = \"{%AGENT_ID%}\";\n\n        // PrepareMessageList（AG-UI protocol format)\n        List<Map<String, Object>> messages = new ArrayList<>();\n        Map<String, Object> userMessage = new HashMap<>();\n        userMessage.put(\"id\", \"msg-\" + UUID.randomUUID().toString());\n        userMessage.put(\"role\", \"user\");\n        userMessage.put(\"content\", \"Who are you\");\n        messages.add(userMessage);\n\n        // PrepareRequestbody（AG-UI Protocol)\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"messages\", messages);                    // Required: Message list\n        payload.put(\"threadId\", \"thread-\" + UUID.randomUUID().toString()); // Optional: Session ID for multi-turn conversation\n        payload.put(\"runId\", \"run-\" + UUID.randomUUID().toString());       // Optional：this timeRunID\n        payload.put(\"tools\", new ArrayList<>());              // Optional: Frontend tool definitions\n        payload.put(\"context\", new ArrayList<>());            // Optional: Context information\n        payload.put(\"forwardedProps\", new HashMap<>());       // Optional: Pass-through parameters\n\n        // Use CloudBaseClient ConfigurationBuildstreamingRequest\n        String url = \"https://\" + cloudbase.getEnvId() + \".api.tcloudbasegateway.com/v1/aibot/bots/\" + botId + \"/send-message\";\n        String jsonPayload = cloudbase.getGson().toJson(payload);\n\n        RequestBody requestBody = RequestBody.create(jsonPayload, MediaType.parse(\"application/json\"));\n\n        Request request = new Request.Builder()\n                .url(url)\n                .post(requestBody)\n                .addHeader(\"Content-Type\", \"application/json\")\n                .addHeader(\"Accept\", \"text/event-stream\")\n                .addHeader(\"Authorization\", \"Bearer \" + cloudbase.getAccessToken())\n                .build();\n\n        System.out.println(\"AI Streaming response:\");\n        StringBuilder fullContent = new StringBuilder();\n\n        try (Response response = cloudbase.getClient().newCall(request).execute()) {\n            if (response.isSuccessful() && response.body() != null) {\n                BufferedReader reader = new BufferedReader(\n                    new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8)\n                );\n                String line;\n\n                while ((line = reader.readLine()) != null) {\n                    if (line.startsWith(\"data: \")) {\n                        String dataStr = line.substring(6).trim();\n                        if (!dataStr.isEmpty() && !dataStr.equals(\"[DONE]\")) {\n                            try {\n                                JsonObject chunkData = cloudbase.getGson().fromJson(dataStr, JsonObject.class);\n\n                                // support multipleResponseformat\n                                String content = null;\n                                if (chunkData.has(\"content\")) {\n                                    content = chunkData.get(\"content\").getAsString();\n                                } else if (chunkData.has(\"choices\") && chunkData.getAsJsonArray(\"choices\").size() > 0) {\n                                    JsonObject choice = chunkData.getAsJsonArray(\"choices\").get(0).getAsJsonObject();\n                                    if (choice.has(\"delta\") && choice.getAsJsonObject(\"delta\").has(\"content\")) {\n                                        content = choice.getAsJsonObject(\"delta\").get(\"content\").getAsString();\n                                    } else if (choice.has(\"message\") && choice.getAsJsonObject(\"message\").has(\"content\")) {\n                                        content = choice.getAsJsonObject(\"message\").get(\"content\").getAsString();\n                                    }\n                                }\n\n                                if (content != null && !content.isEmpty()) {\n                                    System.out.print(content);\n                                    fullContent.append(content);\n                                }\n                            } catch (Exception e) {\n                                // Ignore JSON parsing error\n                            }\n                        }\n                    }\n                }\n                System.out.println(); // newline\n            }\n        }\n    }\n}\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport okhttp3.*;\n\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.nio.charset.StandardCharsets;\nimport java.util.*;\n\npublic class Example {\n    public static void main(String[] args) throws IOException {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // streamingCallAgent\n        String botId = \"{%AGENT_ID%}\";\n        String msg = \"Who are you\";\n        List<Map<String, String>> history = new ArrayList<>();\n\n        // PrepareRequestbody\n        Map<String, Object> payload = new HashMap<>();\n        payload.put(\"history\", history);\n        payload.put(\"msg\", msg);\n\n        // Use CloudBaseClient ConfigurationBuildstreamingRequest\n        String url = \"https://\" + cloudbase.getEnvId() + \".api.tcloudbasegateway.com/v1/aibot/bots/\" + botId + \"/send-message\";\n        String jsonPayload = cloudbase.getGson().toJson(payload);\n\n        RequestBody requestBody = RequestBody.create(jsonPayload, MediaType.parse(\"application/json\"));\n\n        Request request = new Request.Builder()\n                .url(url)\n                .post(requestBody)\n                .addHeader(\"Content-Type\", \"application/json\")\n                .addHeader(\"Accept\", \"text/event-stream\")\n                .addHeader(\"Authorization\", \"Bearer \" + cloudbase.getAccessToken())\n                .build();\n\n        System.out.println(\"AI Streaming response:\");\n        StringBuilder fullContent = new StringBuilder();\n\n        try (Response response = cloudbase.getClient().newCall(request).execute()) {\n            if (response.isSuccessful() && response.body() != null) {\n                BufferedReader reader = new BufferedReader(\n                    new InputStreamReader(response.body().byteStream(), StandardCharsets.UTF_8)\n                );\n                String line;\n\n                while ((line = reader.readLine()) != null) {\n                    if (line.startsWith(\"data: \")) {\n                        String dataStr = line.substring(6).trim();\n                        if (!dataStr.isEmpty() && !dataStr.equals(\"[DONE]\")) {\n                            try {\n                                JsonObject chunkData = cloudbase.getGson().fromJson(dataStr, JsonObject.class);\n\n                                // support multipleResponseformat\n                                String content = null;\n                                if (chunkData.has(\"content\")) {\n                                    content = chunkData.get(\"content\").getAsString();\n                                } else if (chunkData.has(\"choices\") && chunkData.getAsJsonArray(\"choices\").size() > 0) {\n                                    JsonObject choice = chunkData.getAsJsonArray(\"choices\").get(0).getAsJsonObject();\n                                    if (choice.has(\"delta\") && choice.getAsJsonObject(\"delta\").has(\"content\")) {\n                                        content = choice.getAsJsonObject(\"delta\").get(\"content\").getAsString();\n                                    } else if (choice.has(\"message\") && choice.getAsJsonObject(\"message\").has(\"content\")) {\n                                        content = choice.getAsJsonObject(\"message\").get(\"content\").getAsString();\n                                    }\n                                }\n\n                                if (content != null && !content.isEmpty()) {\n                                    System.out.print(content);\n                                    fullContent.append(content);\n                                }\n                            } catch (Exception e) {\n                                // Ignore JSON parsing error\n                            }\n                        }\n                    }\n                }\n                System.out.println(); // newline\n            }\n        }\n    }\n}\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "markdown": "```java\nimport com.cloudbase.CloudBaseClient;\nimport com.google.gson.JsonObject;\nimport java.util.HashMap;\nimport java.util.Map;\n\npublic class Example {\n    public static void main(String[] args) {\n        CloudBaseClient cloudbase = new CloudBaseClient();\n\n        // Username Password Login\n        Map<String, String> credentials = new HashMap<>();\n        credentials.put(\"username\", \"your_username\");\n        credentials.put(\"password\", \"your_password\");\n\n        JsonObject result = cloudbase.request(\"POST\", \"/auth/v1/signin\", credentials);\n\n        if (result != null) {\n            String accessToken = result.get(\"access_token\").getAsString();\n            String refreshToken = result.get(\"refresh_token\").getAsString();\n            String userId = result.get(\"sub\").getAsString();\n\n            System.out.println(\"Login successful! User ID: \" + userId);\n            System.out.println(\"Access token: \" + accessToken.substring(0, 20) + \"...\");\n        }\n    }\n}\n```",
            "index": 8,
            "id": "identity",
            "title": "Authentication"
          }
        ]
      }
    ],
    "_id": "dedacaec69a9286d0044ad2206f99ffb",
    "_openid": "anon",
    "createdAt": 1769744599895,
    "updatedAt": 1769766697784
  },
  {
    "category": "Framework Integration,ORMs,Drizzle",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 14,
    "hasTemplate": false,
    "docsUrl": "https://orm.drizzle.team/docs/get-started-mysql",
    "content": [
      {
        "markdown": "Use `Drizzle` operate **MySQL Database**\n```bash\nnpm install drizzle-orm mysql2\n```",
        "title": "Install Dependencies",
        "type": "",
        "content": []
      },
      {
        "markdown": "Add the following code to your **Drizzle** project",
        "title": "Usage Example",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nimport { drizzle } from \"drizzle-orm/mysql2\";\nimport mysql from \"mysql2/promise\";\nimport { todos } from \"./schema.js\";\n\nasync function main() {\n  const connection = await mysql.createConnection(process.env.DATABASE_URL);\n  const db = drizzle(connection);\n\n  const allTodos = await db.select().from(todos);\n  console.log(allTodos);\n\n  await connection.end();\n}\n\nmain().catch(console.error);\n```",
            "title": "index.js"
          },
          {
            "markdown": "```js\nimport { mysqlTable, text } from \"drizzle-orm/mysql-core\";\n\nexport const todos = mysqlTable(\"todos\", {\n  id: text(\"_id\").primaryKey(),\n  title: text(\"title\"),\n});\n```",
            "id": "",
            "title": "schema.js"
          },
          {
            "markdown": "```\nDATABASE_URL=mysql://{%DATABASE_URL%}\n```",
            "id": "mysqlString",
            "title": ".env"
          }
        ]
      }
    ],
    "_id": "e4bc589369a9286c0044b35213a72044",
    "_openid": "anon",
    "createdAt": 1769744595879,
    "updatedAt": 1769766693678
  },
  {
    "category": "Framework Integration,MiniProgram / MiniGame,MiniProgram",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 1,
    "hasTemplate": false,
    "docsUrl": "https://developers.weixin.qq.com/miniprogram/dev/wxcloudservice/wxcloud/guide/init.html",
    "content": [
      {
        "markdown": "in `app.js` InitializeCloudBase：",
        "index": 1,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "mostCloudBasecapabilities canUse `Mini ProgramNative API` directlyCall，NoneneedInstall SDK，If `NativeAPI` Not supported pleaseUse `Client SDK` performCall\n\n```js\nApp({\n  onLaunch() {\n    wx.cloud.init({\n      env: \"{%ENV_ID%}\"\n    });\n  }\n});\n```",
            "index": 1,
            "title": "NativeAPI Initialize",
            "content": []
          },
          {
            "markdown": "**Install**\n\nUse Client SDK before please firstInstall SDK\n\ninMini Program `package.json` theinDirectory（usually `miniprogram` Directory）execute：\n\n```bash\nnpm i @cloudbase/wx-cloud-client-sdk --save\n```\n\nInstallDoneafter，inWeChatClick in developer tools **tool → Build npm**。\n\n**Initialize**\n\n```js\nconst { init } = require(\"@cloudbase/wx-cloud-client-sdk\");\n\nApp({\n  onLaunch() {\n    wx.cloud.init({\n      env: \"{%ENV_ID%}\"\n    });\n    this.globalData.cloudbase = init(wx.cloud);\n  },\n  globalData: {}\n});\n```",
            "index": 2,
            "title": "Client SDK Initialize",
            "content": []
          }
        ]
      },
      {
        "index": 2,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "markdown": "pleaseUse `Client SDK` performCall",
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Query {%TABLE_NAME%} table first 10 records\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n\nconsole.log(\"QueryResult:\", data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Add {%TABLE_NAME%} table data\nconst { data, error } = await cloudbase.rdb().from(\"{%TABLE_NAME%}\").insert({\n  title: \"Example Title\"\n});\n\nconsole.log(\"AddResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Update {%TABLE_NAME%} table id as <DataID> Data\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({\n    title: \"UpdateafterTitle\"\n  })\n  .eq(\"id\", \"<DataID>\");\n\nconsole.log(\"UpdateResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Example Title\" });\n\nconsole.log(\"AddUpdateResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Delete {%TABLE_NAME%} table id as <DataID> Data\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", \"<DataID>\");\n\nconsole.log(\"DeleteResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Query {%TABLE_NAME%} table first 10 records\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n\nconsole.log(res.data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Add {%TABLE_NAME%} table data\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({\n  data: {\n    title: \"Example Title\",\n    content: \"ExampleContent\"\n  }\n});\n\nconsole.log(res);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Update {%TABLE_NAME%} table id as <DataID> Data\nconst res = await db\n  .collection(\"{%TABLE_NAME%}\")\n  .doc(\"<DataID>\")\n  .update({\n    data: {\n      title: \"UpdateafterTitle\"\n    }\n  });\n\nconsole.log(res.stats.updated);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Delete {%TABLE_NAME%} table id as <DataID> Data\nconst res = await db.collection(\"{%TABLE_NAME%}\").doc(\"<DataID>\").remove();\n\nconsole.log(res.stats.removed);\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "pleaseUse `Client SDK` performCall",
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Query {%TABLE_NAME%} Data Modelbefore10recordsData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\n\nconsole.log(res.data.records);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Add {%TABLE_NAME%} Data ModelData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: {\n    title: \"Example Title\",\n    content: \"ExampleContent\"\n  }\n});\n\nconsole.log(res.data);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Update {%TABLE_NAME%} Data Model _id as <DataID> Data\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: {\n    title: \"UpdateafterTitle\"\n  },\n  filter: {\n    where: {\n      _id: {\n        $eq: \"<DataID>\"\n      }\n    }\n  }\n});\n\nconsole.log(res.data);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nconst cloudbase = getApp().globalData.cloudbase;\n\n// Delete {%TABLE_NAME%} Data Model _id as <DataID> Data\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: {\n    where: {\n      _id: {\n        $eq: \"<DataID>\"\n      }\n    }\n  }\n});\n\nconsole.log(res.data);\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "```js\n// Call {%FUNCTION_NAME%} Cloud Function\nconst res = await wx.cloud.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {} // Cloud Functioninput parameters\n});\n\nconsole.log(res.result);\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function",
            "content": []
          },
          {
            "markdown": "```js\n// Call {%SERVICE_NAME%} Cloud Runservice\nconst res = await wx.cloud.callContainer({\n  config: {\n    env: \"{%ENV_ID%}\" // andMini ProgramalreadyAssociationCloudBaseEnvironment ID\n  },\n  path: \"/\", // businessCustomPath，rootDirectoryas /\n  method: \"GET\", // Choose according to business needs\n  header: {\n    \"X-WX-SERVICE\": \"{%SERVICE_NAME%}\" // Cloud RunserviceName\n    // other header\n  }\n  // dataType: 'text' // Defaultas JSON；if neededmanuallyParsecan be set to 'text'\n});\n\nconsole.log(res);\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run",
            "content": []
          },
          {
            "index": 1,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nwx.chooseMedia({\n  count: 1,\n  mediaType: [\"image\", \"video\"],\n  sourceType: [\"album\", \"camera\"],\n  success: async res => {\n    const res = await wx.cloud.uploadFile({\n      cloudPath: \"images/\" + Date.now() + \".png\", // Path to upload in cloud\n      filePath: res.tempFiles[0].tempFilePath // Mini ProgramtemporaryfilePath\n    });\n\n    console.log(res.fileID);\n  }\n});\n```",
                "index": 1,
                "title": "Upload File"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.getTempFileURL({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\n\nconsole.log(res.fileList);\n// fileListExample\n// [{\n//    fileID: \"cloud://xxx.png\", // file ID\n//    tempFileURL: \"https://xxx.png\", // temporaryfilenetworkURL\n//    maxAge: 120 * 60 * 1000, // Validperiod\n// }]\n```",
                "index": 2,
                "title": "Get File URL"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.downloadFile({\n  fileID: \"cloud://xxx.png\" // File fileID\n});\n\nconsole.log(res.tempFilePath); // ReturntemporaryfilePath\n```",
                "index": 3,
                "title": "Download File"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.deleteFile({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\n\nconsole.log(res.fileList);\n```",
                "index": 4,
                "title": "Delete File"
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst res = await wx.cloud.extend.AI.createModel(\n  \"{%AI_MODEL_NAME%}\"\n).streamText({\n  data: {\n    model: \"{%AI_SUB_MODEL_NAME%}\",\n    messages: [\n      {\n        role: \"user\",\n        content: \"Hello\"\n      }\n    ]\n  }\n});\n\nfor await (let event of res.eventStream) {\n  if (event.data === \"[DONE]\") {\n    break;\n  }\n  const data = JSON.parse(event.data);\n\n  // WhenUse deepseek-r1 when，model willGeneratereasoning chainContent\n  const think = data?.choices?.[0]?.delta?.reasoning_content;\n  if (think) {\n    console.log(think);\n  }\n\n  // Print generated text content\n  const text = data?.choices?.[0]?.delta?.content;\n  if (text) {\n    console.log(text);\n  }\n}\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation"
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```js\n// Call image generation cloud function\nwx.cloud.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: {\n    prompt: \"A cute cat playing in the sunshine\"\n  },\n  success: res => {\n    const result = res.result;\n\n    if (result.success) {\n      // Generation successful\n      console.log(\"Generation successful!\");\n      console.log(\"Image URL:\", result.imageUrl);\n      console.log(\"Optimized prompt:\", result.revised_prompt);\n\n      // Use image\n      // Note: Image URL is valid for 24 hours, please save or transfer promptly\n    } else {\n      // Generation failed\n      console.error(\"Generation failed:\", result.code, result.message);\n    }\n  },\n  fail: err => {\n    console.error(\"Call failed:\", err);\n  }\n});\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation"
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "\n```js\nfunction generateId() {\n  const timestamp = Date.now().toString().slice(-4);\n  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');\n  return timestamp + random;\n}\n\nasync function sendMessage(message) {\n  const res = await wx.cloud.extend.AI.bot.sendMessage({\n    data: {\n      // botId is required to identify the Agent\n      botId: '{%AGENT_ID%}',\n      // Refer to the HTTP Agent protocol for parameter structure:\n      // https://docs.cloudbase.net/ai/agent/http-agent-protocol\n      threadId: 'thread_id_' + generateId(),\n      runId: 'run_id_' + generateId(),\n      messages: [\n        { id: String(Date.now()), role: 'user', content: message }\n      ],\n      tools: [],\n      context: [],\n      state: {},\n      forwardedProps: {},\n    }\n  });\n\n  // Receive streaming response\n  let response = '';\n  for await (const event of res.eventStream) {\n    // Parse event.data manually\n    const data = JSON.parse(event.data);\n    // Output based on event type, see docs:\n    // https://docs.cloudbase.net/ai/agent/http-agent-protocol#response-events\n    switch (data.type) {\n      case 'TEXT_MESSAGE_CONTENT':\n        response += data.delta;\n        console.log(data.delta);  // Real-time output\n        break;\n\n      case 'RUN_ERROR':\n        console.error('Run error:', data.message);\n        break;\n\n      case 'RUN_FINISHED':\n        // Run finished\n        break;\n    }\n  }\n\n  return response;\n}\n\nsendMessage('Hello');\n```\n",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.extend.AI.bot.sendMessage({\n  data: {\n    botId: \"{%AGENT_ID%}\",\n    msg: \"Hello\"\n  }\n});\n\nfor await (const event of res.eventStream) {\n  if (event.data === \"[DONE]\") {\n    break;\n  }\n  const data = JSON.parse(event.data);\n\n  // WhenUse deepseek-r1 when，model willGeneratereasoning chainContent\n  const think = data.reasoning_content;\n  if (think) {\n    console.log(think);\n  }\n\n  // Print output content\n  const content = data.content;\n  if (content) {\n    console.log(content);\n  }\n}\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          }
        ]
      }
    ],
    "_id": "e4bc589369a928710044b3a770e25874",
    "_openid": "anon",
    "createdAt": 1769767029468,
    "updatedAt": 1775130293399
  },
  {
    "category": "Framework Integration,Web Frameworks,Vue(Vite)",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 4,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/en/api-reference/webv2/initialization",
    "content": [
      {
        "markdown": "`@cloudbase/js-sdk` allows you to use JavaScript on Web (such as PC web pages, WeChat H5, etc.) to access CloudBase services and resources.()",
        "index": 1,
        "title": "Install SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```bash\nnpm i @cloudbase/js-sdk\n```",
            "index": 1,
            "title": "npm",
            "content": []
          },
          {
            "markdown": "```bash\nyarn add @cloudbase/js-sdk\n```",
            "index": 2,
            "title": "yarn",
            "content": []
          },
          {
            "markdown": "```bash\npnpm add @cloudbase/js-sdk\n```",
            "index": 3,
            "title": "pnpm",
            "content": []
          }
        ]
      },
      {
        "markdown": "Add the following code to your Vue project",
        "index": 2,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```js\nimport cloudbaseSDK from \"@cloudbase/js-sdk\";\n\nexport const cloudbase = cloudbaseSDK.init({\n  env: import.meta.env.VITE_CLOUDBASE_ENV_ID,\n  region: import.meta.env.VITE_CLOUDBASE_REGION,\n  accessKey: import.meta.env.VITE_CLOUDBASE_ACCESS_KEY\n});\n```",
            "index": 1,
            "title": "src/utils/cloudbase.js",
            "content": []
          },
          {
            "markdown": "```properties\n# Environment ID\nVITE_CLOUDBASE_ENV_ID={%ENV_ID%}\n\n# Region\nVITE_CLOUDBASE_REGION={%REGION%}\n\n# Anonymous access token\nVITE_CLOUDBASE_ACCESS_KEY={%PUBLISHABLE_KEY%}\n```",
            "index": 2,
            "title": ".env",
            "content": []
          }
        ]
      },
      {
        "index": 3,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table first 10 records\nconst { data: result, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\nif (!error) {\n  console.log(result);\n}\n```\n\n**Full Example:**\n\n```vue\n<template>\n  <ul>\n    <li v-for=\"item in data\" :key=\"item.id\">{{ item.title }}</li>\n  </ul>\n</template>\n\n<script setup>\nimport { ref, onMounted } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref([]);\n\nconst getData = async () => {\n  // Query {%TABLE_NAME%} table first 10 records\n  const { data: result, error } = await cloudbase\n    .rdb()\n    .from(\"{%TABLE_NAME%}\")\n    .select(\"*\")\n    .limit(10);\n  if (!error) data.value = result || [];\n};\n\nonMounted(() => {\n  getData();\n});\n</script>\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} table data\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"Example Title\" });\nif (!error) {\n  console.log(\"Insert successful\");\n}\n```\n\n**Full Example:**\n\n```vue\n<template>\n  <div>\n    <input v-model=\"title\" />\n    <button @click=\"addData\">Add</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst title = ref(\"\");\nconst message = ref(\"\");\n\nconst addData = async () => {\n  // Add {%TABLE_NAME%} table data\n  const { error } = await cloudbase.rdb().from(\"{%TABLE_NAME%}\").insert({ title: title.value });\n  if (!error) {\n    title.value = \"\";\n    message.value = \"Insert successful！\";\n  } else {\n    message.value = \"Insert failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} table id with specified value\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ title: \"New Title\" })\n  .eq(\"id\", \"<data id>\");\nif (!error) {\n  console.log(\"Update successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"updateData\">Update</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst updateData = async () => {\n  // Update {%TABLE_NAME%} table id with specified value\n  const { error } = await cloudbase.rdb().from(\"{%TABLE_NAME%}\").update({ title: \"New Title\" }).eq(\"id\", \"<data id>\");\n  if (!error) {\n    message.value = \"Update successful！\";\n  } else {\n    message.value = \"Update failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Example Title\" });\nif (!error) {\n  console.log(\"Operation successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"upsertData\">UpdateorCreate</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst upsertData = async () => {\n  // If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\n  const { error } = await cloudbase.rdb().from(\"{%TABLE_NAME%}\").upsert({ id: 1, title: \"Example Title\" });\n  if (!error) {\n    message.value = \"Operation successful！\";\n  } else {\n    message.value = \"Operation failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} table id with specified value\nconst { error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", \"<data id>\");\nif (!error) {\n  console.log(\"Delete successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"deleteData\">Delete</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst deleteData = async () => {\n  // Delete {%TABLE_NAME%} table id with specified value\n  const { error } = await cloudbase.rdb().from(\"{%TABLE_NAME%}\").delete().eq(\"id\", \"<data id>\");\n  if (!error) {\n    message.value = \"Delete successful！\";\n  } else {\n    message.value = \"Delete failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} table first 10 records\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\nconsole.log(res.data);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <ul>\n    <li v-for=\"item in data\" :key=\"item._id\">{{ item.title }}</li>\n  </ul>\n</template>\n\n<script setup>\nimport { ref, onMounted } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref([]);\n\nconst getData = async () => {\n  // Query {%TABLE_NAME%} table first 10 records\n  const db = cloudbase.database();\n  const res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n  data.value = res.data || [];\n};\n\nonMounted(() => {\n  getData();\n});\n</script>\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} table data\nconst db = cloudbase.database();\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({ title: \"Example Title\" });\nconsole.log(`Insert successful! id: ${res.id}`);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"addData\">Add</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst addData = async () => {\n  try {\n    // Add {%TABLE_NAME%} table data\n    const db = cloudbase.database();\n    const res = await db.collection(\"{%TABLE_NAME%}\").add({ title: \"Example Title\" });\n    message.value = `Insert successful! id: ${res.id}`;\n  } catch (error) {\n    message.value = \"Insert failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} table id with specified value\nconst db = cloudbase.database();\nawait db\n  .collection(\"{%TABLE_NAME%}\")\n  .doc(\"<data id>\")\n  .update({ title: \"New Title\" });\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"updateData\">Update</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst updateData = async () => {\n  try {\n    // Update {%TABLE_NAME%} table id with specified value\n    const db = cloudbase.database();\n    await db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").update({ title: \"New Title\" });\n    message.value = \"Update successful！\";\n  } catch (error) {\n    message.value = \"Update failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} table id with specified value\nconst db = cloudbase.database();\nawait db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").remove();\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"deleteData\">Delete</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst deleteData = async () => {\n  try {\n    // Delete {%TABLE_NAME%} table id with specified value\n    const db = cloudbase.database();\n    await db.collection(\"{%TABLE_NAME%}\").doc(\"<data id>\").remove();\n    message.value = \"Delete successful！\";\n  } catch (error) {\n    message.value = \"Delete failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Query {%TABLE_NAME%} Data Modelbefore10recordsData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\nconsole.log(res.data?.records);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <ul>\n    <li v-for=\"item in data\" :key=\"item._id\">{{ item.title }}</li>\n  </ul>\n</template>\n\n<script setup>\nimport { ref, onMounted } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref([]);\n\nconst getData = async () => {\n  // Query {%TABLE_NAME%} Data Modelbefore10recordsData\n  const res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n    pageNumber: 1,\n    pagesize: 10\n  });\n  data.value = res.data?.records || [];\n};\n\nonMounted(() => {\n  getData();\n});\n</script>\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Add {%TABLE_NAME%} Data ModelData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: { title: \"Example Title\" }\n});\nconsole.log(`Insert successful! id: ${res.data.id}`);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"addData\">Add</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst addData = async () => {\n  try {\n    // Add {%TABLE_NAME%} Data ModelData\n    const res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({ data: { title: \"Example Title\" } });\n    message.value = `Insert successful! id: ${res.data.id}`;\n  } catch (error) {\n    message.value = \"Insert failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Update {%TABLE_NAME%} Data Model _id with specified value\nawait cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: { title: \"New Title\" },\n  filter: { where: { _id: { $eq: \"<data id>\" } } }\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"updateData\">Update</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst updateData = async () => {\n  try {\n    // Update {%TABLE_NAME%} Data Model _id with specified value\n    await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n      data: { title: \"New Title\" },\n      filter: { where: { _id: { $eq: \"<data id>\" } } }\n    });\n    message.value = \"Update successful！\";\n  } catch (error) {\n    message.value = \"Update failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Delete {%TABLE_NAME%} Data Model _id with specified value\nawait cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: { where: { _id: { $eq: \"<data id>\" } } }\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"deleteData\">Delete</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst deleteData = async () => {\n  try {\n    // Delete {%TABLE_NAME%} Data Model _id with specified value\n    await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n      filter: { where: { _id: { $eq: \"<data id>\" } } }\n    });\n    message.value = \"Delete successful！\";\n  } catch (error) {\n    message.value = \"Delete failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call {%FUNCTION_NAME%} Cloud Function\nconst res = await cloudbase.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {}\n});\nconsole.log(res.result);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"getData\">CallCloud Function</button>\n    <pre v-if=\"data\">{{ JSON.stringify(data, null, 2) }}</pre>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref(null);\n\nconst getData = async () => {\n  // Call {%FUNCTION_NAME%} Cloud Function\n  const res = await cloudbase.callFunction({\n    name: \"{%FUNCTION_NAME%}\",\n    data: {}\n  });\n  data.value = res.result;\n};\n</script>\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function",
            "content": []
          },
          {
            "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call {%SERVICE_NAME%} Cloud Runservice\nconst res = await cloudbase.callContainer({\n  name: \"{%SERVICE_NAME%}\"\n  method: 'POST',\n  path: '/',\n  header:{\n    'Content-Type': 'application/json; charset=utf-8'\n  },\n  data: {},\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"getData\">CallCloud Run</button>\n    <pre v-if=\"data\">{{ JSON.stringify(data, null, 2) }}</pre>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref(null);\n\nconst getData = async () => {\n  // Call {%SERVICE_NAME%} Cloud Runservice\n  const res = await cloudbase.callContainer({\n    name: \"{%SERVICE_NAME%}\"\n    method: 'POST',\n    path: '/',\n    header:{\n      'Content-Type': 'application/json; charset=utf-8'\n    },\n    data: {},\n  });\n  data.value = res;\n};\n</script>\n```",
            "index": 5,
            "id": "run",
            "title": "Cloud Run",
            "content": []
          },
          {
            "index": 6,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.uploadFile({\n  cloudPath: `images/${Date.now()}-${file.name}`, // Path to upload in cloud\n  filePath: file\n});\nconsole.log(res.fileID);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <input type=\"file\" @change=\"uploadFile\" />\n    <p v-if=\"fileID\">Upload successful: {{ fileID }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst fileID = ref(\"\");\n\nconst uploadFile = async e => {\n  const file = e.target.files[0];\n  const res = await cloudbase.uploadFile({\n    cloudPath: `images/${Date.now()}-${file.name}`, // Path to upload in cloud\n    filePath: file\n  });\n  fileID.value = res.fileID;\n};\n</script>\n```",
                "index": 1,
                "title": "Upload File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.getTempFileURL({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\nconsole.log(res.fileList[0].tempFileURL);\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"getData\">GetURL</button>\n    <p v-if=\"fileUrl\">URL: {{ fileUrl }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst fileUrl = ref(\"\");\n\nconst getData = async () => {\n  const res = await cloudbase.getTempFileURL({\n    fileList: [\"cloud://xxx.png\"] // File fileID list\n  });\n  fileUrl.value = res.fileList[0].tempFileURL;\n};\n</script>\n```",
                "index": 2,
                "title": "Get File URL"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nawait cloudbase.downloadFile({\n  fileID: \"cloud://xxx.png\" // File fileID\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <button @click=\"downloadFile\">Download File</button>\n</template>\n\n<script setup>\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst downloadFile = async () => {\n  await cloudbase.downloadFile({\n    fileID: \"cloud://xxx.png\" // File fileID\n  });\n};\n</script>\n```",
                "index": 3,
                "title": "Download File"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.deleteFile({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\nif (res.fileList[0].code === \"SUCCESS\") {\n  console.log(\"Delete successful\");\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button @click=\"deleteFile\">Delete File</button>\n    <p v-if=\"message\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\n\nconst deleteFile = async () => {\n  const res = await cloudbase.deleteFile({\n    fileList: [\"cloud://xxx.png\"] // File fileID list\n  });\n  if (res.fileList[0].code === \"SUCCESS\") {\n    message.value = \"Delete successful！\";\n  } else {\n    ((message.value = \"Delete failed！\"), res.fileList);\n  }\n};\n</script>\n```",
                "index": 4,
                "title": "Delete File"
              }
            ]
          },
          {
            "index": 7,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase\n  .ai()\n  .createModel(\"{%AI_MODEL_NAME%}\")\n  .streamText({\n    model: \"{%AI_SUB_MODEL_NAME%}\",\n    messages: [{ role: \"user\", content: \"Hello\" }]\n  });\n\nfor await (let data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data?.choices?.[0]?.delta?.reasoning_content;\n  if (think) console.log(think);\n\n  // Print generated text content\n  const text = data?.choices?.[0]?.delta?.content;\n  if (text) console.log(text);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <input v-model=\"input\" placeholder=\"Enter AI conversation content\" />\n    <button @click=\"getData\">Send</button>\n    <p>{{ data }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref(\"\");\nconst input = ref(\"\");\n\nconst getData = async () => {\n  const res = await cloudbase\n    .ai()\n    .createModel(\"{%AI_MODEL_NAME%}\")\n    .streamText({\n      model: \"{%AI_SUB_MODEL_NAME%}\",\n      messages: [{ role: \"user\", content: input.value }]\n    });\n\n  let result = \"\";\n  for await (let item of res.dataStream) {\n    // Print reasoning content if available\n    const think = item?.choices?.[0]?.delta?.reasoning_content;\n    if (think) {\n      result += think;\n    }\n\n    // Print generated text content\n    const text = item?.choices?.[0]?.delta?.content;\n    if (text) result += text;\n\n    data.value = result;\n  }\n};\n</script>\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation"
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\n// Call image generation cloud function\nconst res = await cloudbase.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: {\n    prompt: \"A cute cat playing in the sunshine\"\n  }\n});\n\nconst result = res.result;\n\nif (result.success) {\n  // Generation successful\n  console.log(\"Generation successful!\");\n  console.log(\"Image URL:\", result.imageUrl);\n  console.log(\"Optimized prompt:\", result.revised_prompt);\n\n  // Use image\n  // Note: Image URL is valid for 24 hours, please save or transfer promptly\n} else {\n  // Generation failed\n  console.error(\"Generation failed:\", result.code, result.message);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <input v-model=\"prompt\" placeholder=\"Enter image description\" />\n    <button @click=\"generateImage\" :disabled=\"!prompt || loading\">\n      {{ loading ? \"Generating...\" : \"Generate Image\" }}\n    </button>\n    <p v-if=\"message\" :style=\"{ color: message.includes('successful') ? 'green' : 'red' }\">\n      {{ message }}\n    </p>\n    <div v-if=\"imageUrl\">\n      <img :src=\"imageUrl\" alt=\"Generated image\" style=\"max-width: 100%\" />\n      <p style=\"font-size: 12px; color: #666\">\n        Note: Image URL is valid for 24 hours, please save promptly\n      </p>\n    </div>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst prompt = ref(\"\");\nconst imageUrl = ref(\"\");\nconst message = ref(\"\");\nconst loading = ref(false);\n\nconst generateImage = async () => {\n  loading.value = true;\n  message.value = \"\";\n  imageUrl.value = \"\";\n\n  try {\n    // Call image generation cloud function\n    const res = await cloudbase.callFunction({\n      name: \"<YOUR_FUNCTION_NAME>\",\n      data: {\n        prompt: prompt.value\n      }\n    });\n\n    const result = res.result;\n\n    if (result.success) {\n      imageUrl.value = result.imageUrl;\n      message.value = \"Generation successful！\";\n    } else {\n      message.value = `Generation failed：${result.message}`;\n    }\n  } catch (error) {\n    message.value = \"Call failed：\" + error.message;\n  } finally {\n    loading.value = false;\n  }\n};\n</script>\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation"
              }
            ]
          },
          {
            "markdown": "",
            "index": 8,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from './utils/cloudbase';\n\nconst res = await cloudbase.ai().bot.sendMessage({\n  botId: '{%AGENT_ID%}',\n  // Refer to frontend-backend communication protocol for input structure：\n  //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n  threadId: '550e8400-e29b-41d4-a716-446655440000',\n  runId: 'run_001',\n  messages: [\n    {\n      id: 'msg_001',\n      role: 'user',\n      content: 'Hello',\n    },\n  ],\n  tools: [],\n  context: [],\n  state: {},\n  forwardedProps: {},\n});\n\nfor await (const data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data.reasoning_content;\n  if (think) console.log(think);\n\n  // Print output content\n  const content = data.content;\n  if (content) console.log(content);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <input v-model=\"input\" placeholder=\"Enter Agent conversation content\" />\n    <button @click=\"getData\">Send</button>\n    <p>{{ data }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref(\"\");\nconst input = ref(\"\");\n\nconst getData = async () => {\n  const res = await cloudbase.ai().bot.sendMessage({\n    botId: \"{%AGENT_ID%}\",\n    // Refer to frontend-backend communication protocol for input structure：\n    //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n    threadId: '550e8400-e29b-41d4-a716-446655440000',\n    runId: 'run_001',\n    messages: [\n      {\n        id: 'msg_001',\n        role: 'user',\n        content: input.value,\n      },\n    ],\n    tools: [],\n    context: [],\n    state: {},\n    forwardedProps: {},\n    });\n\n  let result = \"\";\n  for await (const item of res.dataStream) {\n    // Print reasoning content if available\n    const think = item.reasoning_content;\n    if (think) {\n      result += think;\n    }\n\n    // Print output content\n    const content = item.content;\n    if (content) result += content;\n\n    data.value = result;\n  }\n};\n</script>\n\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst res = await cloudbase.ai().bot.sendMessage({\n  botId: \"{%AGENT_ID%}\",\n  msg: \"Hello\"\n});\n\nfor await (const data of res.dataStream) {\n  // Print reasoning content if available\n  const think = data.reasoning_content;\n  if (think) console.log(think);\n\n  // Print output content\n  const content = data.content;\n  if (content) console.log(content);\n}\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <input v-model=\"input\" placeholder=\"Enter Agent conversation content\" />\n    <button @click=\"getData\">Send</button>\n    <p>{{ data }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst data = ref(\"\");\nconst input = ref(\"\");\n\nconst getData = async () => {\n  const res = await cloudbase.ai().bot.sendMessage({\n    botId: \"{%AGENT_ID%}\",\n    msg: input.value\n  });\n\n  let result = \"\";\n  for await (const item of res.dataStream) {\n    // Print reasoning content if available\n    const think = item.reasoning_content;\n    if (think) {\n      result += think;\n    }\n\n    // Print output content\n    const content = item.content;\n    if (content) result += content;\n\n    data.value = result;\n  }\n};\n</script>\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          },
          {
            "index": 9,
            "id": "identity",
            "title": "Authentication",
            "type": "sideTab",
            "content": [
              {
                "markdown": "Use **SMS Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMSVerification code**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: phone });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  phone_number: `+86 ${phone}`,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${phone.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <label>Phone number：</label>\n    <input v-model=\"phone\" placeholder=\"13800000000\" />\n    <div>\n      <label>Verification code：</label>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button :disabled=\"!phone\" @click=\"sendCode\">Send Code</button>\n    </div>\n    <button :disabled=\"!verificationId || !code\" @click=\"register\">Register</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst phone = ref(\"\");\nconst code = ref(\"\");\nconst verificationId = ref(\"\");\nconst message = ref(\"\");\n\n// Send Code\nconst sendCode = async () => {\n  try {\n    const auth = cloudbase.auth();\n    const res = await auth.getVerification({ phone_number: phone.value });\n    verificationId.value = res.verification_id;\n    message.value = \"Verification code sent！\";\n  } catch (error) {\n    message.value = \"Send failed：\" + error.message;\n  }\n};\n\n// Register\nconst register = async () => {\n  try {\n    const auth = cloudbase.auth();\n    // Verify the code\n    const verifyRes = await auth.verify({\n      verification_id: verificationId.value,\n      verification_code: code.value,\n    });\n    // Register (auto-login if user exists)\n    await auth.signUp({\n      phone_number: `+86 ${phone.value}`,\n      verification_code: code.value,\n      verification_token: verifyRes.verification_token,\n      name: `user_${phone.value.slice(-4)}`,\n      password: \"admin@123\"\n    });\n    message.value = \"Registration successful！\";\n  } catch (error) {\n    message.value = \"Registration failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 1,
                "title": "SMS Code Registration"
              },
              {
                "markdown": "Use **Email Code Registration** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Verify the code\nconst verifyRes = await auth.verify({\n  verification_id: verificationId,\n  verification_code: code\n});\n\n// Register (auto-login if user exists)\nawait auth.signUp({\n  email,\n  verification_code: code,\n  verification_token: verifyRes.verification_token,\n  name: `user_${email.slice(-4)}`,\n  password: \"admin@123\"\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <label>Email：</label>\n    <input v-model=\"email\" placeholder=\"example@email.com\" />\n    <div>\n      <label>Verification code：</label>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button :disabled=\"!email\" @click=\"sendCode\">Send Code</button>\n    </div>\n    <button :disabled=\"!verificationId || !code\" @click=\"register\">Register</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst email = ref(\"\");\nconst code = ref(\"\");\nconst verificationId = ref(\"\");\nconst message = ref(\"\");\n\n// Send Code\nconst sendCode = async () => {\n  try {\n    const auth = cloudbase.auth();\n    const res = await auth.getVerification({ email: email.value });\n    verificationId.value = res.verification_id;\n    message.value = \"Verification code sent！\";\n  } catch (error) {\n    message.value = \"Send failed：\" + error.message;\n  }\n};\n\n// Register\nconst register = async () => {\n  try {\n    const auth = cloudbase.auth();\n    // Verify the code\n    const verifyRes = await auth.verify({\n      verification_id: verificationId.value,\n      verification_code: code.value,\n    });\n    // Register (auto-login if user exists)\n    await auth.signUp({\n      email: email.value,\n      verification_code: code.value,\n      verification_token: verifyRes.verification_token,\n      name: `user_${email.value.slice(-4)}`,\n      password: \"admin@123\"\n    });\n    message.value = \"Registration successful！\";\n  } catch (error) {\n    message.value = \"Registration failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 2,
                "title": "Email Code Registration"
              },
              {
                "markdown": "Use **Username Password Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **UsernamePasswordLogin**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\nawait auth.signIn({\n  username, // Can be username, phone or email\n  password\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <label>Account：</label>\n    <input v-model=\"username\" placeholder=\"Username/Phone/Email\" />\n    Note: Add country code for phone login +86\n    <br />\n    <label>Password：</label>\n    <input\n      type=\"password\"\n      v-model=\"password\"\n      placeholder=\"Enter password\"\n    />\n    <br />\n    <button :disabled=\"!username || !password\" @click=\"login\">Login</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst username = ref(\"\");\nconst password = ref(\"\");\nconst message = ref(\"\");\n\n// Login\nconst login = async () => {\n  try {\n    const auth = cloudbase.auth();\n    await auth.signIn({\n      username: username.value, // Can be username, phone or email\n      password: password.value,\n    });\n    message.value = \"Login successful！\";\n  } catch (error) {\n    message.value = \"Login failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 3,
                "id": "UserNameLogin",
                "title": "Username Password Login"
              },
              {
                "markdown": "Use **SMS Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **SMS Verification Login**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ phone_number: `+86 ${phone}` });\n\n// Login\nawait auth.signInWithSms({\n  verificationInfo: res,\n  verificationCode: code,\n  phoneNum: `+86 ${phone}`\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <label>Phone number：</label>\n    <input v-model=\"phone\" placeholder=\"13800000000\" />\n    <div>\n      <label>Verification code：</label>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button @click=\"sendCode\" :disabled=\"!phone\">Send Code</button>\n    </div>\n    <button @click=\"login\" :disabled=\"!verificationInfo || !code\">Login</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst phone = ref(\"\");\nconst code = ref(\"\");\nconst verificationInfo = ref(null);\nconst message = ref(\"\");\n\n// Send Code\nconst sendCode = async () => {\n  try {\n    const auth = cloudbase.auth();\n    const res = await auth.getVerification({ phone_number: `+86 ${phone.value}` });\n    verificationInfo.value = res;\n    message.value = \"Verification code sent！\";\n  } catch (error) {\n    message.value = \"Send failed：\" + error.message;\n  }\n};\n\n// Login\nconst login = async () => {\n  try {\n    const auth = cloudbase.auth();\n    await auth.signInWithSms({\n      verificationInfo: verificationInfo.value,\n      verificationCode: code.value,\n      phoneNum: `+86 ${phone.value}`\n    });\n    message.value = \"Login successful！\";\n  } catch (error) {\n    message.value = \"Login failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 4,
                "id": "PhoneNumberLogin",
                "title": "SMS Verification Login"
              },
              {
                "markdown": "Use **Email Verification Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **EmailVerification code**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Send Code\nconst res = await auth.getVerification({ email });\n\n// Login\nawait auth.signInWithEmail({\n  verificationInfo: res,\n  verificationCode: code,\n  email\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <label>Email：</label>\n    <input v-model=\"email\" placeholder=\"example@email.com\" />\n    <div>\n      <label>Verification code：</label>\n      <input v-model=\"code\" placeholder=\"Verification code\" />\n      <button @click=\"sendCode\" :disabled=\"!email\">Send Code</button>\n    </div>\n    <button @click=\"login\" :disabled=\"!verificationInfo || !code\">Login</button>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">{{ message }}</p>\n  </div>\n</template>\n\n<script setup>\nimport { ref } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst email = ref(\"\");\nconst code = ref(\"\");\nconst verificationInfo = ref(null);\nconst message = ref(\"\");\n\n// Send Code\nconst sendCode = async () => {\n  try {\n    const auth = cloudbase.auth();\n    const res = await auth.getVerification({ email: email.value });\n    verificationInfo.value = res;\n    message.value = \"Verification code sent！\";\n  } catch (error) {\n    message.value = \"Send failed：\" + error.message;\n  }\n};\n\n// Login\nconst login = async () => {\n  try {\n    const auth = cloudbase.auth();\n    await auth.signInWithEmail({\n      verificationInfo: verificationInfo.value,\n      verificationCode: code.value,\n      email: email.value\n    });\n    message.value = \"Login successful！\";\n  } catch (error) {\n    message.value = \"Login failed：\" + error.message;\n  }\n};\n</script>\n```",
                "index": 5,
                "id": "email",
                "title": "Email Verification Login"
              },
              {
                "markdown": "Use **Google OAuth Login** Please go to [Authentication/Loginmethod](https://tcb.cloud.tencent.com/dev?envId={%ENV_ID%}#/identity/login-manage) enable **Google OAuth Login**\n\n**Usage：**\n\n```js\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst auth = cloudbase.auth();\n\n// Step1：GenerateGoogleauthorization URLandRedirect\nconst state = Date.now().toString();\nlocalStorage.setItem(\"google_login_state\", state);\nconst { uri } = await auth.genProviderRedirectUri({\n  provider_id: \"google\",\n  provider_redirect_uri: window.location.href,\n  state: state\n});\nwindow.location.href = uri;\n\n// Step2：Usecodeexchange forprovider_token\nconst { provider_token } = await auth.grantProviderToken({\n  provider_id: \"google\",\n  provider_redirect_uri: window.location.origin + window.location.pathname,\n  provider_code: code\n});\n\n// Step3：Useprovider_tokenLogin\nawait auth.signInWithProvider({\n  provider_token: provider_token\n});\n```\n\n**Full Example：**\n\n```vue\n<template>\n  <div>\n    <button v-if=\"!isCallback\" @click=\"startGoogleLogin\">GoogleLogin</button>\n    <p v-if=\"isCallback\">ProcessingGoogleLogin...</p>\n    <p v-if=\"message\" :style=\"{ color: message.includes(\"successful\") ? \"green\" : \"red\" }\">\n      {{ message }}\n    </p>\n  </div>\n</template>\n\n<script setup>\nimport { ref, onMounted } from \"vue\";\nimport { cloudbase } from \"./utils/cloudbase\";\n\nconst message = ref(\"\");\nconst isCallback = ref(false);\n\nonMounted(() => {\n  // CheckYesNoYesGoogleCallbackPage\n  const urlParams = new URLSearchParams(window.location.search);\n  const code = urlParams.get(\"code\");\n  const state = urlParams.get(\"state\");\n\n  if (code && state) {\n    isCallback.value = true;\n    handleGoogleCallback(code, state);\n  }\n});\n\n// Step1：Redirect toGoogleauthorization page\nconst startGoogleLogin = async () => {\n  try {\n    const auth = cloudbase.auth();\n    const state = Date.now().toString(); // Generate unique identifier to prevent CSRF attacks\n\n    // Save state locally for callback verification\n    localStorage.setItem(\"google_login_state\", state);\n\n    // GenerateGoogleauthorization URL\n    const { uri } = await auth.genProviderRedirectUri({\n      provider_id: \"google\", // Fixed value, representingGoogleOpen Platform\n      provider_redirect_uri: window.location.href, // Callback to current page after authorization\n      state: state,\n    });\n\n    // Redirect toGoogleauthorization page\n    window.location.href = uri;\n  } catch (error) {\n    message.value = \"Redirect failed：\" + error.message;\n  }\n};\n\n// Step2and3：ProcessGoogleCallbackandDoneLogin\nconst handleGoogleCallback = async (code, state) => {\n  try {\n    // Verify state matches to prevent CSRF attacks\n    const savedState = localStorage.getItem(\"google_login_state\");\n    if (savedState !== state) {\n      message.value = \"Login failed：State verification failed\";\n      return;\n    }\n\n    const auth = cloudbase.auth();\n\n    // Usecodeexchange forprovider_token\n    const { provider_token } = await auth.grantProviderToken({\n      provider_id: \"google\",\n      provider_redirect_uri: window.location.origin + window.location.pathname,\n      provider_code: code,\n    });\n\n    try {\n      // Try direct login\n      await auth.signInWithProvider({\n        provider_token: provider_token,\n      });\n\n      message.value = \"Login successful！\";\n\n      // Clear URL parameters and local storage\n      localStorage.removeItem(\"google_login_state\");\n      window.history.replaceState({}, document.title, window.location.pathname);\n\n    } catch (loginError) {\n      // IfYesfirst-timeGoogleLogin，needfirstRegisterandbindthe\n      if (loginError.error === \"not_found\") {\n        message.value = \"Detected first-timeGoogleLogin，Need to bindaccount...\";\n\n        // Here you need to guide the user to complete the registration process\n        // For example: collect phone verification code for registration\n        // After successful registration, call bindWithProvider bindtheGoogleidentity\n\n        // Example: Assuming an account registered via other methods, bindirect\n        await auth.bindWithProvider({\n          provider_token: provider_token,\n        });\n\n        // Re-login after successful bindng\n        await auth.signInWithProvider({\n          provider_token: provider_token,\n        });\n\n        message.value = \"bindand login successful！\";\n\n        // Clear URL parameters and local storage\n        localStorage.removeItem(\"google_login_state\");\n        window.history.replaceState({}, document.title, window.location.pathname);\n\n      } else {\n        throw loginError;\n      }\n    }\n  } catch (error) {\n    message.value = \"Login failed：\" + error.message;\n    localStorage.removeItem(\"google_login_state\");\n  }\n};\n</script>\n```",
                "index": 6,
                "id": "google",
                "title": "Google OAuth Login"
              }
            ]
          }
        ]
      }
    ],
    "_id": "e4bc589369a928710044b3a8766491dd",
    "_openid": "anon",
    "createdAt": 1769767040475,
    "updatedAt": 1769767040475
  },
  {
    "category": "Framework Integration,ORMs,Prisma",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 15,
    "hasTemplate": false,
    "docsUrl": "https://prisma.org.cn/docs/getting-started/prisma-orm/quickstart/mysql",
    "content": [
      {
        "docsUrl": "",
        "markdown": "Use `Prisma` operate **MySQL Database**\n\nAdd the following code to your **Prisma** project",
        "title": "Modify Environment Variables",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```\nDATABASE_URL=mysql://{%DATABASE_URL%}\n```",
            "index": 2,
            "id": "mysqlString",
            "title": ".env"
          },
          {
            "markdown": "```prisma\ngenerator client {\n  provider = \"prisma-client-js\"\n}\n\ndatasource db {\n  provider = \"mysql\"\n  url      = env(\"DATABASE_URL\")\n}\n```",
            "index": 1,
            "id": "",
            "title": "prisma/schema.prisma"
          }
        ]
      }
    ],
    "_id": "ed435bfa69a9286d0040bc6a2155dd36",
    "_openid": "anon",
    "createdAt": 1769744596500,
    "updatedAt": 1769766694387
  },
  {
    "category": "CloudBase MCP,OpenCode",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 106,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/opencode",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.opencode.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"OpenCode\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "ed435bfa69a928700040bc8a43cd9505",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "Framework Integration,ORMs,SQLAlchemy",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 16,
    "hasTemplate": false,
    "docsUrl": "https://docs.sqlalchemy.org/en/20/orm/quickstart.html",
    "content": [
      {
        "docsUrl": "",
        "markdown": "Use `SQLAlchemy` operate **MySQL Database**\n```bash\npip install sqlalchemy pymysql\n```",
        "title": "Install Dependencies",
        "type": "",
        "content": []
      },
      {
        "markdown": "Add the following code to your **SQLAlchemy** project",
        "title": "Usage Example",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```python\nimport os\nfrom sqlalchemy import create_engine, text\nfrom sqlalchemy.orm import sessionmaker\nfrom models import Base, Todo\n\ndef main():\n    engine = create_engine(os.getenv('DATABASE_URL'))\n\n    Session = sessionmaker(bind=engine)\n    with Session() as session:\n        todos = session.query(Todo).all()\n        print(f\"Found {len(todos)} todos\")\n\nif __name__ == '__main__':\n    main()\n```",
            "title": "main.py"
          },
          {
            "markdown": "```python\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.orm import declarative_base\n\nBase = declarative_base()\n\nclass Todo(Base):\n    __tablename__ = 'todos'\n\n    _id = Column(String(255), primary_key=True)\n    title = Column(String(255))\n```",
            "title": "models.py"
          },
          {
            "markdown": "```\nDATABASE_URL=mysql+pymysql://{%DATABASE_URL%}\n```",
            "id": "mysqlString",
            "title": ".env"
          }
        ]
      }
    ],
    "_id": "eda9bd8369a9286d004361430a73f46c",
    "_openid": "anon",
    "createdAt": 1769744597090,
    "updatedAt": 1769766695036
  },
  {
    "category": "CloudBase MCP,VSCode",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 115,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/github-copilot",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.vscode/mcp.json`:\n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"VSCode\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "eda9bd8369a9286f00436164625279b3",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Augment Code",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 107,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/augment-code",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.vscode/settings.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Augment\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "eda9bd8369a9286f0043616777c3d9a5",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Kiro",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 101,
    "hasTemplate": true,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/kiro",
    "content": [
      {
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration toprojectdirectory `.kiro/settings/mcp.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Kiro\"\n }\n }\n }\n}\n```",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "tab",
        "content": []
      }
    ],
    "_id": "eda9bd8369a928700043616d1f81ee88",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "Framework Integration,ORMs,SQLAlchemy",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 43,
    "hasTemplate": false,
    "docsUrl": "https://docs.sqlalchemy.org/en/20/orm/quickstart.html",
    "content": [
      {
        "docsUrl": "",
        "markdown": "Use `SQLAlchemy` operate **MySQL Database**\n```bash\npip install sqlalchemy pymysql\n```",
        "title": "Install Dependencies",
        "type": "",
        "content": []
      },
      {
        "markdown": "Add the following code to your **SQLAlchemy** project",
        "title": "Usage Example",
        "type": "codeTab",
        "content": [
          {
            "markdown": "```python\nimport os\nfrom sqlalchemy import create_engine, text\nfrom sqlalchemy.orm import sessionmaker\nfrom models import Base, Todo\n\ndef main():\n    engine = create_engine(os.getenv('DATABASE_URL'))\n\n    Session = sessionmaker(bind=engine)\n    with Session() as session:\n        todos = session.query(Todo).all()\n        print(f\"Found {len(todos)} todos\")\n\nif __name__ == '__main__':\n    main()\n```",
            "title": "main.py"
          },
          {
            "markdown": "```python\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.orm import declarative_base\n\nBase = declarative_base()\n\nclass Todo(Base):\n    __tablename__ = 'todos'\n\n    _id = Column(String(255), primary_key=True)\n    title = Column(String(255))\n```",
            "title": "models.py"
          },
          {
            "markdown": "```\nDATABASE_URL=mysql+pymysql://{%DATABASE_URL%}\n```",
            "id": "mysqlString",
            "title": ".env"
          }
        ]
      }
    ],
    "_id": "ee4af104697c28d50038907f554775d9",
    "_openid": "anon",
    "createdAt": 1769744597090,
    "updatedAt": 1769766695036
  },
  {
    "category": "Framework Integration,MiniProgram / MiniGame,MiniGame,Native API",
    "targetPlatform": [
      "default"
    ],
    "lang": "en",
    "index": 2,
    "hasTemplate": false,
    "docsUrl": "https://developers.weixin.qq.com/minigame/dev/wxcloud/",
    "content": [
      {
        "markdown": "in `game.js` InitializeCloudBase：",
        "index": 1,
        "title": "Initialize SDK",
        "type": "codeTab",
        "content": [
          {
            "markdown": "mostCloudBasecapabilities canUse `Mini GameNative API` directlyCall，NoneneedInstall SDK，If `NativeAPI` Not supported pleaseUse `Client SDK` performCall\n\n```js\nwx.cloud.init({\n  env: \"{%ENV_ID%}\"\n});\n```",
            "index": 1,
            "title": "NativeAPI Initialize",
            "content": []
          },
          {
            "markdown": "**Install**\n\nUse Client SDK before please firstInstall SDK\n\ninMini Game `package.json` theinDirectory（usuallygamerootDirectory）execute：\n\n```bash\nnpm i @cloudbase/wx-cloud-client-sdk --save\n```\n\nInstallDoneafter，inWeChatClick in developer tools **tool → Build npm**。\n\n**Initialize**\n\n```js\nconst { init } = require(\"@cloudbase/wx-cloud-client-sdk\");\n\nwx.cloud.init({\n  env: \"{%ENV_ID%}\"\n});\n\nconst cloudbase = init(wx.cloud);\n```",
            "index": 2,
            "title": "Client SDK Initialize",
            "content": []
          }
        ]
      },
      {
        "sideTabs": [
          {
            "id": "pg-db",
            "title": "PostgreSQL Database"
          }
        ],
        "index": 2,
        "title": "Using CloudBase Capabilities",
        "type": "codeTab",
        "content": [
          {
            "index": 1,
            "id": "pg-db",
            "title": "PostgreSQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\n// Query {%TABLE_NAME%} table (limit 10 records)\nconst { data, error } = await wx.cloud.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n\nconsole.log(\"Query result:\", data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\n// Insert a record into {%TABLE_NAME%} table\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await wx.cloud.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .insert({ title: \"New Post\", status: \"draft\" })\n  .select();\n\nconsole.log(\"Insert result:\", data);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\n// Update record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await wx.cloud.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({ status: \"published\" })\n  .eq(\"id\", 1)\n  .select();\n\nconsole.log(\"Update result:\", data);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\n// Upsert: update on conflict, otherwise insert\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await wx.cloud.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Post Title\", status: \"published\" }, { onConflict: \"id\" })\n  .select();\n\nconsole.log(\"Upsert result:\", data);\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```js\n// Delete record by id in {%TABLE_NAME%}\n// Note: anon token has read-only access; write ops require auth or RLS write policy\nconst { data, error } = await wx.cloud.rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", 1);\n\nconsole.log(\"Delete completed:\", error);\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "pleaseUse `Client SDK` performCall",
            "index": 1,
            "id": "mysql-db",
            "title": "MySQL Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\n// Query {%TABLE_NAME%} table first 10 records\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .select(\"*\")\n  .limit(10);\n\nconsole.log(\"QueryResult:\", data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\n// Add {%TABLE_NAME%} table data\nconst { data, error } = await cloudbase.rdb().from(\"{%TABLE_NAME%}\").insert({\n  title: \"Example Title\"\n});\n\nconsole.log(\"AddResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\n// Update {%TABLE_NAME%} table id as <DataID> Data\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .update({\n    title: \"UpdateafterTitle\"\n  })\n  .eq(\"id\", \"<DataID>\");\n\nconsole.log(\"UpdateResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\n// If {%TABLE_NAME%} tableexists id as 1 record then update title as\"Example Title\"，does not existotherwise insert new record\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .upsert({ id: 1, title: \"Example Title\" });\n\nconsole.log(\"AddUpdateResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 4,
                "title": "Upsert Data"
              },
              {
                "markdown": "```js\n// Delete {%TABLE_NAME%} table id as <DataID> Data\nconst { data, error } = await cloudbase\n  .rdb()\n  .from(\"{%TABLE_NAME%}\")\n  .delete()\n  .eq(\"id\", \"<DataID>\");\n\nconsole.log(\"DeleteResult:\", error ? \"failed\" : \"successful\");\n```",
                "index": 5,
                "title": "Delete Data"
              }
            ]
          },
          {
            "index": 2,
            "id": "doc-db",
            "title": "Document Database",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Query {%TABLE_NAME%} table first 10 records\nconst res = await db.collection(\"{%TABLE_NAME%}\").limit(10).get();\n\nconsole.log(res.data);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Add {%TABLE_NAME%} table data\nconst res = await db.collection(\"{%TABLE_NAME%}\").add({\n  data: {\n    title: \"Example Title\",\n    content: \"ExampleContent\"\n  }\n});\n\nconsole.log(res);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Update {%TABLE_NAME%} table id as <DataID> Data\nconst res = await db\n  .collection(\"{%TABLE_NAME%}\")\n  .doc(\"<DataID>\")\n  .update({\n    data: {\n      title: \"UpdateafterTitle\"\n    }\n  });\n\nconsole.log(res.stats.updated);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\nconst db = wx.cloud.database();\n\n// Delete {%TABLE_NAME%} table id as <DataID> Data\nconst res = await db.collection(\"{%TABLE_NAME%}\").doc(\"<DataID>\").remove();\n\nconsole.log(res.stats.removed);\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "pleaseUse `Client SDK` performCall",
            "index": 3,
            "id": "data-model",
            "title": "Data Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\n// Query {%TABLE_NAME%} Data Modelbefore10recordsData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].list({\n  pageNumber: 1,\n  pagesize: 10\n});\n\nconsole.log(res.data.records);\n```",
                "index": 1,
                "title": "Query Data"
              },
              {
                "markdown": "```js\n// Add {%TABLE_NAME%} Data ModelData\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].create({\n  data: {\n    title: \"Example Title\",\n    content: \"ExampleContent\"\n  }\n});\n\nconsole.log(res.data);\n```",
                "index": 2,
                "title": "Insert Data"
              },
              {
                "markdown": "```js\n// Update {%TABLE_NAME%} Data Model _id as <DataID> Data\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].update({\n  data: {\n    title: \"UpdateafterTitle\"\n  },\n  filter: {\n    where: {\n      _id: {\n        $eq: \"<DataID>\"\n      }\n    }\n  }\n});\n\nconsole.log(res.data);\n```",
                "index": 3,
                "title": "Update Data"
              },
              {
                "markdown": "```js\n// Delete {%TABLE_NAME%} Data Model _id as <DataID> Data\nconst res = await cloudbase.models[\"{%TABLE_NAME%}\"].delete({\n  filter: {\n    where: {\n      _id: {\n        $eq: \"<DataID>\"\n      }\n    }\n  }\n});\n\nconsole.log(res.data);\n```",
                "index": 4,
                "title": "Delete Data"
              }
            ]
          },
          {
            "markdown": "```js\n// Call {%FUNCTION_NAME%} Cloud Function\nconst res = await wx.cloud.callFunction({\n  name: \"{%FUNCTION_NAME%}\",\n  data: {} // Cloud Functioninput parameters\n});\n\nconsole.log(res.result);\n```",
            "index": 4,
            "id": "scf",
            "title": "Cloud Function",
            "content": []
          },
          {
            "index": 5,
            "id": "storage",
            "title": "Cloud Storage",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\n// Mini GamecanUse canvas Generate ImageorUseother methodsGetfilePath\nconst filePath = \"localfilePath\"; // for exampleUse canvas.toTempFilePath Get\n\nconst res = await wx.cloud.uploadFile({\n  cloudPath: \"images/\" + Date.now() + \".png\", // Path to upload in cloud\n  filePath: filePath // Mini GametemporaryfilePath\n});\n\nconsole.log(res.fileID);\n```",
                "index": 1,
                "title": "Upload File"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.getTempFileURL({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\n\nconsole.log(res.fileList);\n// fileListExample\n// [{\n//    fileID: \"cloud://xxx.png\", // file ID\n//    tempFileURL: \"https://xxx.png\", // temporaryfilenetworkURL\n//    maxAge: 120 * 60 * 1000, // Validperiod\n// }]\n```",
                "index": 2,
                "title": "Get File URL"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.downloadFile({\n  fileID: \"cloud://xxx.png\" // File fileID\n});\n\nconsole.log(res.tempFilePath); // ReturntemporaryfilePath\n```",
                "index": 3,
                "title": "Download File"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.deleteFile({\n  fileList: [\"cloud://xxx.png\"] // File fileID list\n});\n\nconsole.log(res.fileList);\n```",
                "index": 4,
                "title": "Delete File"
              }
            ]
          },
          {
            "index": 6,
            "id": "ai-model",
            "title": "AI Model",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst res = await wx.cloud.extend.AI.createModel(\n  \"{%AI_MODEL_NAME%}\"\n).streamText({\n  data: {\n    model: \"{%AI_SUB_MODEL_NAME%}\",\n    messages: [\n      {\n        role: \"user\",\n        content: \"Hello\"\n      }\n    ]\n  }\n});\n\nfor await (let event of res.eventStream) {\n  if (event.data === \"[DONE]\") {\n    break;\n  }\n  const data = JSON.parse(event.data);\n\n  // WhenUse deepseek-r1 when，model willGeneratereasoning chainContent\n  const think = data?.choices?.[0]?.delta?.reasoning_content;\n  if (think) {\n    console.log(think);\n  }\n\n  // Print generated text content\n  const text = data?.choices?.[0]?.delta?.content;\n  if (text) {\n    console.log(text);\n  }\n}\n```",
                "index": 1,
                "id": "text-aiModel",
                "title": "Text Generation"
              },
              {
                "markdown": "Image generation is implemented via cloud functions. Click \"One-click Create Cloud Function\" on the image generation page. Function call example:：\n\n```js\n// CallCloud FunctionGenerate Image\nwx.cloud.callFunction({\n  name: \"<YOUR_FUNCTION_NAME>\",\n  data: {\n    prompt: \"A cute cat playing in the sunshine\"\n  },\n  success: res => {\n    const result = res.result;\n    if (result.success) {\n      console.log(\"Image URL:\", result.imageUrl);\n      console.log(\"Optimized prompt:\", result.revised_prompt);\n      console.log(\"Note: Image URLValidis valid for24hours\");\n      \n      // inMini GamecanUseImage URLperformaftersubsequentProcess\n      // for exampleLoadtoSpriteorCanvas\n    } else {\n      console.error(\"Generation failed:\", result.code, result.message);\n    }\n  },\n  fail: err => {\n    console.error(\"Call failed:\", err);\n  }\n});\n```",
                "index": 2,
                "id": "image-aiModel",
                "title": "Image Generation"
              }
            ]
          },
          {
            "markdown": "",
            "index": 7,
            "id": "agent",
            "title": "Agent",
            "type": "sideTab",
            "content": [
              {
                "markdown": "```js\nconst res = await wx.cloud.extend.AI.bot.sendMessage({\n  data: {\n    botId: '{%AGENT_ID%}',\n    // Refer to frontend-backend communication protocol for input structure：\n    //  https://docs.cloudbase.net/ai/agent/http-agent-protocol\n    threadId: '550e8400-e29b-41d4-a716-446655440000',\n    runId: 'run_001',\n    messages: [{ id: 'msg-1', role: 'user', content: 'Hello' }],\n    tools: [],\n    context: [],\n    state: {},\n    forwardedProps: {},\n  },\n});\n\nfor await (const event of res.eventStream) {\n  if (event.data === '[DONE]') {\n    break;\n  }\n  const data = JSON.parse(event.data);\n\n  // WhenUse deepseek-r1 when，model willGeneratereasoning chainContent\n  const think = data.reasoning_content;\n  if (think) {\n    console.log(think);\n  }\n\n  // Print output content\n  const content = data.content;\n  if (content) {\n    console.log(content);\n  }\n}\n```",
                "index": 0,
                "id": "scf",
                "title": "Function Type"
              },
              {
                "markdown": "```js\nconst res = await wx.cloud.extend.AI.bot.sendMessage({\n  data: {\n    botId: \"{%AGENT_ID%}\",\n    msg: \"Hello\"\n  }\n});\n\nfor await (const event of res.eventStream) {\n  if (event.data === \"[DONE]\") {\n    break;\n  }\n  const data = JSON.parse(event.data);\n\n  // WhenUse deepseek-r1 when，model willGeneratereasoning chainContent\n  const think = data.reasoning_content;\n  if (think) {\n    console.log(think);\n  }\n\n  // Print output content\n  const content = data.content;\n  if (content) {\n    console.log(content);\n  }\n}\n```",
                "index": 1,
                "id": "baas",
                "title": "Standard Type"
              }
            ]
          }
        ]
      }
    ],
    "_id": "ee4af104697c809b0042d6e1007a3376",
    "_openid": "anon",
    "createdAt": 1769767067406,
    "updatedAt": 1775130863197
  },
  {
    "category": "CloudBase MCP,Qoder",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 105,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/qoder",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `Qoder Settings > MCP`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Qorder\"\n }\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "fb39ee6269a928700043fb8c375999ba",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  },
  {
    "category": "CloudBase MCP,Cline",
    "targetPlatform": [
      "intl"
    ],
    "lang": "en",
    "index": 102,
    "hasTemplate": false,
    "docsUrl": "https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/ide-setup/cline",
    "content": [
      {
        "docsUrl": "",
        "markdown": "",
        "title": "Installation",
        "type": "list",
        "content": [
          {
            "markdown": "Add the following configuration to `.cline/mcp.json`: \n```json\n{\n \"mcpServers\": {\n \"cloudbase\": {\n \"autoApprove\": [],\n \"timeout\": 60,\n \"command\": \"npx\",\n \"args\": [\"@cloudbase/cloudbase-mcp@latest\"],\n \"env\": {\n \"INTEGRATION_IDE\": \"Cline\"\n },\n \"transportType\": \"stdio\",\n \"disabled\": false\n }\n }\n}\n```\n",
            "title": "Manual Configuration"
          }
        ]
      },
      {
        "markdown": "After configuration is complete, you can operate CloudBase resources in AI conversations. Click [MCP Tools](https://docs.cloudbase.net/ai/cloudbase-ai-toolkit/mcp-tools) to view the complete list of features provided by the tools\n\n``` \nHelp me connect CloudBase: open https://docs.cloudbase.net/skill.md, follow the instructions to complete the setup, then let me know and suggest the most relevant next step.\n```\n``` \nHelp me create a todo app using CloudBase Skills, with document database for data storage\n```",
        "title": "Chat with AI",
        "type": "",
        "content": []
      }
    ],
    "_id": "fb39ee6269a928700043fb9006234d2c",
    "_openid": "1524963278340493312",
    "createdAt": 1769745940590,
    "updatedAt": 1769745940590
  }
]
