PHPackages                             sungithubid/coze-php-sdk - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [API Development](/categories/api)
4. /
5. sungithubid/coze-php-sdk

ActiveLibrary[API Development](/categories/api)

sungithubid/coze-php-sdk
========================

The PHP SDK for the Coze API

0.0.5(4mo ago)03MITPHPPHP &gt;=7.4

Since Jan 16Pushed 4mo agoCompare

[ Source](https://github.com/sungithubid/coze-php-sdk)[ Packagist](https://packagist.org/packages/sungithubid/coze-php-sdk)[ Docs](https://github.com/sungithubid/coze-php-sdk)[ RSS](/packages/sungithubid-coze-php-sdk/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (3)Versions (7)Used By (0)

Coze PHP SDK
============

[](#coze-php-sdk)

[![License: MIT](https://camo.githubusercontent.com/fdf2982b9f5d7489dcf44570e714e3a15fce6253e0cc6b5aa61a075aac2ff71b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d79656c6c6f772e737667)](https://opensource.org/licenses/MIT)[![PHP Version](https://camo.githubusercontent.com/291fb48c27888cb58d3daa496237532ea2d0bdd51a933f0a7a4262e9d87b7304/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344372e342d3838393242462e737667)](https://www.php.net/)

> ⚠️ **Note:** This is an unofficial third-party PHP SDK. Currently, only the commonly used **Chat** and **Datasets** APIs are implemented. Other APIs will be added gradually.

A PHP SDK for the Coze API. This SDK provides a convenient way to integrate Coze's AI capabilities into your PHP applications.

Features
--------

[](#features)

- 🚀 PHP SDK for the Coze API
- 🔐 Personal Access Token (PAT) authentication
- 📡 Both streaming and non-streaming chat support
- 🔄 Automatic polling for chat completion
- ⚡ Built on GuzzleHttp for reliable HTTP requests
- 📦 PSR-4 autoloading, ready for Packagist
- 🎯 PHP Generator pattern (`yield $event`) for memory-efficient streaming

Requirements
------------

[](#requirements)

- PHP 7.4 or higher
- Composer
- GuzzleHttp 7.0+

Installation
------------

[](#installation)

```
composer require sungithubid/coze-php-sdk
```

Or add to your `composer.json`:

```
{
    "require": {
        "sungithubid/coze-php-sdk": "^1.0"
    }
}
```

Quick Start
-----------

[](#quick-start)

### Initialize the Client

[](#initialize-the-client)

```
use Coze\CozeClient;
use Coze\Auth\TokenAuth;

$client = new CozeClient(
    new TokenAuth('your_access_token'),
    CozeClient::BASE_URL_CN  // or CozeClient::BASE_URL_COM for global
);
```

### Chat Examples

[](#chat-examples)

ExampleMethodDescription[chat\_stream.php](./examples/chat_stream.php)`$client->chat->stream()`Streaming chat using PHP Generator (`yield`), memory-efficient for large responses[chat\_no\_stream.php](./examples/chat_no_stream.php)`$client->chat->create()`Non-streaming chat, returns complete response[chat\_poll.php](./examples/chat_poll.php)`$client->chat->createAndPoll()`Auto-polling until chat completion[chat\_with\_conversation.php](./examples/chat_with_conversation.php)`$client->chat->create()`Chat with conversation context### Conversation &amp; Message Examples

[](#conversation--message-examples)

ExampleDescription[conversation\_crud.php](./examples/conversation_crud.php)Create, retrieve, list, and clear conversations[message\_crud.php](./examples/message_crud.php)Create, retrieve, list, update, and delete messages### Dataset Examples

[](#dataset-examples)

ExampleDescription[dataset\_crud.php](./examples/dataset_crud.php)Create, list, update, and delete datasets (knowledge bases)[document\_crud.php](./examples/document_crud.php)Create, list, update, and delete documents in datasets### Workflow Examples

[](#workflow-examples)

ExampleDescription[workflow\_run.php](./examples/workflow_run.php)Execute a workflow with non-streaming output[workflow\_stream.php](./examples/workflow_stream.php)Execute a workflow with streaming output (SSE)API Reference
-------------

[](#api-reference)

### CozeClient

[](#cozeclient)

The main entry point for the SDK.

```
$client = new CozeClient(
    AuthInterface $auth,      // Authentication handler
    string $baseUrl = 'https://api.coze.cn',  // API base URL
    array $options = []       // Additional HTTP client options
);
```

### Chat API

[](#chat-api)

#### `$client->chat->create(array $request): array`

[](#client-chat-createarray-request-array)

Create a non-streaming chat.

**Parameters:**

- `bot_id` (string, required): The ID of the bot
- `user_id` (string, required): The ID of the user
- `additional_messages` (array, required): List of messages
- `conversation_id` (string, optional): Conversation ID for context
- `auto_save_history` (bool, optional): Whether to save history (default: true)
- `meta_data` (array, optional): Additional metadata
- `parameters` (array, optional): Custom parameters

#### `$client->chat->stream(array $request): Generator`

[](#client-chat-streamarray-request-generator)

Create a streaming chat that yields `ChatEvent` objects.

#### `$client->chat->createAndPoll(array $request, int $pollInterval = 1, int $timeout = 300): Chat`

[](#client-chat-createandpollarray-request-int-pollinterval--1-int-timeout--300-chat)

Create a chat and poll until completion.

#### `$client->chat->retrieve(string $conversationId, string $chatId): array`

[](#client-chat-retrievestring-conversationid-string-chatid-array)

Retrieve chat status.

#### `$client->chat->cancel(string $conversationId, string $chatId): array`

[](#client-chat-cancelstring-conversationid-string-chatid-array)

Cancel a chat.

### Conversations API

[](#conversations-api)

#### `$client->conversations->create(array $request): array`

[](#client-conversations-createarray-request-array)

Create a new conversation.

**Parameters:**

- `messages` (array, optional): Initial messages in the conversation
- `meta_data` (array, optional): Additional metadata
- `bot_id` (string, optional): Bot ID to bind the conversation
- `connector_id` (string, optional): Connector ID (999: Chat SDK, 1024: API)

```
$response = $client->conversations->create([
    'bot_id' => 'your_bot_id',
    'meta_data' => [
        'user_name' => 'Test User',
    ],
]);
$conversationId = $response['data']['id'];
```

#### `$client->conversations->retrieve(string $conversationId): array`

[](#client-conversations-retrievestring-conversationid-array)

Retrieve conversation details.

#### `$client->conversations->list(array $request): array`

[](#client-conversations-listarray-request-array)

List conversations for a bot.

**Parameters:**

- `bot_id` (string, required): Bot ID
- `page_num` (int, optional): Page number (default: 1)
- `page_size` (int, optional): Page size (default: 20)

#### `$client->conversations->clear(string $conversationId): array`

[](#client-conversations-clearstring-conversationid-array)

Clear conversation context/history.

### Messages API

[](#messages-api)

#### `$client->conversations->messages->create(array $request): array`

[](#client-conversations-messages-createarray-request-array)

Create a message in a conversation.

**Parameters:**

- `conversation_id` (string, required): Conversation ID
- `role` (string, required): Message role ('user' or 'assistant')
- `content` (string, required): Message content
- `content_type` (string, required): Content type ('text' or 'object\_string')
- `meta_data` (array, optional): Additional metadata

```
$response = $client->conversations->messages->create([
    'conversation_id' => $conversationId,
    'role' => 'user',
    'content' => 'Hello, how are you?',
    'content_type' => 'text',
]);
```

#### `$client->conversations->messages->list(array $request): array`

[](#client-conversations-messages-listarray-request-array)

List messages in a conversation.

**Parameters:**

- `conversation_id` (string, required): Conversation ID
- `order` (string, optional): Sorting order ('asc' or 'desc')
- `chat_id` (string, optional): Filter by chat ID
- `before_id` (string, optional): Get messages before this ID
- `after_id` (string, optional): Get messages after this ID
- `limit` (int, optional): Number of messages (default: 50, max: 50)

#### `$client->conversations->messages->retrieve(string $conversationId, string $messageId): array`

[](#client-conversations-messages-retrievestring-conversationid-string-messageid-array)

Retrieve a specific message.

#### `$client->conversations->messages->update(array $request): array`

[](#client-conversations-messages-updatearray-request-array)

Update a message.

**Parameters:**

- `conversation_id` (string, required): Conversation ID
- `message_id` (string, required): Message ID
- `content` (string, optional): New message content
- `content_type` (string, optional): New content type
- `meta_data` (array, optional): New metadata

#### `$client->conversations->messages->delete(string $conversationId, string $messageId): array`

[](#client-conversations-messages-deletestring-conversationid-string-messageid-array)

Delete a message.

### Datasets API (Knowledge Base)

[](#datasets-api-knowledge-base)

#### `$client->datasets->create(array $request): array`

[](#client-datasets-createarray-request-array)

Create a new dataset (knowledge base).

**Parameters:**

- `name` (string, required): Dataset name
- `space_id` (string, required): Space ID
- `format_type` (int, required): 0 = Document, 1 = Spreadsheet, 2 = Image
- `description` (string, optional): Dataset description

#### `$client->datasets->list(array $request): array`

[](#client-datasets-listarray-request-array)

List datasets in a space.

**Parameters:**

- `space_id` (string, required): Space ID
- `page_num` (int, optional): Page number (default: 1)
- `page_size` (int, optional): Page size (default: 10)

#### `$client->datasets->update(string $datasetId, array $request): array`

[](#client-datasets-updatestring-datasetid-array-request-array)

Update a dataset.

#### `$client->datasets->delete(string $datasetId): array`

[](#client-datasets-deletestring-datasetid-array)

Delete a dataset.

### Documents API (Knowledge Base Files)

[](#documents-api-knowledge-base-files)

#### `$client->datasets->documents->create(array $request): array`

[](#client-datasets-documents-createarray-request-array)

Create documents in a dataset.

```
use Coze\Models\DocumentBase;

$client->datasets->documents->create([
    'dataset_id' => 123456789,
    'document_bases' => [
        DocumentBase::buildLocalFile('doc.txt', 'File content here', 'txt'),
        DocumentBase::buildWebPage('Web Page', 'https://example.com', 24),
    ],
    'format_type' => 0,
]);
```

#### `$client->datasets->documents->list(array $request): array`

[](#client-datasets-documents-listarray-request-array)

List documents in a dataset.

**Parameters:**

- `dataset_id` (int, required): Dataset ID
- `page` (int, optional): Page number (default: 1)
- `size` (int, optional): Page size (default: 20)

#### `$client->datasets->documents->update(array $request): array`

[](#client-datasets-documents-updatearray-request-array)

Update a document.

**Parameters:**

- `document_id` (int, required): Document ID
- `document_name` (string, optional): New document name

#### `$client->datasets->documents->delete(array $documentIds): array`

[](#client-datasets-documents-deletearray-documentids-array)

Delete documents.

### DocumentBase Helper Methods

[](#documentbase-helper-methods)

```
use Coze\Models\DocumentBase;

// Build from local file content
$doc = DocumentBase::buildLocalFile('name', 'content', 'txt');

// Build from web page URL
$doc = DocumentBase::buildWebPage('name', 'https://example.com', 24); // 24h update interval

// Build from image file ID
$doc = DocumentBase::buildImage('name', $fileId);
```

### Message Helper Methods

[](#message-helper-methods)

```
use Coze\Models\Message;

// Build a user text question
$message = Message::buildUserQuestionText('Hello!');

// Build an assistant answer
$message = Message::buildAssistantAnswer('Hi there!');

// Build multimodal message with text and image
$message = Message::buildUserQuestionObjects([
    Message::textObject('What is in this image?'),
    Message::imageObjectByUrl('https://example.com/image.jpg'),
]);
```

### Event Types

[](#event-types)

```
use Coze\Chat\ChatEventType;

ChatEventType::CONVERSATION_CHAT_CREATED;
ChatEventType::CONVERSATION_CHAT_IN_PROGRESS;
ChatEventType::CONVERSATION_CHAT_COMPLETED;
ChatEventType::CONVERSATION_CHAT_FAILED;
ChatEventType::CONVERSATION_CHAT_REQUIRES_ACTION;
ChatEventType::CONVERSATION_MESSAGE_DELTA;
ChatEventType::CONVERSATION_MESSAGE_COMPLETED;
ChatEventType::ERROR;
ChatEventType::DONE;
```

Error Handling
--------------

[](#error-handling)

```
use Coze\Exceptions\ApiException;
use Coze\Exceptions\CozeException;

try {
    $response = $client->chat->create([...]);
} catch (ApiException $e) {
    echo "API Error: " . $e->getErrorMessage() . "\n";
    echo "Error Code: " . $e->getErrorCode() . "\n";
    echo "Log ID: " . $e->getLogId() . "\n";  // For debugging with Coze support
} catch (CozeException $e) {
    echo "SDK Error: " . $e->getMessage() . "\n";
}
```

Environment Variables
---------------------

[](#environment-variables)

You can configure the SDK using environment variables:

```
export COZE_API_TOKEN="your_access_token"
export COZE_API_BASE="https://api.coze.cn"  # or https://api.coze.com
export COZE_BOT_ID="your_bot_id"
export COZE_USER_ID="user_123"
```

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.

Contributing
------------

[](#contributing)

Contributions are welcome! Please feel free to submit a Pull Request.

TODO
----

[](#todo)

- **Conversations**
- **Workflows**
- **Bots**
- **Workspaces**
- **Files**
- **Apps**
- **Folders**

Related Links
-------------

[](#related-links)

- [Coze Official Website](https://www.coze.cn)
- [Coze API Documentation](https://www.coze.cn/open/docs/developer_guides)
- [Coze Python SDK](https://github.com/coze-dev/coze-py)
- [Coze Go SDK](https://github.com/coze-dev/coze-go)

###  Health Score

28

—

LowBetter than 52% of packages

Maintenance74

Regular maintenance activity

Popularity3

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity29

Early-stage or recently created project

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~6 days

Total

5

Last Release

144d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/7321032?v=4)[sungithubid](/maintainers/sungithubid)[@sungithubid](https://github.com/sungithubid)

---

Tags

apisdkaibotchatcoze

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/sungithubid-coze-php-sdk/health.svg)

```
[![Health](https://phpackages.com/badges/sungithubid-coze-php-sdk/health.svg)](https://phpackages.com/packages/sungithubid-coze-php-sdk)
```

###  Alternatives

[aws/aws-sdk-php

AWS SDK for PHP - Use Amazon Web Services in your PHP project

6.3k543.5M2.6k](/packages/aws-aws-sdk-php)[neuron-core/neuron-ai

The PHP Agentic Framework.

2.0k656.1k38](/packages/neuron-core-neuron-ai)[tempest/framework

The PHP framework that gets out of your way.

2.2k34.4k15](/packages/tempest-framework)[telnyx/telnyx-php

Official Telnyx PHP SDK — APIs for Voice, SMS, MMS, WhatsApp, Fax, SIP Trunking, Wireless IoT, Call Control, and more. Build global communications on Telnyx's private carrier-grade network.

35789.4k2](/packages/telnyx-telnyx-php)[eslazarev/wildberries-sdk

Wildberries OpenAPI clients (generated).

273.0k](/packages/eslazarev-wildberries-sdk)[bushlanov-dev/max-bot-api-client-php

Max Bot API Client library

486.3k](/packages/bushlanov-dev-max-bot-api-client-php)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
