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:
- Full support for Coze open APIs and authentication APIs
- Kotlin Coroutines & Flow support for async operations
- Cross-platform support (Android & iOS)
- Optimized streaming APIs with Flow returns
- Simple and intuitive API design
-
/cozeAPI
- The core API SDK module containing all the API implementations.commonMain
- Common code for all platforms:- API Services:
bot
- Bot management serviceschat
- Chat and message servicesconversation
- Conversation management servicesdataset
- Dataset and document servicesfile
- File upload servicesworkflow
- Workflow execution servicesworkspace
- Workspace management services
- API Services:
androidMain
- 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 examples
androidMain
- Android-specific demo codeiosMain
- iOS-specific demo code
-
/iosApp
- iOS demo application.- Native iOS application entry point
- Demonstrates SDK usage in iOS environment
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:
- Personal Access Token (PAT)
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)
}
}
- JWT Token
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)
}
}
- OAuth Token
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:
- Token is null
- Token is about to expire (30 seconds before expiration)
- Force refresh is requested
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 and publish bots
- List and retrieve bots
- Update bot configurations
- Non-streaming chat
- Streaming chat
- Chat with images
- Chat with local plugins
- Run workflows
- Stream workflow execution
- Handle workflow interrupts
- Create/Update/Delete datasets
- List datasets
- Document management
- Image management
- Create/Update conversations
- List conversations
- Message operations
- Upload files
- Retrieve file information
- List workspaces
- Workspace management
// 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 errors
Example 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:
- HTTP status code (if applicable)
- Error code
- Error message
- Error details
- Help documentation URL (if available)
- Log ID for debugging
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.