Skip to content

Latest commit

 

History

History
 
 

coze-taro

Taro Coze API SDK

English | 简体中文

License: MIT

Official Taro SDK for Coze(or 扣子) API platform.

Quick Start

1. Installation

npm install @coze/taro-api @coze/api
# or
pnpm install @coze/taro-api @coze/api

2. Basic Usage

import { COZE_COM_BASE_URL, RoleType, ChatStatus } from '@coze/api';
import { CozeAPI } from '@coze/taro-api';

// Initialize client with your Personal Access Token
const client = new CozeAPI({
  token: 'your_pat_token', // Get your PAT from https://www.coze.com/open/oauth/pats
  baseURL: COZE_COM_BASE_URL,
});

// Simple chat example
async function quickChat() {
  try {
    const v = await client.chat.createAndPoll({
      bot_id: 'your_bot_id',
      additional_messages: [
        {
          role: RoleType.User,
          content: 'Hello!',
          content_type: 'text',
        },
      ],
    });

    if (v.chat.status === ChatStatus.COMPLETED) {
      for (const item of v.messages) {
        console.log('[%s]:[%s]:%s', item.role, item.type, item.content);
      }
      console.log('usage', v.chat.usage);
    }
  } catch (error) {
    console.error('Chat error:', error);
    throw error;
  }
}

Key Features

  • 🌐 Consistent API: Maintains consistent API with Coze-JS
  • 🔄 Streaming Support: Compatible with ByteDance Mini Program/WeChat Mini Program/H5

Advanced Usage

Streaming Chat

import { ChatEventType } from '@coze/api';
import { CozeAPI } from '@coze/taro-api';

async function streamChat() {
  const stream = await client.chat.stream({
    bot_id: 'your_bot_id',
    additional_messages: [
      {
        role: RoleType.User,
        content: 'Hello!',
        content_type: 'text',
      },
    ],
  });

  for await (const part of stream) {
    if (part.event === ChatEventType.CONVERSATION_MESSAGE_DELTA) {
      console.log(part.data.content); // Real-time response
    }
  }
}

Refresh token

import { COZE_COM_BASE_URL } from '@coze/api';
import { CozeAPI } from '@coze/taro-api';

const client = new CozeAPI({
  token: 'your_pat_token', // https://www.coze.com/open/oauth/pats
  baseURL: COZE_COM_BASE_URL,
  onBeforeAPICall: () => {
    return { token: 'your_new_pat_token' };
  },
});

Abort streaming chat

import { ChatEventType } from '@coze/api';
import { CozeAPI, AbortController } from '@coze/taro-api';

async function streamChat() {
  const controller = new AbortController();
  setTimeout(() => {
    controller.abort();
  }, 10);

  const stream = await client.chat.stream({
    bot_id: 'your_bot_id',
    additional_messages: [
      {
        role: RoleType.User,
        content: 'Hello!',
        content_type: 'text',
      },
    ],
  }, {
    signal: controller.signal,
  });

  for await (const part of stream) {
    if (part.event === ChatEventType.CONVERSATION_MESSAGE_DELTA) {
      console.log(part.data.content); // Real-time response
    }
  }
}

Try Examples

cd examples/coze-js-taro
cp .env.development .env.local # Edit .env.local with your credentials
npm run dev:weapp

Notes

Taro@3 + React

The following configuration is required:

export default defineConfig(() => {
  compiler: {
    type: 'webpack5',
    prebundle: {
      // 1. Don‘t prebundle '@coze/taro-api'
      exclude: ['@coze/taro-api'],
    },
  },

  mini: {
    webpackChain(chain) {
      // 2. Enable multi-platform support for '@coze/taro-api'
      chain.resolve.plugin('MultiPlatformPlugin').tap(args => {
        args[2]['include'] = ['@coze/taro-api'];
        return args;
      });
    },
  },

  h5: {
    webpackChain(chain) {
      // 2. Enable multi-platform support for '@coze/taro-api'
      chain.resolve.plugin('MultiPlatformPlugin').tap(args => {
        args[2]['include'] = ['@coze/taro-api'];
        return args;
      });
    },
  }
});

Documentation

For detailed API documentation and guides, visit: