⚠️ 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.
- 🚀 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
- PHP 7.4 or higher
- Composer
- GuzzleHttp 7.0+
composer require sungithubid/coze-php-sdkOr add to your composer.json:
{
"require": {
"sungithubid/coze-php-sdk": "^1.0"
}
}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
);| Example | Method | Description |
|---|---|---|
| chat_stream.php | $client->chat->stream() |
Streaming chat using PHP Generator (yield), memory-efficient for large responses |
| chat_no_stream.php | $client->chat->create() |
Non-streaming chat, returns complete response |
| chat_poll.php | $client->chat->createAndPoll() |
Auto-polling until chat completion |
| chat_with_conversation.php | $client->chat->create() |
Chat with conversation context |
| Example | Description |
|---|---|
| conversation_crud.php | Create, retrieve, list, and clear conversations |
| message_crud.php | Create, retrieve, list, update, and delete messages |
| Example | Description |
|---|---|
| dataset_crud.php | Create, list, update, and delete datasets (knowledge bases) |
| document_crud.php | Create, list, update, and delete documents in datasets |
| Example | Description |
|---|---|
| workflow_run.php | Execute a workflow with non-streaming output |
| workflow_stream.php | Execute a workflow with streaming output (SSE) |
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
);Create a non-streaming chat.
Parameters:
bot_id(string, required): The ID of the botuser_id(string, required): The ID of the useradditional_messages(array, required): List of messagesconversation_id(string, optional): Conversation ID for contextauto_save_history(bool, optional): Whether to save history (default: true)meta_data(array, optional): Additional metadataparameters(array, optional): Custom parameters
Create a streaming chat that yields ChatEvent objects.
Create a chat and poll until completion.
Retrieve chat status.
Cancel a chat.
Create a new conversation.
Parameters:
messages(array, optional): Initial messages in the conversationmeta_data(array, optional): Additional metadatabot_id(string, optional): Bot ID to bind the conversationconnector_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'];Retrieve conversation details.
List conversations for a bot.
Parameters:
bot_id(string, required): Bot IDpage_num(int, optional): Page number (default: 1)page_size(int, optional): Page size (default: 20)
Clear conversation context/history.
Create a message in a conversation.
Parameters:
conversation_id(string, required): Conversation IDrole(string, required): Message role ('user' or 'assistant')content(string, required): Message contentcontent_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',
]);List messages in a conversation.
Parameters:
conversation_id(string, required): Conversation IDorder(string, optional): Sorting order ('asc' or 'desc')chat_id(string, optional): Filter by chat IDbefore_id(string, optional): Get messages before this IDafter_id(string, optional): Get messages after this IDlimit(int, optional): Number of messages (default: 50, max: 50)
Retrieve a specific message.
Update a message.
Parameters:
conversation_id(string, required): Conversation IDmessage_id(string, required): Message IDcontent(string, optional): New message contentcontent_type(string, optional): New content typemeta_data(array, optional): New metadata
Delete a message.
Create a new dataset (knowledge base).
Parameters:
name(string, required): Dataset namespace_id(string, required): Space IDformat_type(int, required): 0 = Document, 1 = Spreadsheet, 2 = Imagedescription(string, optional): Dataset description
List datasets in a space.
Parameters:
space_id(string, required): Space IDpage_num(int, optional): Page number (default: 1)page_size(int, optional): Page size (default: 10)
Update a dataset.
Delete a dataset.
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,
]);List documents in a dataset.
Parameters:
dataset_id(int, required): Dataset IDpage(int, optional): Page number (default: 1)size(int, optional): Page size (default: 20)
Update a document.
Parameters:
document_id(int, required): Document IDdocument_name(string, optional): New document name
Delete documents.
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);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'),
]);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;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";
}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"This project is licensed under the MIT License - see the LICENSE file for details.
Contributions are welcome! Please feel free to submit a Pull Request.
- Conversations
- Workflows
- Bots
- Workspaces
- Files
- Apps
- Folders