Skip to main content
CID222Documentation

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});
15
16const 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: true
12 })
13 });
14
15 const reader = response.body.getReader();
16 const decoder = new TextDecoder();
17 let fullContent = '';
18
19 while (true) {
20 const { done, value } = await reader.read();
21 if (done) break;
22
23 const chunk = decoder.decode(value);
24 const lines = chunk.split('\n');
25
26 for (const line of lines) {
27 if (line.startsWith('data: ')) {
28 const data = line.slice(6);
29 if (data === '[DONE]') continue;
30
31 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 JSON
40 }
41 }
42 }
43 }
44
45 return fullContent;
46}

Python

Python - Basic Request
1import os
2import requests
3
4def 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 )
18
19 data = response.json()
20 return data['choices'][0]['message']['content']
21
22# Usage
23result = chat_completion("What is the capital of France?")
24print(result)

Python Streaming

Python - SSE Streaming
1import os
2import requests
3import json
4
5def 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': True
16 },
17 stream=True
18 )
19
20 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 break
27 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 pass
34 print() # New line at end
35
36# Usage
37stream_chat("Explain quantum computing in simple terms.")

React / Next.js

React - Chat Hook
1import { useState, useCallback } from 'react';
2
3export function useChat() {
4 const [messages, setMessages] = useState([]);
5 const [isLoading, setIsLoading] = useState(false);
6
7 const sendMessage = useCallback(async (content: string) => {
8 setIsLoading(true);
9
10 // Add user message
11 const userMessage = { role: 'user', content };
12 setMessages(prev => [...prev, userMessage]);
13
14 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 });
22
23 const data = await response.json();
24
25 // Add assistant message
26 setMessages(prev => [...prev, {
27 role: 'assistant',
28 content: data.choices[0].message.content
29 }]);
30 } catch (error) {
31 console.error('Chat error:', error);
32 } finally {
33 setIsLoading(false);
34 }
35 }, [messages]);
36
37 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 session
curl -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 session
curl -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?"}'