Implement Puter Auth: To begin using Puter.js, simply add it to your HTML file using the following script tag either in the <head> or <body> of your HTML file: <script src="https://js.puter.com/v2/"></script> That's it! You're now ready to start using Puter.js in your web application. No need to install any dependencies or set up a server. No API keys or configuration required. Example 1Add GPT-4o to your web application Once you've added the Puter.js script to your web application, a global puter object will be available for you to use. This object contains all of the functionality provided by Puter.js. For example, to use GPT-4o mini, you can call the puter.ai.chat function: <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.ai.chat(`Why did the chicken cross the road?`).then(puter.print); </script> </body> </html> In this example, we're using the puter.ai.chat function to generate text with GPT-4o. The generated text is then printed to the console using the puter.print function. You can replace the input text with any prompt you'd like to generate text for. Example 2Add cloud storage to your web application Let's try another example, this time using cloud storage to write and read a file: <html> <body> <script src="https://js.puter.com/v2/"></script> <script> async function fileDemo() { // Write a file await puter.fs.write('hello.txt', 'Hello, Puter!'); puter.print('File written successfully<br>'); // Read the file const fileContent = await puter.fs.read('hello.txt'); puter.print('File content: ', await fileContent.text(), '<br>'); } fileDemo(); </script> </body> </html> In this example, we're using the puter.fs.write function to write a file to the cloud storage. We then use the puter.fs.read function to read the file and print its content to the console. You can replace the file name and content with your own data. Example 3Cloud Key-Value Store Let's use Puter.js to store and retrieve data from the cloud key-value store. In this example, we'll save a user preference to the cloud and then retrieve it: <html> <body> <script src="https://js.puter.com/v2/"></script> <script> async function kvDemo() { // Set a value await puter.kv.set('user_preference', 'dark_mode'); puter.print('Preference saved<br>'); // Get the value const preference = await puter.kv.get('user_preference'); puter.print('User preference:', preference, '<br>'); } kvDemo(); </script> </body> </html> In this example, we're using the puter.kv.set function to save a user preference to the cloud key-value store. We then use the puter.kv.get function to retrieve the preference and print it to the console. You can replace the key and value with your own data. Example 4Authentication Puter.js handles authentication automatically. When your code tries to access any cloud services, the user will be prompted to sign in with their Puter.com account if they haven't already. You can build your app as if the user is already signed in, and Puter.js will handle the authentication process for you when needed. If you want to explicitly check if a user is signed in or trigger the sign-in process, you can use the following methods: <html> <body> <script src="https://js.puter.com/v2/"></script> <script> async function authDemo() { // Check if user is signed in const isSignedIn = puter.auth.isSignedIn(); puter.print('Is user signed in? ', isSignedIn, '<br>'); if (!isSignedIn) { // Trigger sign-in process await puter.auth.signIn(); puter.print('User signed in successfully<br>'); } // Get user info const user = await puter.auth.getUser(); puter.print('User info:', JSON.stringify(user)); } authDemo(); </script> </body> </html> This is all you need to use GPT-4o mini in your app. No backend code, no configuration, and no API keys. Just include the Puter.js script, and you're ready to start. Puter.js offers many more features, including hosting static websites, generating images with DALL-E 3, and more. Explore the Puter.js documentation to discover all the possibilities and start building powerful, serverless web applications with ease! Remember, Puter.js is designed to be simple and straightforward, allowing you to focus on building your application without worrying about backend infrastructure or complex setups. Happy coding! - Example 1Basic Text Generation with Claude Sonnet 4 To generate text using Claude, use the puter.ai.chat() function with your preferred model. Here's a full code example using Claude Sonnet 4: <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.ai.chat("Explain quantum computing in simple terms", {model: 'claude-sonnet-4'}) .then(response => { puter.print(response.message.content[0].text); }); </script> </body> </html> Example 2Streaming Responses for Longer Queries For longer responses, use streaming to get results in real-time: async function streamClaudeResponse(model = 'claude-sonnet-4') { const response = await puter.ai.chat( "Write a detailed essay on the impact of artificial intelligence on society", {model: model, stream: true} ); for await (const part of response) { puter.print(part?.text); } } // Use Claude Sonnet 4 (default) streamClaudeResponse(); Here's the full code example with streaming: <html> <body> <script src="https://js.puter.com/v2/"></script> <script> (async () => { const response = await puter.ai.chat( "Write a detailed essay on the impact of artificial intelligence on society", {model: 'claude-opus-4', stream: true} ); for await (const part of response) { puter.print(part?.text); } })(); </script> </body> </html> Example 3Using different Claude models You can specify different Claude models using the model parameter, for example claude-sonnet-4 or claude-opus-4: // Using claude-sonnet-4 model puter.ai.chat( "Write a short poem about coding", { model: "claude-sonnet-4" } ).then(response => { puter.print(response); }); // Using claude-opus-4 model puter.ai.chat( "Write a short poem about coding", { model: "claude-opus-4" } ).then(response => { puter.print(response); }); Full code example: <html> <body> <script src="https://js.puter.com/v2/"></script> <script> // Using claude-sonnet-4 model puter.ai.chat( "Write a short poem about coding", { model: "claude-sonnet-4" } ).then(response => { puter.print("<h2>Using claude-sonnet-4 model</h2>"); puter.print(response); }); // Using claude-opus-4 model puter.ai.chat( "Write a short poem about coding", { model: "claude-opus-4" } ).then(response => { puter.print("<h2>Using claude-opus-4 model</h2>"); puter.print(response); }); </script> </body> </html> \\\----- Example 1Use GPT-4.1 nano for text generation To generate text using GPT-4.1 nano, use the puter.ai.chat() function: puter.ai.chat("What are the benefits of exercise?", { model: "gpt-4.1-nano" }) .then(response => { puter.print(response); }); Full code example: <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.ai.chat("What are the benefits of exercise?", { model: "gpt-4.1-nano" }) .then(response => { puter.print(response); }); </script> </body> </html> Example 4Use different OpenAI models You can specify different OpenAI models using the model parameter, for example gpt-4.1, o3-mini, o1-mini, or gpt-4o: // Using gpt-4.1 model puter.ai.chat( "Write a short poem about coding", { model: "gpt-4.1" } ).then(response => { puter.print(response); }); // Using o3-mini model puter.ai.chat( "Write a short poem about coding", { model: "o3-mini" } ).then(response => { puter.print(response); }); // Using o1-mini model puter.ai.chat( "Write a short poem about coding", { model: "o1-mini" } ).then(response => { puter.print(response); }); // Using 4o model puter.ai.chat( "Write a short poem about coding", { model: "gpt-4o" } ).then(response => { puter.print(response); }); Full code example: <html> <body> <script src="https://js.puter.com/v2/"></script> <script> // Using gpt-4.1 model puter.ai.chat( "Write a short poem about coding", { model: "gpt-4.1" } ).then(response => { puter.print("<h2>Using gpt-4.1 model</h2>"); puter.print(response); }); // Using o3-mini model puter.ai.chat( "Write a short poem about coding", { model: "o3-mini" } ).then(response => { puter.print("<h2>Using o3-mini model</h2>"); puter.print(response); }); // Using o1-mini model puter.ai.chat( "Write a short poem about coding", { model: "o1-mini" } ).then(response => { puter.print("<h2>Using o1-mini model</h2>"); puter.print(response); }); // Using 4o model puter.ai.chat( "Write a short poem about coding", { model: "gpt-4o" } ).then(response => { puter.print("<h2>Using gpt-4o model</h2>"); puter.print(response); }); </script> </body> </html> Example 5Stream responses for longer queries For longer responses, use streaming to get results in real-time: async function streamResponse() { const response = await puter.ai.chat( "Explain the theory of relativity in detail", {stream: true} ); for await (const part of response) { puter.print(part?.text); } } streamResponse(); Full code example: <html> <body> <script src="https://js.puter.com/v2/"></script> <script> async function streamResponse() { const response = await puter.ai.chat( "Explain the theory of relativity in detail", {stream: true} ); for await (const part of response) { puter.print(part?.text); } } streamResponse(); </script> </body> </html> \\--- 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 3Interactive Q&A interface Here's how to create an engaging Q&A interface using Grok 4: <html> <body> <div style="max-width: 800px; margin: 20px auto; font-family: Arial, sans-serif;"> <h1>Ask Grok Anything</h1> <div id="chat-container" style="margin: 20px 0;"> <div id="messages" style="height: 400px; border: 1px solid #ccc; overflow-y: auto; padding: 20px; margin-bottom: 20px; border-radius: 8px;"></div> <div style="display: flex; gap: 10px;"> <input type="text" id="user-input" style="flex-grow: 1; padding: 10px; border: 1px solid #ccc; border-radius: 4px;" placeholder="Ask me anything..."> <button onclick="askQuestion()" style="padding: 10px 20px; background: #0066cc; color: white; border: none; border-radius: 4px; cursor: pointer;"> Ask </button> </div> </div> </div> <script src="https://js.puter.com/v2/"></script> <script> const messagesDiv = document.getElementById('messages'); const userInput = document.getElementById('user-input'); async function askQuestion() { const question = userInput.value; if (!question) return; // Add user question messagesDiv.innerHTML += ` <div style="margin-bottom: 15px;"> <strong style="color: #0066cc;">You:</strong><br> ${question} </div> `; userInput.value = ''; messagesDiv.scrollTop = messagesDiv.scrollHeight; // Add Grok's response container const responseContainer = document.createElement('div'); responseContainer.style.marginBottom = '15px'; responseContainer.innerHTML = ` <strong style="color: #009933;">Grok:</strong><br> <span></span> `; messagesDiv.appendChild(responseContainer); const responseSpan = responseContainer.querySelector('span'); // Get streaming response from Grok const response = await puter.ai.chat(question, { model: 'x-ai/grok-4', stream: true }); for await (const part of response) { responseSpan.innerHTML += part.text; messagesDiv.scrollTop = messagesDiv.scrollHeight; } } // Allow sending message with Enter key userInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') askQuestion(); }); // Add initial greeting window.onload = () => { messagesDiv.innerHTML = ` <div style="margin-bottom: 15px;"> <strong style="color: #009933;">Grok:</strong><br> Hi there! I'm Grok, your witty AI assistant. I'm here to help you with anything you'd like to know about. What's on your mind? </div> `; }; </script> </body> </html> Example 4Multi-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 5Using Grok for creative writing Grok is particularly good at creative and engaging writing. Here's an example of using it for story generation: <html> <body> <div style="max-width: 800px; margin: 20px auto; font-family: Arial, sans-serif;"> <h1>Story Generator</h1> <div style="margin: 20px 0;"> <h3>Story Parameters</h3> <input type="text" id="genre" placeholder="Genre (e.g., sci-fi, fantasy)" style="width: 100%; margin-bottom: 10px; padding: 5px;"> <input type="text" id="theme" placeholder="Theme (e.g., friendship, adventure)" style="width: 100%; margin-bottom: 10px; padding: 5px;"> <input type="text" id="setting" placeholder="Setting (e.g., space station, medieval castle)" style="width: 100%; margin-bottom: 10px; padding: 5px;"> <button onclick="generateStory()" style="padding: 10px 20px;">Generate Story</button> </div> <div id="story" style="white-space: pre-wrap; line-height: 1.6;"></div> </div> <script src="https://js.puter.com/v2/"></script> <script> async function generateStory() { const genre = document.getElementById('genre').value || 'sci-fi'; const theme = document.getElementById('theme').value || 'adventure'; const setting = document.getElementById('setting').value || 'space station'; const prompt = ` Write a short story with the following parameters: - Genre: ${genre} - Theme: ${theme} - Setting: ${setting} Make it engaging, witty, and memorable. Include some clever dialogue and unexpected twists.`; const storyDiv = document.getElementById('story'); storyDiv.innerHTML = 'Generating your story...'; const response = await puter.ai.chat(prompt, { model: 'x-ai/grok-4 stream: true }); storyDiv.innerHTML = ''; for await (const part of response) { storyDiv.innerHTML += part.text; } } </script> </body> </html> \\--- Getting Started Puter.js is completely serverless and works without any API keys or sign-ups. To start using Puter.js, simply include the following script tag in your HTML file: <script src="https://js.puter.com/v2/"></script> That's it! You're now ready to use Puter.js for free access to all major AI models in your website or app. No API keys, backend setup, or server-side code required. OpenAI Models To integrate AI models into your website or app, use the puter.ai.chat() function and specify the model name in the model parameter. Here's an example of how to use the OpenAI's GPT-4.1 Nano model: puter.ai.chat("What are the benefits of exercise?", { model: "gpt-4.1-nano" }) .then(response => { puter.print(response); }); Full code example: <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.ai.chat("What are the benefits of exercise?", { model: "gpt-4.1-nano" }) .then(response => { puter.print(response); }); </script> </body> </html> As you can see, the experience is completely serverless and doesn't require any API keys or backend setup. Claude Models Puter.js is not limited to OpenAI models. You can use any major AI model by specifying the model name in the model parameter. Here's an example of how to use the Claude Sonnet 4 model: <html> <body> <script src="https://js.puter.com/v2/"></script> <script> // Claude Sonnet 4 puter.ai.chat( "Write a creative short story about a time traveler", { model: "claude-sonnet-4" } ).then(response => { puter.print(response.message.content[0].text); }); </script> </body> </html> Google Gemini Models Leverage Google's Gemini models for various AI tasks: <html> <body> <script src="https://js.puter.com/v2/"></script> <script> puter.ai.chat( "Create a meal plan for a healthy week", { model: "google/gemini-2.5-flash" } ).then(response => { puter.print(response.message.content); }); </script> </body> </html> Other Models From open-source to commercial, Puter supports more than 400 AI models. You can use any of them by specifying the model name in the model parameter. The full list of models is available here. Advanced Features Streaming Responses For better user experience with longer content, use streaming to display responses in real-time: <html> <body> <div id="streamOutput"></div> <script src="https://js.puter.com/v2/"></script> <script> async function streamExample() { const outputDiv = document.getElementById('streamOutput'); outputDiv.innerHTML = '<h2>AI Streaming Response Demo</h2>'; // Stream from GPT-4.1 Nano const response = await puter.ai.chat( "Write a detailed essay about the future of renewable energy", { model: "gpt-4.1-nano", stream: true } ); // Print the response in real-time for await (const part of response) { if (part?.text) { outputDiv.innerHTML += part.text; } } } streamExample(); </script> </body> </html> Image Analysis You are not limited to text generation. You can also analyze images using AI. In the example below, we're using GPT-4.1 Nano to analyze an image and then ask follow-up questions. All you have to do is pass the image URL to the puter.ai.chat() function: <html> <body> <h1>AI Image Analysis</h1> <input type="text" id="imageUrl" placeholder="Enter image URL..." style="width: 400px; padding: 5px;"> <button onclick="analyzeImage()">Analyze Image</button> <div id="analysis"></div> <script src="https://js.puter.com/v2/"></script> <script> async function analyzeImage() { const imageUrl = document.getElementById('imageUrl').value; if (!imageUrl) return; const analysisDiv = document.getElementById('analysis'); analysisDiv.innerHTML = '<p>Analyzing image...</p>'; // Display the image analysisDiv.innerHTML = `<img src="${imageUrl}" style="max-width: 400px; margin: 10px 0;"><br>`; // Get AI analysis const response = await puter.ai.chat( "Describe this image in detail. What objects, people, or scenes do you see?", imageUrl ); analysisDiv.innerHTML += `<h3>Analysis:</h3><p>${response}</p>`; } // Example with default image window.onload = () => { document.getElementById('imageUrl').value = 'https://assets.puter.site/doge.jpeg'; }; </script> </body> </html> Function Calling (a.k.a. "Tool Calling" or "Agentic AI") Function calling allows AI models to call functions in your application, enabling them to perform actions, access real-time data, and interact with external systems. This transforms static AI responses into dynamic, interactive experiences. With Puter.js, you can define functions that the AI can call, and the AI will intelligently decide when and how to use them based on the user's request. This is perfect for creating chatbots, virtual assistants, and interactive applications. Here's a simple example showing how to create a weather assistant that can fetch weather data: <html> <body> <input type="text" id="userInput" placeholder="Ask about the weather..." style="width: 400px; padding: 10px; margin: 10px 0;"> <button onclick="askWeather()">Ask</button> <div id="response" style="margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 5px;"></div> <script src="https://js.puter.com/v2/"></script> <script> // Mock weather function - in a real app, this would call a weather API function getWeather(location) { const weatherData = { 'Paris': { temp: '22°C', condition: 'Partly Cloudy', humidity: '65%' }, 'London': { temp: '18°C', condition: 'Rainy', humidity: '80%' }, 'New York': { temp: '25°C', condition: 'Sunny', humidity: '45%' }, 'Tokyo': { temp: '28°C', condition: 'Clear', humidity: '70%' } }; const weather = weatherData[location] || { temp: '20°C', condition: 'Unknown', humidity: '50%' }; return JSON.stringify(weather); } // Define the functions available to the AI 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: "City name (e.g., Paris, London, New York)" } }, required: ["location"], additionalProperties: false }, strict: true } }]; async function askWeather() { const userInput = document.getElementById('userInput').value; const responseDiv = document.getElementById('response'); if (!userInput) return; responseDiv.innerHTML = 'Processing...'; try { // First, get the AI's response with potential function calls const completion = await puter.ai.chat(userInput, { tools }); // Check if the AI wants to call a function if (completion.message.tool_calls && completion.message.tool_calls.length > 0) { const toolCall = completion.message.tool_calls[0]; if (toolCall.function.name === 'get_weather') { // Parse the arguments and call our weather function const args = JSON.parse(toolCall.function.arguments); const weatherResult = getWeather(args.location); // Send the function result back to the AI for a natural response const finalResponse = await puter.ai.chat([ { role: "user", content: userInput }, completion.message, { role: "tool", tool_call_id: toolCall.id, content: weatherResult } ]); responseDiv.innerHTML = `<strong>Weather Assistant:</strong><br>${finalResponse}`; } } else { // No function call needed, just show the response responseDiv.innerHTML = `<strong>Assistant:</strong><br>${completion}`; } } catch (error) { responseDiv.innerHTML = `<strong>Error:</strong> ${error.message}`; } } </script> </body> </html> That's it! You now have access to all major AI models through a single, simple interface. With Puter.js, you can build powerful AI applications without worrying about API keys, rate limits, or backend infrastructure. The future of AI development is serverless, and it's available to you right now - completely free. - Follow Up Deployment
verified