0% found this document useful (0 votes)
93 views11 pages

CozeSDK_Guide

Uploaded by

theodore bai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views11 pages

CozeSDK_Guide

Uploaded by

theodore bai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 11

# Coze Python API SDK

Welcome to the **Coze Python API SDK**! This SDK provides a seamless way to
integrate with the Coze platform, enabling you to leverage various functionalities
such as chat, bot management, conversations, file handling, workflows, and
knowledge management within your Python applications.

## Table of Contents

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Getting Started](#getting-started)
- [Authentication](#authentication)
- [Personal Auth Token](#personal-auth-token)
- [JWT OAuth App](#jwt-oauth-app)
- [Initializing the Coze Client](#initializing-the-coze-client)
- [Usage](#usage)
- [Chat](#chat)
- [Bots](#bots)
- [Conversations](#conversations)
- [Files](#files)
- [Workflows](#workflows)
- [Knowledge](#knowledge)
- [OAuth Apps](#oauth-apps)
- [Web OAuth App](#web-oauth-app)
- [JWT OAuth App](#jwt-oauth-app-1)
- [PKCE OAuth App](#pkce-oauth-app)
- [Device OAuth App](#device-oauth-app)
- [Asynchronous Usage](#asynchronous-usage)
- [Streaming Usage](#streaming-usage)
- [Examples](#examples)
- [Support](#support)
- [Contributing](#contributing)
- [License](#license)

## Features

- **Authentication:** Supports multiple authentication methods including Personal


Auth Tokens and various OAuth flows.
- **Chat Management:** Create and manage chat sessions with both streaming and non-
streaming capabilities.
- **Bot Management:** Retrieve, list, create, update, and delete bots.
- **Conversation Handling:** Manage conversations and messages seamlessly.
- **File Operations:** Upload and retrieve file information.
- **Workflow Management:** Execute and monitor workflows with streaming support.
- **Knowledge Management:** Create, update, delete, and list knowledge documents.
- **Asynchronous Operations:** Utilize asynchronous calls for improved performance.
- **Streaming Support:** Real-time streaming for chat and workflow events.

## Requirements

- **Python Version:** 3.7 or higher

## Installation

Install the Coze Python SDK using `pip`:

```shell
pip install cozepy
```

## Getting Started

### Authentication

Before interacting with the Coze API, you need to authenticate your client. The SDK
supports multiple authentication methods:

#### Personal Auth Token

Generate a Personal Auth Token from either [扣


子](https://www.coze.cn/open/oauth/pats) or the [Coze
Platform](https://www.coze.com/open/oauth/pats).

#### JWT OAuth App

Create a JWT OAuth App via [扣子](https://www.coze.cn/open/oauth/apps) or the [Coze


Platform](https://www.coze.com/open/oauth/apps).

### Initializing the Coze Client

Initialize the Coze client using your chosen authentication method.

#### Using Personal Auth Token

```python
from cozepy import Coze, TokenAuth

# Replace 'your_token' with your actual Personal Auth Token


coze = Coze(auth=TokenAuth("your_token"))
```

#### Using JWT OAuth App

```python
from cozepy import Coze, JWTAuth

# Replace with your actual client ID, private key, and key ID
coze = Coze(auth=JWTAuth("your_client_id", "your_private_key", "your_key_id"))
```

## Usage

### Chat

Interact with the chat functionality to create and manage chat sessions.

#### Non-Streaming Chat

```python
import time
from cozepy import Coze, TokenAuth, ChatStatus, Message

# Initialize Coze client


coze = Coze(auth=TokenAuth("your_token"))

# Create a chat session


chat = coze.chat.create(
bot_id='bot_id',
user_id='user_id',
additional_messages=[
Message.user_text_message('How are you?'),
Message.assistant_text_message('I am fine, thank you.')
],
)

# Monitor chat status


start_time = int(time.time())
while chat.status == ChatStatus.IN_PROGRESS:
if int(time.time()) - start_time > 120:
# Cancel chat if it takes too long
coze.chat.cancel(conversation_id=chat.conversation_id,
chat_id=chat.chat_id)
break

time.sleep(1)
chat = coze.chat.retrieve(conversation_id=chat.conversation_id,
chat_id=chat.chat_id)

# Retrieve and print messages


messages = coze.chat.messages.list(conversation_id=chat.conversation_id,
chat_id=chat.chat_id)
for msg in messages:
print('Received message:', msg.content)
```

#### Streaming Chat

```python
from cozepy import Coze, TokenAuth, ChatEventType, Message

# Initialize Coze client


coze = Coze(auth=TokenAuth("your_token"))

# Start streaming chat


stream = coze.chat.stream(
bot_id='bot_id',
user_id='user_id',
additional_messages=[
Message.user_text_message('How are you?'),
Message.assistant_text_message('I am fine, thank you.')
],
)

# Handle streaming events


for event in stream:
if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
print('Received message delta:', event.message.content)
```

### Bots

Manage bots by retrieving, listing, creating, updating, and deleting them.

```python
from cozepy import Coze, TokenAuth
# Initialize Coze client
coze = Coze(auth=TokenAuth("your_token"))

# Retrieve bot information


bot = coze.bots.retrieve(bot_id='bot_id')

# List bots in a specific space


bots_page = coze.bots.list(space_id='space_id', page_num=1)
bots = bots_page.items

# Create a new bot


new_bot = coze.bots.create(
space_id='space_id',
name='Bot Name',
description='Bot Description',
)

# Update existing bot information


coze.bots.update(
bot_id='bot_id',
name='Updated Bot Name',
description='Updated Bot Description',
)

# Publish (delete) a bot


coze.bots.publish(bot_id='bot_id')
```

### Conversations

Handle conversations by creating, retrieving, updating, deleting, and listing


messages.

```python
from cozepy import Coze, TokenAuth, Message, MessageContentType

# Initialize Coze client


coze = Coze(auth=TokenAuth("your_token"))

# Create a new conversation


conversation = coze.conversations.create(
messages=[
Message.user_text_message('How are you?'),
Message.assistant_text_message('I am fine, thank you.')
],
)

# Retrieve conversation details


conversation = coze.conversations.retrieve(conversation_id=conversation.id)

# Create a new message in the conversation


message = coze.conversations.messages.create(
conversation_id=conversation.id,
content='How are you?',
content_type=MessageContentType.TEXT,
)

# Retrieve a specific message


message = coze.conversations.messages.retrieve(conversation_id=conversation.id,
message_id=message.id)

# Update a message's content


coze.conversations.messages.update(
conversation_id=conversation.id,
message_id=message.id,
content='Hey, how are you?',
content_type=MessageContentType.TEXT,
)

# Delete a message
coze.conversations.messages.delete(conversation_id=conversation.id,
message_id=message.id)

# List all messages in the conversation


message_list = coze.conversations.messages.list(conversation_id=conversation.id)
```

### Files

Upload and retrieve file information using the Files module.

```python
from cozepy import Coze, TokenAuth

# Initialize Coze client


coze = Coze(auth=TokenAuth("your_token"))

# Upload a file
uploaded_file = coze.files.upload(file='/path/to/your/file')

# Retrieve file information


file_info = coze.files.retrieve(file_id=uploaded_file.id)
```

### Workflows

Execute and monitor workflows with both streaming and non-streaming options.

#### Non-Streaming Workflow Run

```python
from cozepy import Coze, TokenAuth

# Initialize Coze client


coze = Coze(auth=TokenAuth("your_token"))

# Create a workflow run


result = coze.workflows.runs.create(
workflow_id='workflow_id',
parameters={
'input_key': 'input_value',
}
)
```

#### Streaming Workflow Run


```python
from cozepy import Coze, TokenAuth, Stream, WorkflowEvent, WorkflowEventType

# Initialize Coze client


coze = Coze(auth=TokenAuth("your_token"))

def handle_workflow_stream(stream: Stream[WorkflowEvent]):


for event in stream:
if event.event == WorkflowEventType.MESSAGE:
print('Received message:', event.message)
elif event.event == WorkflowEventType.ERROR:
print('Received error:', event.error)
elif event.event == WorkflowEventType.INTERRUPT:
# Resume workflow upon interruption
resumed_stream = coze.workflows.runs.resume(
workflow_id='workflow_id',
event_id=event.interrupt.interrupt_data.event_id,
resume_data='resume_data',
interrupt_type=event.interrupt.interrupt_data.type,
)
handle_workflow_stream(resumed_stream)

# Start streaming the workflow run


stream = coze.workflows.runs.stream(
workflow_id='workflow_id',
parameters={
'input_key': 'input_value',
}
)

handle_workflow_stream(stream)
```

### Knowledge

Manage knowledge documents by creating, updating, deleting, and listing them.

```python
from cozepy import Coze, TokenAuth, DocumentBase, DocumentSourceInfo,
DocumentChunkStrategy, DocumentUpdateRule

# Initialize Coze client


coze = Coze(auth=TokenAuth("your_token"))

# Create knowledge documents from a local file


documents = coze.knowledge.documents.create(
dataset_id='dataset_id',
document_bases=[
DocumentBase(
name='Document Name',
source_info=DocumentSourceInfo.from_local_file('path/to/local/file')
)
],
chunk_strategy=DocumentChunkStrategy.auto()
)

# Create knowledge documents from a web page


documents = coze.knowledge.documents.create(
dataset_id='dataset_id',
document_bases=[
DocumentBase(
name='Document Name',
source_info=DocumentSourceInfo.from_web_page('https://example.com')
)
],
chunk_strategy=DocumentChunkStrategy.auto()
)

# Update a knowledge document


coze.knowledge.documents.update(
document_id='document_id',
document_name='Updated Document Name',
update_rule=DocumentUpdateRule.no_auto_update()
)

# Delete a knowledge document


coze.knowledge.documents.delete(document_ids=['document_id'])

# List knowledge documents


paged_documents = coze.knowledge.documents.list(
dataset_id='dataset_id',
page_num=1,
page_size=10
)
```

### OAuth Apps

Coze SDK supports various OAuth flows for authentication. Below are examples of
different OAuth App types.

#### Web OAuth App

Implement OAuth 2.0 Web Authorization Flow.

```python
from cozepy import Coze, TokenAuth, WebOAuthApp

# Initialize Web OAuth App with your credentials


web_oauth_app = WebOAuthApp(
client_id='your_client_id',
client_secret='your_client_secret',
)

# Generate the OAuth URL


oauth_url = web_oauth_app.get_oauth_url(redirect_uri='http://127.0.0.1:8080',
state='unique_state')

print("Open this URL in your browser to authorize:", oauth_url)

# After user authorization, capture the 'code' from the redirect URI
code = 'authorization_code_received'

# Exchange the code for an access token


oauth_token = web_oauth_app.get_access_token(redirect_uri='http://127.0.0.1:8080',
code=code)

# Initialize Coze client with the obtained access token


coze = Coze(auth=TokenAuth(oauth_token.access_token))

# Refresh the access token when expired


oauth_token = web_oauth_app.refresh_access_token(oauth_token.refresh_token)
```

#### JWT OAuth App

Use JWT for server-to-server authentication without user interaction.

```python
from cozepy import Coze, TokenAuth, JWTOAuthApp

# Initialize JWT OAuth App with your credentials


jwt_oauth_app = JWTOAuthApp(
client_id='your_client_id',
private_key='your_private_key',
public_key_id='your_public_key_id'
)

# Obtain an access token using JWT


oauth_token = jwt_oauth_app.get_access_token(ttl=3600)

# Initialize Coze client with the access token


coze = Coze(auth=TokenAuth(oauth_token.access_token))

# Note: JWT OAuth does not support token refresh. Obtain a new token when needed.
```

#### PKCE OAuth App

Implement OAuth 2.0 with Proof Key for Code Exchange (PKCE) for enhanced security.

```python
from cozepy import Coze, TokenAuth, PKCEOAuthApp

# Initialize PKCE OAuth App with your client ID


pkce_oauth_app = PKCEOAuthApp(
client_id='your_client_id',
)

# Generate a code verifier


code_verifier = 'unique_code_verifier'

# Generate the OAuth URL with PKCE parameters


oauth_url = pkce_oauth_app.get_oauth_url(
redirect_uri='http://127.0.0.1:8080',
state='unique_state',
code_verifier=code_verifier
)

print("Open this URL in your browser to authorize:", oauth_url)

# After user authorization, capture the 'code' from the redirect URI
code = 'authorization_code_received'

# Exchange the code and verifier for an access token


oauth_token = pkce_oauth_app.get_access_token(
redirect_uri='http://127.0.0.1:8080',
code=code,
code_verifier=code_verifier
)

# Initialize Coze client with the access token


coze = Coze(auth=TokenAuth(oauth_token.access_token))

# Refresh the access token when expired


oauth_token = pkce_oauth_app.refresh_access_token(oauth_token.refresh_token)
```

#### Device OAuth App

Use OAuth 2.0 Device Authorization Grant for devices with limited input
capabilities.

```python
from cozepy import Coze, TokenAuth, DeviceOAuthApp

# Initialize Device OAuth App with your client ID


device_oauth_app = DeviceOAuthApp(
client_id='your_client_id',
)

# Request a device code for the device flow


device_code = device_oauth_app.get_device_code()

print("Visit the following URL to authorize:", device_code.verification_url)


print("Enter the user code:", device_code.user_code)

# Poll for the access token after user authorization


oauth_token = device_oauth_app.get_access_token(device_code.device_code, poll=True)

# Initialize Coze client with the access token


coze = Coze(auth=TokenAuth(oauth_token.access_token))

# Refresh the access token when expired


oauth_token = device_oauth_app.refresh_access_token(oauth_token.refresh_token)
```

## Asynchronous Usage

The `cozepy` SDK supports asynchronous operations using `httpx.AsyncClient`.


Replace the `Coze` client with `AsyncCoze` to utilize asynchronous calls.

```python
import asyncio
from cozepy import TokenAuth, Message, AsyncCoze

# Initialize AsyncCoze client


coze = AsyncCoze(auth=TokenAuth("your_token"))

async def main():


# Create a chat session asynchronously
chat = await coze.chat.create(
bot_id='bot_id',
user_id='user_id',
additional_messages=[
Message.user_text_message('How are you?'),
Message.assistant_text_message('I am fine, thank you.')
],
)
print('Chat created:', chat)

# Run the asynchronous main function


asyncio.run(main())
```

## Streaming Usage

Coze SDK supports real-time streaming for chat and workflow runs, allowing you to
handle events as they occur.

### Chat Streaming Example

```python
from cozepy import Coze, TokenAuth, ChatEventType, Message

# Initialize Coze client


coze = Coze(auth=TokenAuth("your_token"))

# Start streaming chat


stream = coze.chat.stream(
bot_id='bot_id',
user_id='user_id',
additional_messages=[
Message.user_text_message('How are you?'),
Message.assistant_text_message('I am fine, thank you.')
],
)

# Handle streaming events


for event in stream:
if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
print('Received message delta:', event.message.content)
```

### Workflow Streaming Example

```python
from cozepy import Coze, TokenAuth, Stream, WorkflowEvent, WorkflowEventType

# Initialize Coze client


coze = Coze(auth=TokenAuth("your_token"))

def handle_workflow_stream(stream: Stream[WorkflowEvent]):


for event in stream:
if event.event == WorkflowEventType.MESSAGE:
print('Received message:', event.message)
elif event.event == WorkflowEventType.ERROR:
print('Received error:', event.error)
elif event.event == WorkflowEventType.INTERRUPT:
# Resume workflow upon interruption
resumed_stream = coze.workflows.runs.resume(
workflow_id='workflow_id',
event_id=event.interrupt.interrupt_data.event_id,
resume_data='resume_data',
interrupt_type=event.interrupt.interrupt_data.type,
)
handle_workflow_stream(resumed_stream)

# Start streaming the workflow run


stream = coze.workflows.runs.stream(
workflow_id='workflow_id',
parameters={
'input_key': 'input_value',
}
)

handle_workflow_stream(stream)
```

### Asynchronous Streaming Example

```python
import asyncio
from cozepy import TokenAuth, ChatEventType, Message, AsyncCoze

# Initialize AsyncCoze client


coze = AsyncCoze(auth=TokenAuth("your_token"))

async def main():


# Start streaming chat asynchronously
stream = await coze.chat.stream(
bot_id='bot_id',
user_id='user_id',
additional_messages=[
Message.user_text_message('How are you?'),
Message.assistant_text_message('I am fine, thank you.')
],
)
async for event in stream:
if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
print('Received message delta:', event.message.content)

# Run the asynchronous main function


asyncio.run(main())
```

---

*Note: Replace placeholders like `'your_token'`, `'bot_id'`, `'user_id'`,


`'workflow_id'`, etc., with your actual credentials and identifiers.*

You might also like