Tutorials
Free, Unlimited Grok API
Grok is xAI's latest large language model, known for its unique approach to problem-solving and witty responses. In this tutorial, we'll show you how to use Grok through Puter.js to create engaging and intelligent applications.
Puter is the pioneer of the "User Pays" model, which allows developers to incorporate AI capabilities into their applications while each user will cover their own usage costs. This model enables developers to access advanced AI capabilities for free, without any API keys, usage costs, or server-side setup.
Prerequisites
Just include the Puter.js library in your HTML file:
<script src="https://js.puter.com/v2/"></script>
Example 1Use Grok 4
To use Grok 4, you'll use the puter.ai.chat()
function with the model
parameter set to x-ai/grok-4
. Here's a basic example:
<html>
<body>
<script src="https://js.puter.com/v2/"></script>
<script>
// Chat with Grok 4
puter.ai.chat(
"Explain quantum computing in a witty and engaging way.",
{model: 'x-ai/grok-4'}
).then(response => {
puter.print(response.message.content);
});
</script>
</body>
</html>
Example 2Streaming responses
For a more interactive experience, you can stream the responses from Grok as they're generated:
<html>
<body>
<script src="https://js.puter.com/v2/"></script>
<script>
(async () => {
const response = await puter.ai.chat(
"Tell me a funny story about artificial intelligence.",
{
model: 'x-ai/grok-4',
stream: true
}
);
for await (const part of response) {
puter.print(part.text);
}
})();
</script>
</body>
</html>
Example 3Multi-turn conversations
Grok excels at maintaining context in conversations. Here's how to implement a context-aware chat:
<html>
<body>
<script src="https://js.puter.com/v2/"></script>
<script>
// Keep track of conversation history
let conversationHistory = [];
async function continueConversation(userMessage) {
// Add user message to history
conversationHistory.push({
role: "user",
content: userMessage
});
// Get response from Grok
const response = await puter.ai.chat(conversationHistory, {
model: 'x-ai/grok-4'
});
// Add Grok's response to history
conversationHistory.push({
role: "assistant",
content: response.message.content
});
return response.message.content;
}
// Example usage
async function demonstrateConversation() {
let response;
response = await continueConversation("What's the most interesting thing about space?");
document.body.innerHTML += `<p><strong>You:</strong> What's the most interesting thing about space?</p>`;
document.body.innerHTML += `<p><strong>Grok:</strong> ${response}</p>`;
response = await continueConversation("Tell me more about that!");
document.body.innerHTML += `<p><strong>You:</strong> Tell me more about that!</p>`;
document.body.innerHTML += `<p><strong>Grok:</strong> ${response}</p>`;
}
demonstrateConversation();
</script>
</body>
</html>
Example 4Using Temperature and Max Tokens
You can control Grok's response characteristics using the temperature
and max_tokens
parameters:
<html>
<body>
<script src="https://js.puter.com/v2/"></script>
<script>
(async () => {
// Low temperature (more focused, deterministic)
puter.print("<h3>Low Temperature (0.1):</h3>");
const focusedResponse = await puter.ai.chat("Tell me about cats.", {
model: 'x-ai/grok-4',
temperature: 0.1,
max_tokens: 50
});
puter.print(focusedResponse.message.content[0].text + "<br><br>");
// High temperature (more creative, random)
puter.print("<h3>High Temperature (1.8):</h3>");
const creativeResponse = await puter.ai.chat("Tell me about cats.", {
model: 'x-ai/grok-4',
temperature: 0.8,
max_tokens: 50
});
puter.print(creativeResponse.message.content[0].text + "<br><br>");
// Different max_tokens
puter.print("<h3>Short Response (max_tokens: 20):</h3>");
const shortResponse = await puter.ai.chat("Explain quantum physics.", {
model: 'x-ai/grok-4',
max_tokens: 20
});
puter.print(shortResponse.message.content[0].text);
})();
</script>
</body>
</html>
Example 5Function/Tool Calling with Grok
Grok can call functions to interact with external systems or perform specific tasks:
<html>
<body>
<div style="max-width: 800px; margin: 20px auto; font-family: Arial, sans-serif;">
<h1>Grok Function Calling Demo</h1>
<div style="margin: 20px 0;">
<input type="text" id="user-input"
value="What's the weather like in New York? Also, what time is it there?"
style="width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 4px; margin-bottom: 10px;"
placeholder="Ask about weather or time...">
<button onclick="handleQuery()"
style="padding: 10px 20px; background: #0066cc; color: white; border: none; border-radius: 4px; cursor: pointer;">
Ask Grok
</button>
</div>
<div id="response" style="margin-top: 20px; padding: 15px; background: #f5f5f5; border-radius: 4px;">
Responses will appear here...
</div>
</div>
<script src="https://js.puter.com/v2/"></script>
<script>
// Mock functions that Grok can call
function getWeather(location) {
const weatherData = {
'New York': { temp: '72°F', condition: 'Partly cloudy', humidity: '65%' },
'London': { temp: '18°C', condition: 'Rainy', humidity: '80%' },
'Tokyo': { temp: '28°C', condition: 'Sunny', humidity: '70%' },
'Paris': { temp: '22°C', condition: 'Clear', humidity: '55%' }
};
return weatherData[location] || { temp: 'Unknown', condition: 'Data not available', humidity: 'Unknown' };
}
function getCurrentTime(location) {
const timeData = {
'New York': '2:30 PM EST',
'London': '7:30 PM GMT',
'Tokyo': '3:30 AM JST',
'Paris': '8:30 PM CET'
};
return timeData[location] || 'Time data not available';
}
// Define the tools/functions available to Grok
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "Get current weather information for a specific location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city name (e.g., New York, London, Tokyo, Paris)"
}
},
required: ["location"]
}
}
},
{
type: "function",
function: {
name: "get_current_time",
description: "Get the current time for a specific location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city name (e.g., New York, London, Tokyo, Paris)"
}
},
required: ["location"]
}
}
}
];
async function handleQuery() {
const userInput = document.getElementById('user-input').value;
const responseDiv = document.getElementById('response');
if (!userInput.trim()) return;
responseDiv.innerHTML = 'Processing your request...';
try {
// First, send the query to Grok with available tools
const completion = await puter.ai.chat(userInput, {
model: 'x-ai/grok-4',
tools: tools
});
let finalResponse = completion;
// Check if Grok wants to call any functions
if (completion.message.tool_calls && completion.message.tool_calls.length > 0) {
const messages = [
{ role: "user", content: userInput },
completion.message
];
// Execute each function call
for (const toolCall of completion.message.tool_calls) {
let functionResult;
const args = JSON.parse(toolCall.function.arguments);
if (toolCall.function.name === 'get_weather') {
functionResult = getWeather(args.location);
} else if (toolCall.function.name === 'get_current_time') {
functionResult = getCurrentTime(args.location);
}
// Add the function result to the conversation
messages.push({
role: "tool",
tool_call_id: toolCall.id,
content: JSON.stringify(functionResult)
});
}
// Get Grok's final response with the function results
finalResponse = await puter.ai.chat(messages, {
model: 'x-ai/grok-4'
});
}
responseDiv.innerHTML = `
<h4>Grok's Response:</h4>
<p>${finalResponse.message.content.replace(/\n/g, '<br>')}</p>
`;
} catch (error) {
responseDiv.innerHTML = `<strong>Error:</strong> ${error.message}`;
}
}
// Allow Enter key to submit
document.getElementById('user-input').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
handleQuery();
}
});
</script>
</body>
</html>
Example 6Using Grok for Image Analysis
Grok can analyze images and provide insights:
<html>
<body>
<script src="https://js.puter.com/v2/"></script>
<img src="https://assets.puter.site/doge.jpeg" style="display:block; max-width: 300px; margin-bottom: 20px;">
<script>
puter.ai.chat(
"What do you see in this image?",
"https://assets.puter.site/doge.jpeg",
{ model: "x-ai/grok-4" }
)
.then(response => {
puter.print(response.message.content);
});
</script>
</body>
</html>
Supported Models
The following Grok models are supported through Puter.js:
x-ai/grok-2-1212
x-ai/grok-2-vision-1212
x-ai/grok-3
x-ai/grok-3-beta
x-ai/grok-3-mini
x-ai/grok-3-mini-beta
x-ai/grok-4
x-ai/grok-code-fast-1
x-ai/grok-vision-beta
Grok through Puter.js provides a unique and engaging AI experience, combining technical capability with wit and creativity. Whether you're building a chatbot, a creative writing tool, or any other AI-powered application, Grok can help make it more engaging and fun for users.
Related Resources
Free, Serverless AI and Cloud
Start creating powerful web applications with Puter.js in seconds!
Get Started Now