JavaScript
JavaScript Examples
Use Quiet Stack with JavaScript - no installation required, just HTTP requests
Basic Fetch Example
Simple example using the modern fetch API
// Step 1: Make your AI request to OpenAI
const aiResponse = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_OPENAI_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [{
role: 'user',
content: 'What is the capital of France?'
}]
})
});
const aiData = await aiResponse.json();
console.log('AI Response:', aiData.choices[0].message.content);
// Step 2: Log the context to Quiet Stack blockchain
const auditResponse = await fetch('https://api.quietstack.ai/api/v1/audit/log', {
method: 'POST',
headers: {
'Authorization': 'Bearer qs_live_YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
context: {
request_id: 'req-' + Date.now(),
model_provider: 'openai',
model_name: 'gpt-3.5-turbo',
prompt: 'What is the capital of France?',
response: aiData.choices[0].message.content,
token_usage: aiData.usage,
timestamp: new Date().toISOString()
}
})
});
const audit = await auditResponse.json();
console.log('Blockchain Transaction:', audit.transaction_hash);Node.js Example
Server-side JavaScript with built-in https module
// Node.js example with full workflow
async function aiWithBlockchainAudit(prompt) {
try {
// Step 1: Make AI request to OpenAI
const aiResponse = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + process.env.OPENAI_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-4',
messages: [{ role: 'user', content: prompt }]
})
});
const aiData = await aiResponse.json();
const aiMessage = aiData.choices[0].message.content;
// Step 2: Log to Quiet Stack blockchain
const auditResponse = await fetch('https://api.quietstack.ai/api/v1/audit/log', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + process.env.QUIETSTACK_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
context: {
request_id: 'req-' + Date.now(),
model_provider: 'openai',
model_name: 'gpt-4',
prompt: prompt,
response: aiMessage,
token_usage: aiData.usage,
timestamp: new Date().toISOString()
}
})
});
const audit = await auditResponse.json();
return {
aiResponse: aiMessage,
blockchainTx: audit.transaction_hash,
auditId: audit.audit_id
};
} catch (error) {
console.error('Error:', error);
throw error;
}
}
// Usage
aiWithBlockchainAudit('Explain quantum computing')
.then(result => {
console.log('AI Response:', result.aiResponse);
console.log('Blockchain TX:', result.blockchainTx);
})
.catch(error => console.error('Error:', error));React Component
Interactive React component with blockchain verification
// React component example
import { useState } from 'react';
function AIChat() {
const [message, setMessage] = useState('');
const [response, setResponse] = useState('');
const [loading, setLoading] = useState(false);
const [txHash, setTxHash] = useState(null);
const sendMessage = async () => {
if (!message.trim()) return;
setLoading(true);
try {
// Step 1: Call OpenAI
const aiRes = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + process.env.NEXT_PUBLIC_OPENAI_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: message }]
})
});
const aiData = await aiRes.json();
const aiMessage = aiData.choices[0].message.content;
setResponse(aiMessage);
// Step 2: Log to Quiet Stack blockchain
const auditRes = await fetch('https://api.quietstack.ai/api/v1/audit/log', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + process.env.NEXT_PUBLIC_QUIETSTACK_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
context: {
request_id: 'req-' + Date.now(),
model_provider: 'openai',
model_name: 'gpt-3.5-turbo',
prompt: message,
response: aiMessage,
token_usage: aiData.usage,
timestamp: new Date().toISOString()
}
})
});
const audit = await auditRes.json();
setTxHash(audit.transaction_hash);
} catch (error) {
console.error('Error:', error);
} finally {
setLoading(false);
}
};
return (
<div>
<input
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Ask something..."
disabled={loading}
/>
<button onClick={sendMessage} disabled={loading}>
{loading ? 'Thinking...' : 'Send'}
</button>
{response && (
<div>
<h3>AI Response:</h3>
<p>{response}</p>
{txHash && (
<div>
<p>✅ Blockchain Verified</p>
<a href={`https://polygonscan.com/tx/${txHash}`} target="_blank">
View Transaction
</a>
</div>
)}
</div>
)}
</div>
);
}
export default AIChat;Next.js API Route
Server-side API route with environment variable for API key
// Next.js API route example
// app/api/chat/route.js
export async function POST(request) {
try {
const { message } = await request.json();
// Step 1: Call OpenAI directly
const aiResponse = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [{ role: 'user', content: message }]
})
});
const aiData = await aiResponse.json();
const aiMessage = aiData.choices[0].message.content;
// Step 2: Log to Quiet Stack blockchain
const auditResponse = await fetch('https://api.quietstack.ai/api/v1/audit/log', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.QUIETSTACK_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
context: {
request_id: 'req-' + Date.now(),
model_provider: 'openai',
model_name: 'gpt-3.5-turbo',
prompt: message,
response: aiMessage,
token_usage: aiData.usage,
timestamp: new Date().toISOString()
}
})
});
const audit = await auditResponse.json();
return Response.json({
response: aiMessage,
blockchainTx: audit.transaction_hash,
auditId: audit.audit_id
});
} catch (error) {
console.error('Error:', error);
return Response.json({ error: 'Failed to process request' }, { status: 500 });
}
}Environment Setup
Keep your API key secure using environment variables
1. Create .env file:
QUIETSTACK_API_KEY=qs_live_your_actual_api_key_here2. Use in your code:
const apiKey = process.env.QUIETSTACK_API_KEY;Ready to try it out?
Get your API key and test these examples in our playground