Integration Examples
Learn how to integrate CID222 into your applications with these real-world code examples across different languages and frameworks.
JavaScript / Node.js
Basic Request
Node.js - Basic Chat
1const response = await fetch('https://api.cid222.ai/chat/completions', {2 method: 'POST',3 headers: {4 'Authorization': `Bearer ${process.env.CID222_API_KEY}`,5 'Content-Type': 'application/json',6 },7 body: JSON.stringify({8 model: 'gpt-4',9 messages: [10 { role: 'system', content: 'You are a helpful assistant.' },11 { role: 'user', content: userMessage }12 ]13 })14});1516const data = await response.json();17console.log(data.choices[0].message.content);
Streaming Response
Node.js - SSE Streaming
1async function streamChat(message) {2 const response = await fetch('https://api.cid222.ai/chat/completions', {3 method: 'POST',4 headers: {5 'Authorization': `Bearer ${process.env.CID222_API_KEY}`,6 'Content-Type': 'application/json',7 },8 body: JSON.stringify({9 model: 'gpt-4',10 messages: [{ role: 'user', content: message }],11 stream: true12 })13 });1415 const reader = response.body.getReader();16 const decoder = new TextDecoder();17 let fullContent = '';1819 while (true) {20 const { done, value } = await reader.read();21 if (done) break;2223 const chunk = decoder.decode(value);24 const lines = chunk.split('\n');2526 for (const line of lines) {27 if (line.startsWith('data: ')) {28 const data = line.slice(6);29 if (data === '[DONE]') continue;3031 try {32 const parsed = JSON.parse(data);33 const content = parsed.choices[0]?.delta?.content;34 if (content) {35 fullContent += content;36 process.stdout.write(content);37 }38 } catch (e) {39 // Skip invalid JSON40 }41 }42 }43 }4445 return fullContent;46}
Python
Python - Basic Request
1import os2import requests34def chat_completion(message: str) -> str:5 response = requests.post(6 'https://api.cid222.ai/chat/completions',7 headers={8 'Authorization': f'Bearer {os.environ["CID222_API_KEY"]}',9 'Content-Type': 'application/json',10 },11 json={12 'model': 'gpt-4',13 'messages': [14 {'role': 'user', 'content': message}15 ]16 }17 )1819 data = response.json()20 return data['choices'][0]['message']['content']2122# Usage23result = chat_completion("What is the capital of France?")24print(result)
Python Streaming
Python - SSE Streaming
1import os2import requests3import json45def stream_chat(message: str):6 response = requests.post(7 'https://api.cid222.ai/chat/completions',8 headers={9 'Authorization': f'Bearer {os.environ["CID222_API_KEY"]}',10 'Content-Type': 'application/json',11 },12 json={13 'model': 'gpt-4',14 'messages': [{'role': 'user', 'content': message}],15 'stream': True16 },17 stream=True18 )1920 for line in response.iter_lines():21 if line:22 line = line.decode('utf-8')23 if line.startswith('data: '):24 data = line[6:]25 if data == '[DONE]':26 break27 try:28 parsed = json.loads(data)29 content = parsed['choices'][0].get('delta', {}).get('content', '')30 if content:31 print(content, end='', flush=True)32 except json.JSONDecodeError:33 pass34 print() # New line at end3536# Usage37stream_chat("Explain quantum computing in simple terms.")
React / Next.js
React - Chat Hook
1import { useState, useCallback } from 'react';23export function useChat() {4 const [messages, setMessages] = useState([]);5 const [isLoading, setIsLoading] = useState(false);67 const sendMessage = useCallback(async (content: string) => {8 setIsLoading(true);910 // Add user message11 const userMessage = { role: 'user', content };12 setMessages(prev => [...prev, userMessage]);1314 try {15 const response = await fetch('/api/chat', {16 method: 'POST',17 headers: { 'Content-Type': 'application/json' },18 body: JSON.stringify({19 messages: [...messages, userMessage]20 })21 });2223 const data = await response.json();2425 // Add assistant message26 setMessages(prev => [...prev, {27 role: 'assistant',28 content: data.choices[0].message.content29 }]);30 } catch (error) {31 console.error('Chat error:', error);32 } finally {33 setIsLoading(false);34 }35 }, [messages]);3637 return { messages, sendMessage, isLoading };38}
For production React apps, consider using the CID222 SDK which handles streaming, error recovery, and type safety automatically.
cURL Examples
cURL - Basic Request
curl -X POST https://api.cid222.ai/chat/completions \-H "Authorization: Bearer $CID222_API_KEY" \-H "Content-Type: application/json" \-d '{"model": "gpt-4","messages": [{"role": "user", "content": "Hello, world!"}]}'
cURL - Create Session
# Create sessioncurl -X POST https://api.cid222.ai/sessions \-H "Authorization: Bearer $CID222_API_KEY" \-H "Content-Type: application/json" \-d '{"provider": "openai","model": "gpt-4","system_prompt": "You are a helpful assistant."}'# Send message to sessioncurl -X POST https://api.cid222.ai/sessions/SESSION_ID/messages \-H "Authorization: Bearer $CID222_API_KEY" \-H "Content-Type: application/json" \-d '{"content": "What can you help me with?"}'