
Integrates open APIs with comprehensive support for async operations, offering features like bot management, chat services, and workflow execution. Simplifies authentication and provides cross-platform demo applications.
This is a Kotlin Multiplatform project for Coze API targeting Android, iOS. The SDK provides a powerful way to integrate Coze's open APIs into your Kotlin Multiplatform projects.
Key Features:
/cozeAPI - The core API SDK module containing all the API implementations.
commonMain - Common code for all platforms:
bot - Bot management serviceschat - Chat and message servicesconversation - Conversation management servicesdataset - Dataset and document servicesfile - File upload servicesworkflow - Workflow execution servicesworkspace - Workspace management servicesandroidMain - Android-specific implementationsiosMain - iOS-specific implementations/composeApp - Demo application showcasing SDK usage.
commonMain - Cross-platform demo code:
com.coze.demo - Demo implementations for each API feature:
AuthDemo.kt - Authentication examplesBotDemo.kt - Bot management examplesChatDemo.kt - Chat functionality examplesConversationDemo.kt - Conversation management examplesDatasetDemo.kt - Dataset operations examplesFileDemo.kt - File handling examplesWorkflowDemo.kt - Workflow execution examplesWorkspaceDemo.kt - Workspace management examplesandroidMain - Android-specific demo codeiosMain - iOS-specific demo code/iosApp - iOS demo application.
This project utilizes the Kotlin Multiplatform framework.
To use the Coze API, you need to implement a TokenService interface that provides authentication tokens. The SDK uses this service to handle authentication for all API calls.
interface TokenService {
/**
* Get token from service
* @return TokenInfo Token information including expiration time
*/
suspend fun getToken(): TokenInfo
}The TokenInfo class contains:
data class TokenInfo(
val token: String?, // Access token
val expiresIn: Long // Expiration time in seconds
)You can implement this interface in different ways:
class PATTokenService(private val token: String) : TokenService {
override suspend fun getToken(): TokenInfo {
// Return PAT with a default expiration time
return TokenInfo(token = token, expiresIn = 3600)
}
}class JWTTokenService(
private val appId: String,
private val keyId: String,
private val privateKey: String
) : TokenService {
override suspend fun getToken(): TokenInfo {
// Implement JWT token generation logic
val jwtToken = generateJWTToken(
appId = appId,
keyId = keyId,
privateKey = privateKey
)
return TokenInfo(token = jwtToken.accessToken, expiresIn = jwtToken.expiresIn)
}
}class OAuthTokenService(
private val appId: String,
private val appSecret: String
) : TokenService {
override suspend fun getToken(): TokenInfo {
// Implement OAuth token retrieval logic
val tokenData = getOAuthToken(
appId = appId,
appSecret = appSecret
)
return TokenInfo(token = tokenData.accessToken, expiresIn = tokenData.expiresIn)
}
}Then initialize the SDK with your token service:
// Initialize with PAT
val patService = PATTokenService("your-pat-token")
TokenManager.init(patService)
// Or initialize with JWT
val jwtService = JWTTokenService(
appId = "your-app-id",
keyId = "your-key-id",
privateKey = "your-private-key"
)
TokenManager.init(jwtService)
// Or initialize with OAuth
val oauthService = OAuthTokenService(
appId = "your-app-id",
appSecret = "your-app-secret"
)
TokenManager.init(oauthService)The SDK will automatically handle token caching and renewal. It will refresh the token when:
The SDK provides comprehensive examples for various use cases:
| Example | File |
|---|---|
| Token Authentication | AuthDemo.kt |
| Bot Creation and Publishing | BotDemo.kt |
| Non-streaming Chat | ChatDemo.kt |
| Streaming Chat | ChatDemo.kt |
| Conversation Management | ConversationDemo.kt |
| Dataset Management | DatasetDemo.kt |
| File Upload and Management | FileDemo.kt |
| Workflow Execution | WorkflowDemo.kt |
| Workspace Management | WorkspaceDemo.kt |
// Create a streaming chat
val chatService = ChatService()
chatService.stream(StreamChatReq(
botId = "your-bot-id",
additionalMessages = listOf(EnterMessage("Tell me a joke"))
)).collect { chatData ->
println(chatData)
}
// Create a non-streaming chat
chatService.createAndPollChat(CreateChatReq(
botId = "your-bot-id",
additionalMessages = listOf(EnterMessage("Tell me a joke"))
)).let { result ->
println(result)
}val workflowService = WorkflowService()
workflowService.stream(RunWorkflowReq(
workflowId = "your-workflow-id"
)).collect { workflowData ->
println(workflowData)
}val datasetService = DatasetService()
datasetService.create(CreateDatasetReq(
name = "Test Dataset",
spaceId = "your-space-id",
description = "Test description"
)).let { result ->
println(result)
}val botService = BotService()
// Create a bot
botService.create(CreateBotReq(
spaceId = "your-space-id",
name = "Test Bot",
description = "A test bot"
)).let { result ->
println(result)
}
// List published bots
botService.list(ListBotReq(
spaceId = "your-space-id"
)).let { result ->
println(result)
}
// Publish a bot
botService.publish(PublishBotReq(
botId = "your-bot-id",
connectorIds = listOf("1024") // Agent as API
)).let { result ->
println(result)
}val conversationService = ConversationService()
// Create a conversation
conversationService.create(CreateConversationReq(
botId = "your-bot-id"
)).let { result ->
println(result)
}
// List conversations
conversationService.list(ListConversationReq(
botId = "your-bot-id"
)).let { result ->
println(result)
}val fileService = FileService()
// Upload a file
fileService.upload(CreateFileReq(
file = byteArrayOf(), // Your file bytes
fileName = "test.txt",
mimeType = "text/plain"
)).let { result ->
println(result)
}val workspaceService = WorkspaceService()
// List workspaces
workspaceService.list(WorkspaceListRequest(
pageNum = 1,
pageSize = 10
)).let { result ->
println(result)
}The SDK provides comprehensive error handling with the following error types:
AuthenticationError - Authentication related errors (HTTP 401, code 4100)BadRequestError - Invalid request errors (HTTP 400, code 4000)PermissionDeniedError - Permission related errors (HTTP 403, code 4101)NotFoundError - Resource not found errors (HTTP 404, code 4200)RateLimitError - Rate limit related errors (HTTP 429, code 4013)TimeoutError - Request timeout errors (HTTP 408)InternalServerError - Server side errors (HTTP 5xx)GatewayError - Gateway related errors (HTTP 502)APIConnectionError - Network connection errorsAPIUserAbortError - User aborted request errorsJSONParseError - JSON parsing errorsExample error handling:
try {
val result = chatService.createChat(params)
println(result)
} catch (e: AuthenticationError) {
println("Authentication failed: ${e.message}")
} catch (e: BadRequestError) {
println("Invalid request: ${e.message}")
} catch (e: APIError) {
println("API error: ${e.message}")
}Each error type includes:
We welcome contributions! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.
This is a Kotlin Multiplatform project for Coze API targeting Android, iOS. The SDK provides a powerful way to integrate Coze's open APIs into your Kotlin Multiplatform projects.
Key Features:
/cozeAPI - The core API SDK module containing all the API implementations.
commonMain - Common code for all platforms:
bot - Bot management serviceschat - Chat and message servicesconversation - Conversation management servicesdataset - Dataset and document servicesfile - File upload servicesworkflow - Workflow execution servicesworkspace - Workspace management servicesandroidMain - Android-specific implementationsiosMain - iOS-specific implementations/composeApp - Demo application showcasing SDK usage.
commonMain - Cross-platform demo code:
com.coze.demo - Demo implementations for each API feature:
AuthDemo.kt - Authentication examplesBotDemo.kt - Bot management examplesChatDemo.kt - Chat functionality examplesConversationDemo.kt - Conversation management examplesDatasetDemo.kt - Dataset operations examplesFileDemo.kt - File handling examplesWorkflowDemo.kt - Workflow execution examplesWorkspaceDemo.kt - Workspace management examplesandroidMain - Android-specific demo codeiosMain - iOS-specific demo code/iosApp - iOS demo application.
This project utilizes the Kotlin Multiplatform framework.
To use the Coze API, you need to implement a TokenService interface that provides authentication tokens. The SDK uses this service to handle authentication for all API calls.
interface TokenService {
/**
* Get token from service
* @return TokenInfo Token information including expiration time
*/
suspend fun getToken(): TokenInfo
}The TokenInfo class contains:
data class TokenInfo(
val token: String?, // Access token
val expiresIn: Long // Expiration time in seconds
)You can implement this interface in different ways:
class PATTokenService(private val token: String) : TokenService {
override suspend fun getToken(): TokenInfo {
// Return PAT with a default expiration time
return TokenInfo(token = token, expiresIn = 3600)
}
}class JWTTokenService(
private val appId: String,
private val keyId: String,
private val privateKey: String
) : TokenService {
override suspend fun getToken(): TokenInfo {
// Implement JWT token generation logic
val jwtToken = generateJWTToken(
appId = appId,
keyId = keyId,
privateKey = privateKey
)
return TokenInfo(token = jwtToken.accessToken, expiresIn = jwtToken.expiresIn)
}
}class OAuthTokenService(
private val appId: String,
private val appSecret: String
) : TokenService {
override suspend fun getToken(): TokenInfo {
// Implement OAuth token retrieval logic
val tokenData = getOAuthToken(
appId = appId,
appSecret = appSecret
)
return TokenInfo(token = tokenData.accessToken, expiresIn = tokenData.expiresIn)
}
}Then initialize the SDK with your token service:
// Initialize with PAT
val patService = PATTokenService("your-pat-token")
TokenManager.init(patService)
// Or initialize with JWT
val jwtService = JWTTokenService(
appId = "your-app-id",
keyId = "your-key-id",
privateKey = "your-private-key"
)
TokenManager.init(jwtService)
// Or initialize with OAuth
val oauthService = OAuthTokenService(
appId = "your-app-id",
appSecret = "your-app-secret"
)
TokenManager.init(oauthService)The SDK will automatically handle token caching and renewal. It will refresh the token when:
The SDK provides comprehensive examples for various use cases:
| Example | File |
|---|---|
| Token Authentication | AuthDemo.kt |
| Bot Creation and Publishing | BotDemo.kt |
| Non-streaming Chat | ChatDemo.kt |
| Streaming Chat | ChatDemo.kt |
| Conversation Management | ConversationDemo.kt |
| Dataset Management | DatasetDemo.kt |
| File Upload and Management | FileDemo.kt |
| Workflow Execution | WorkflowDemo.kt |
| Workspace Management | WorkspaceDemo.kt |
// Create a streaming chat
val chatService = ChatService()
chatService.stream(StreamChatReq(
botId = "your-bot-id",
additionalMessages = listOf(EnterMessage("Tell me a joke"))
)).collect { chatData ->
println(chatData)
}
// Create a non-streaming chat
chatService.createAndPollChat(CreateChatReq(
botId = "your-bot-id",
additionalMessages = listOf(EnterMessage("Tell me a joke"))
)).let { result ->
println(result)
}val workflowService = WorkflowService()
workflowService.stream(RunWorkflowReq(
workflowId = "your-workflow-id"
)).collect { workflowData ->
println(workflowData)
}val datasetService = DatasetService()
datasetService.create(CreateDatasetReq(
name = "Test Dataset",
spaceId = "your-space-id",
description = "Test description"
)).let { result ->
println(result)
}val botService = BotService()
// Create a bot
botService.create(CreateBotReq(
spaceId = "your-space-id",
name = "Test Bot",
description = "A test bot"
)).let { result ->
println(result)
}
// List published bots
botService.list(ListBotReq(
spaceId = "your-space-id"
)).let { result ->
println(result)
}
// Publish a bot
botService.publish(PublishBotReq(
botId = "your-bot-id",
connectorIds = listOf("1024") // Agent as API
)).let { result ->
println(result)
}val conversationService = ConversationService()
// Create a conversation
conversationService.create(CreateConversationReq(
botId = "your-bot-id"
)).let { result ->
println(result)
}
// List conversations
conversationService.list(ListConversationReq(
botId = "your-bot-id"
)).let { result ->
println(result)
}val fileService = FileService()
// Upload a file
fileService.upload(CreateFileReq(
file = byteArrayOf(), // Your file bytes
fileName = "test.txt",
mimeType = "text/plain"
)).let { result ->
println(result)
}val workspaceService = WorkspaceService()
// List workspaces
workspaceService.list(WorkspaceListRequest(
pageNum = 1,
pageSize = 10
)).let { result ->
println(result)
}The SDK provides comprehensive error handling with the following error types:
AuthenticationError - Authentication related errors (HTTP 401, code 4100)BadRequestError - Invalid request errors (HTTP 400, code 4000)PermissionDeniedError - Permission related errors (HTTP 403, code 4101)NotFoundError - Resource not found errors (HTTP 404, code 4200)RateLimitError - Rate limit related errors (HTTP 429, code 4013)TimeoutError - Request timeout errors (HTTP 408)InternalServerError - Server side errors (HTTP 5xx)GatewayError - Gateway related errors (HTTP 502)APIConnectionError - Network connection errorsAPIUserAbortError - User aborted request errorsJSONParseError - JSON parsing errorsExample error handling:
try {
val result = chatService.createChat(params)
println(result)
} catch (e: AuthenticationError) {
println("Authentication failed: ${e.message}")
} catch (e: BadRequestError) {
println("Invalid request: ${e.message}")
} catch (e: APIError) {
println("API error: ${e.message}")
}Each error type includes:
We welcome contributions! Please feel free to submit a Pull Request.
This project is licensed under the MIT License - see the LICENSE file for details.