5.4. Ví dụ
Các ví dụ code thực tế để bắt đầu nhanh
1. Lấy danh sách AI Twins
Xem tất cả AI twins mà bạn có thể truy cập
GET/api/v1/twins
<> Ví dụ code
Lấy danh sách twins có thể truy cập
// Lấy danh sách twins
const response = await fetch('https://api.twinexpert.com/api/v1/twins', {
headers: {
'Authorization': 'Bearer 123456',
'Content-Type': 'application/json'
}
});
const twins = await response.json();
console.log('Available twins:', twins.data);
2. Chat với AI Twin
Tạo cuộc trò chuyện và gửi tin nhắn đến AI twin
GET /api/v1/conversations
<> Ví dụ code
Tạo cuộc trò chuyện và gửi tin nhắn đến AI twin
// Tạo cuộc trò chuyện và gửi tin nhắn
async function chatWithTwin(twinId, message) {
// 1. Tạo cuộc trò chuyện mới
const conversationResponse = await fetch('https://api.twinexpert.com/api/v1/conversations', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
twinId: twinId,
title: 'API Chat Session'
})
});
const conversation = await conversationResponse.json();
const conversationId = conversation.data.id;
// 2. Gửi tin nhắn
const messageResponse = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/api/v1/conversations/${conversationId}/messages`, {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
content: message
})
});
const result = await messageResponse.json();
return result.data;
}
// Sử dụng
chatWithTwin('twin-id', 'Xin chào!').then(result => {
console.log('Response:', result);
});
2. Streaming Chat
Nhận phản hồi real-time bằng Server-Sent Events
Streaming Response
Endpoint streaming trả về Server-Sent Events với các event types:
progress
: Thông tin tiến trình
delta
: Từng phần của response
complete
: Hoàn thành message
error
: Lỗi xảy ra
Last updated