Tích hợp ClickAI qua RESTful API

Hướng dẫn đầy đủ để tích hợp các ứng dụng AI được xây dựng trên ClickAI vào bất kỳ hệ thống nào thông qua API.

Mục lục

· [Cách API Integration hoạt động](#cách-api-integration-hoạt-động)

· [Bắt đầu](#bắt-đầu)

· [Xác thực (Authentication)](#xác-thực-authentication)

· [API lấy danh sách Assistants](#api-lấy-danh-sách-assistants)

· [API cho Text Generation App](#api-cho-text-generation-app)

· [API cho Conversational App (Chatbot / Agent)](#api-cho-conversational-app)

· [API cho Workflow App](#api-cho-workflow-app)

· [Quản lý conversation_id](#quản-lý-conversation_id)

· [Streaming vs Blocking Response](#streaming-vs-blocking-response)

· [File Upload API](#file-upload-api)

· [Feedback API](#feedback-api)

· [Conversations API](#conversations-api)

· [Error Handling](#error-handling)

· [Rate Limits](#rate-limits)

· [SDK & Libraries](#sdk--libraries)

Cách API Integration hoạt động

┌─────────────────┐ ┌─────────────────┐ │ Ứng dụng │ HTTP Request │ ClickAI │ │ của bạn │──────────────────▶│ Platform │ │ (Frontend/ │ │ │ │ Backend) │◀──────────────────│ AI Processing │ │ │ JSON / SSE │ │ └─────────────────┘ Response └─────────────────┘

1. Build ứng dụng AI trong ClickAI Studio

2. Generate API credentials (Secret Key)

3. Call API từ ứng dụng của bạn

4. Users tương tác qua giao diện của bạn — ClickAI xử lý AI phía sau

Bắt đầu

Bước 1: Truy cập API Settings

5. Mở ứng dụng trong ClickAI Studio

6. Nhấn "Publish" → Chọn tab "API"

7. Xem tài liệu API tự động cho ứng dụng

Bước 2: Tạo API Key

8. Trong tab API, nhấn "+ Create API Key"

9. Đặt tên mô tả (ví dụ: production-backend)

10. Copy Secret Key — lưu trữ an toàn, chỉ hiển thị 1 lần

Bước 3: Xác định endpoint phù hợp

ClickAI có hai base URL tùy theo loại API:

Base URL

Dùng cho

https://clickai.io

Studio / Console APIs (quản lý apps, workspace)

https://api.clickai.io

App Runtime APIs (chat, workflow, files)

Loại ứng dụng

Base

Endpoint

Danh sách Assistants

clickai.io

GET /assistant/api/assistant/my-assistants

Text Generation

api.clickai.io

POST /v1/completion-messages

Chatbot / Agent

api.clickai.io

POST /v1/chat-messages

Workflow

api.clickai.io

POST /v1/workflows/run

Xác thực (Authentication)

Mọi API request đều yêu cầu Bearer Token trong header:

Authorization: Bearer {YOUR_SECRET_KEY} Content-Type: application/json

🛑 CAUTION: **Bảo mật API Key:** - KHÔNG BAO GIỜ đặt API Key trong code client-side (JavaScript frontend) - KHÔNG commit API Key vào Git repository - Luôn gọi API từ backend server - Lưu API Key trong environment variables - Rotate key định kỳ nếu nghi ngờ bị lộ

API lấy danh sách Assistants

Lấy danh sách các assistants (apps) thuộc workspace của bạn.

Endpoint

GET https://clickai.io/assistant/api/assistant/my-assistants

Query Parameters

Parameter

Type

Required

Mô tả

page

integer

Trang hiện tại (mặc định: 1)

page_size

integer

Số items mỗi trang (mặc định: 10)

mode

string

Loại app: workflow, agent-chat, chat, completion

workspace_id

string

ID workspace của bạn

Ví dụ — Lấy danh sách Workflow Apps

curl -G 'https://clickai.io/assistant/api/assistant/my-assistants' \ -d 'page=1' \ -d 'page_size=10' \ -d 'mode=workflow' \ -d 'workspace_id=<YOUR_WORKSPACE_ID>' \ -H 'accept: application/json' \ -H 'authorization: Bearer <YOUR_ACCESS_TOKEN>'

Ví dụ — Lấy danh sách Agent Chat Apps

curl -G 'https://clickai.io/assistant/api/assistant/my-assistants' \ -d 'page=1' \ -d 'page_size=10' \ -d 'mode=agent-chat' \ -d 'workspace_id=<YOUR_WORKSPACE_ID>' \ -H 'accept: application/json' \ -H 'authorization: Bearer <YOUR_ACCESS_TOKEN>'

Ví dụ — Python

import requests url = "https://clickai.io/assistant/api/assistant/my-assistants" headers = { 'accept': 'application/json', 'authorization': 'Bearer YOUR_ACCESS_TOKEN', } params = { 'page': 1, 'page_size': 10, 'mode': 'workflow', 'workspace_id': 'YOUR_WORKSPACE_ID' } response = requests.get(url, headers=headers, params=params) data = response.json() for app in data.get('data', []): print(f"App: {app['name']} (ID: {app['id']})")

Response

{ "page": 1, "page_size": 10, "total": 5, "data": [ { "id": "app-abc123", "name": "Customer Support Bot", "mode": "agent-chat", "description": "AI hỗ trợ khách hàng", "created_at": 1705395332 } ] }

💡 TIP: Sử dụng API này để tự động lấy danh sách apps trong workspace, phục vụ cho việc tích hợp MCP hoặc quản lý apps qua script.

API cho Text Generation App

Dành cho ứng dụng tạo nội dung một lần (single-turn), không lưu lịch sử hội thoại.

Endpoint

POST https://api.clickai.io/v1/completion-messages

Request Body

Field

Type

Required

Mô tả

inputs

object

Biến đầu vào theo cấu hình app

response_mode

string

"streaming" hoặc "blocking"

user

string

User ID duy nhất để tracking

files

array

Files đính kèm (nếu app hỗ trợ)

Ví dụ — cURL

curl --location --request POST 'https://api.clickai.io/v1/completion-messages' \ --header 'Authorization: Bearer YOUR-SECRET-KEY' \ --header 'Content-Type: application/json' \ --data-raw '{ "inputs": { "text": "Viết email cảm ơn khách hàng đã mua sản phẩm" }, "response_mode": "streaming", "user": "user-abc-123" }'

Ví dụ — Python

import requests import json url = "https://api.clickai.io/v1/completion-messages" headers = { 'Authorization': 'Bearer YOUR-SECRET-KEY', 'Content-Type': 'application/json', } data = { "inputs": { "text": "Viết email cảm ơn khách hàng đã mua sản phẩm" }, "response_mode": "streaming", "user": "user-abc-123" } response = requests.post(url, headers=headers, data=json.dumps(data)) print(response.text)

Ví dụ — JavaScript (Node.js)

const axios = require('axios'); const response = await axios.post( 'https://api.clickai.io/v1/completion-messages', { inputs: { text: 'Viết email cảm ơn khách hàng' }, response_mode: 'streaming', user: 'user-abc-123' }, { headers: { 'Authorization': 'Bearer YOUR-SECRET-KEY', 'Content-Type': 'application/json' } } ); console.log(response.data);

Response (Blocking Mode)

{ "id": "msg-abc123", "answer": "Kính gửi Quý khách hàng...", "created_at": 1705395332, "metadata": { "usage": { "prompt_tokens": 45, "completion_tokens": 128, "total_tokens": 173, "total_price": "0.000346", "currency": "USD" } } }

API cho Conversational App

Dành cho Chatbot và Agent — hỗ trợ multi-turn conversation.

Endpoint

POST https://api.clickai.io/v1/chat-messages

Request Body

Field

Type

Required

Mô tả

inputs

object

Biến đầu vào (chỉ cho cuộc hội thoại mới)

query

string

Tin nhắn của người dùng

response_mode

string

"streaming" hoặc "blocking"

conversation_id

string

ID cuộc hội thoại (để trống = tạo mới)

user

string

User ID duy nhất

files

array

Files đính kèm

Ví dụ — cURL

curl --location --request POST 'https://api.clickai.io/v1/chat-messages' \ --header 'Authorization: Bearer YOUR-SECRET-KEY' \ --header 'Content-Type: application/json' \ --data-raw '{ "inputs": {}, "query": "Xin chào, tôi cần hỗ trợ về sản phẩm", "response_mode": "streaming", "conversation_id": "", "user": "user-abc-123" }'

Ví dụ — Python

import requests import json url = "https://api.clickai.io/v1/chat-messages" headers = { 'Authorization': 'Bearer YOUR-SECRET-KEY', 'Content-Type': 'application/json', } data = { "inputs": {}, "query": "Xin chào, tôi cần hỗ trợ về sản phẩm", "response_mode": "streaming", "conversation_id": "", "user": "user-abc-123" } response = requests.post(url, headers=headers, data=json.dumps(data)) print(response.text)

Response (Blocking Mode)

{ "id": "msg-abc456", "conversation_id": "conv-xyz789", "answer": "Xin chào! Tôi có thể giúp gì cho bạn...", "created_at": 1705395332, "metadata": { "usage": { "prompt_tokens": 56, "completion_tokens": 89, "total_tokens": 145 } } }

API cho Workflow App

Dành cho Workflow — batch processing, pipeline execution.

Endpoint

POST https://api.clickai.io/v1/workflows/run

Request Body

Field

Type

Required

Mô tả

inputs

object

Biến đầu vào cho workflow

response_mode

string

"streaming" hoặc "blocking"

user

string

User ID duy nhất

Ví dụ — cURL

curl --location --request POST 'https://api.clickai.io/v1/workflows/run' \ --header 'Authorization: Bearer YOUR-SECRET-KEY' \ --header 'Content-Type: application/json' \ --data-raw '{ "inputs": { "input_text": "Phân tích dữ liệu bán hàng Q4 2024" }, "response_mode": "streaming", "user": "user-abc-123" }'

Response (Blocking Mode)

{ "workflow_run_id": "wf-run-abc123", "task_id": "task-xyz789", "data": { "id": "wf-abc123", "workflow_id": "wf-def456", "status": "succeeded", "outputs": { "result": "Kết quả phân tích..." }, "total_tokens": 456, "created_at": 1705395332, "finished_at": 1705395345 } }

Quản lý conversation_id

conversation_id là khóa quan trọng nhất khi làm việc với Conversational Apps.

Quy tắc chi tiết

Tình huống

Xử lý

Ghi chú

Bắt đầu hội thoại mới

conversation_id: "" (để trống)

Hệ thống tạo ID mới và trả về trong response

Tiếp tục hội thoại

conversation_id: "conv-xyz789"

Sử dụng ID từ response trước

Truyền inputs giữa session

Dùng Conversation Variables

inputs bị bỏ qua khi có conversation_id

Ví dụ flow hoàn chỉnh

import requests import json BASE_URL = "https://api.clickai.io/v1" HEADERS = { 'Authorization': 'Bearer YOUR-SECRET-KEY', 'Content-Type': 'application/json', } # === Lượt 1: Bắt đầu hội thoại mới === response1 = requests.post(f"{BASE_URL}/chat-messages", headers=HEADERS, data=json.dumps({ "inputs": {"language": "vi"}, "query": "Xin chào, tôi muốn hỏi về bảo hành", "response_mode": "blocking", "conversation_id": "", # Để trống → tạo mới "user": "user-001" }) ) data1 = response1.json() conv_id = data1["conversation_id"] # Lưu lại conversation_id print(f"Bot: {data1['answer']}") print(f"Conversation ID: {conv_id}") # === Lượt 2: Tiếp tục hội thoại === response2 = requests.post(f"{BASE_URL}/chat-messages", headers=HEADERS, data=json.dumps({ "inputs": {}, "query": "Sản phẩm XYZ có bảo hành bao lâu?", "response_mode": "blocking", "conversation_id": conv_id, # Truyền ID để tiếp tục "user": "user-001" }) ) data2 = response2.json() print(f"Bot: {data2['answer']}") # === Lượt 3: Tiếp tục === response3 = requests.post(f"{BASE_URL}/chat-messages", headers=HEADERS, data=json.dumps({ "inputs": {}, "query": "Cảm ơn bạn!", "response_mode": "blocking", "conversation_id": conv_id, "user": "user-001" }) ) data3 = response3.json() print(f"Bot: {data3['answer']}")

🚨 WARNING: Khi truyền `conversation_id` đã tồn tại, mọi giá trị trong `inputs` sẽ bị bỏ qua. Chỉ `query` được xử lý. Nếu cần thay đổi biến giữa session, hãy sử dụng **Conversation Variables**.

Streaming vs Blocking Response

Blocking Mode

· Response trả về toàn bộ kết quả khi xử lý xong

· Phù hợp cho: Backend processing, batch jobs

· Timeout mặc định: 60 giây

{ "response_mode": "blocking" }

Streaming Mode (Khuyến nghị)

· Response trả về từng phần qua Server-Sent Events (SSE)

· Phù hợp cho: Real-time chat, UX tốt hơn

· Không giới hạn thời gian xử lý

{ "response_mode": "streaming" }

Xử lý SSE trong JavaScript:

const eventSource = new EventSource( 'https://api.clickai.io/v1/chat-messages', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR-SECRET-KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ inputs: {}, query: 'Xin chào', response_mode: 'streaming', user: 'user-001' }) } ); // Hoặc dùng fetch API const response = await fetch('https://api.clickai.io/v1/chat-messages', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR-SECRET-KEY', 'Content-Type': 'application/json' }, body: JSON.stringify({ inputs: {}, query: 'Xin chào', response_mode: 'streaming', conversation_id: '', user: 'user-001' }) }); const reader = response.body.getReader(); const decoder = new TextDecoder(); while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value); const lines = chunk.split('\n'); for (const line of lines) { if (line.startsWith('data: ')) { const data = JSON.parse(line.slice(6)); if (data.event === 'message') { process.stdout.write(data.answer); } } } }

SSE Event Types

Event

Mô tả

message

Phần nội dung phản hồi (text chunk)

agent_message

Phản hồi từ Agent mode

agent_thought

Quá trình suy luận của Agent

message_file

File được tạo bởi AI

message_end

Kết thúc tin nhắn, bao gồm metadata

tts_message

Audio chunk (nếu bật TTS)

message_replace

Nội dung thay thế (content moderation)

error

Lỗi xảy ra trong stream

ping

Keep-alive signal

File Upload API

Upload file để sử dụng trong conversation:

Endpoint

POST https://api.clickai.io/v1/files/upload

Request (multipart/form-data)

Field

Type

Mô tả

file

file

File cần upload

user

string

User ID

Ví dụ — cURL

curl --location --request POST 'https://api.clickai.io/v1/files/upload' \ --header 'Authorization: Bearer YOUR-SECRET-KEY' \ --form 'file=@"/path/to/document.pdf"' \ --form 'user="user-abc-123"'

Response

{ "id": "file-abc123", "name": "document.pdf", "size": 1024000, "extension": "pdf", "mime_type": "application/pdf", "created_by": "user-abc-123", "created_at": 1705395332 }

Sử dụng file trong chat

{ "inputs": {}, "query": "Tóm tắt nội dung file này", "response_mode": "streaming", "conversation_id": "", "user": "user-abc-123", "files": [ { "type": "document", "transfer_method": "local_file", "upload_file_id": "file-abc123" } ] }

Feedback API

Thu thập feedback người dùng cho từng tin nhắn:

Endpoint

POST https://api.clickai.io/v1/messages/{message_id}/feedbacks

Request Body

{ "rating": "like", "user": "user-abc-123", "content": "Câu trả lời rất hữu ích!" }

Field

Values

Mô tả

rating

"like", "dislike", null

Đánh giá (null = hủy đánh giá)

content

string

Comment bổ sung (optional)

Conversations API

Lấy danh sách conversations

GET https://api.clickai.io/v1/conversations?user=user-abc-123&limit=20

Lấy lịch sử tin nhắn

GET https://api.clickai.io/v1/messages?conversation_id=conv-xyz789&user=user-abc-123&limit=20

Đổi tên conversation

POST https://api.clickai.io/v1/conversations/{conversation_id}/name

{ "name": "Hỗ trợ bảo hành sản phẩm XYZ", "auto_generate": false, "user": "user-abc-123" }

Xóa conversation

DELETE https://api.clickai.io/v1/conversations/{conversation_id}

Error Handling

HTTP Status Codes

Code

Mô tả

200

Thành công

400

Bad Request — Request không hợp lệ

401

Unauthorized — API Key sai hoặc hết hạn

403

Forbidden — Không có quyền truy cập

404

Not Found — Resource không tồn tại

429

Too Many Requests — Vượt quá rate limit

500

Internal Server Error — Lỗi server

Error Response Format

{ "code": "invalid_param", "message": "The 'query' field is required", "status": 400 }

Xử lý lỗi — Python

import requests import json try: response = requests.post(url, headers=headers, data=json.dumps(data)) response.raise_for_status() result = response.json() print(result["answer"]) except requests.exceptions.HTTPError as e: if e.response.status_code == 401: print("API Key không hợp lệ") elif e.response.status_code == 429: print("Quá nhiều requests, thử lại sau") else: error = e.response.json() print(f"Lỗi: {error.get('message', 'Unknown error')}") except requests.exceptions.ConnectionError: print("Không thể kết nối đến ClickAI API")

Rate Limits

Gói dịch vụ

Requests/phút

Requests/ngày

Sandbox

100

10,000

Professional

500

100,000

Team

1,000

500,000

Enterprise

Custom

Custom

📝 NOTE: Khi vượt rate limit, API trả về `429 Too Many Requests`. Implement retry logic với exponential backoff.

SDK & Libraries

Official SDKs

Ngôn ngữ

Package

Install

Python

clickai-sdk

pip install clickai-sdk

JavaScript

@clickai/sdk

npm install @clickai/sdk

Python SDK

from clickai import ClickAI client = ClickAI(api_key="YOUR-SECRET-KEY") # Chat response = client.chat.create( query="Xin chào", user="user-001" ) print(response.answer) # Streaming for chunk in client.chat.create( query="Viết một bài thơ", user="user-001", stream=True ): print(chunk.answer, end="")

JavaScript SDK

import { ClickAI } from '@clickai/sdk'; const client = new ClickAI({ apiKey: 'YOUR-SECRET-KEY' }); // Chat const response = await client.chat.create({ query: 'Xin chào', user: 'user-001' }); console.log(response.answer); // Streaming const stream = await client.chat.create({ query: 'Viết một bài thơ', user: 'user-001', stream: true }); for await (const chunk of stream) { process.stdout.write(chunk.answer); }

📖 Xem thêm: [MCP Server](./02-mcp-server.md) · [Build](../01-build.md) · [Publish](../02-publish.md)

Last updated