Integrating the Keyless API into Your Browser Workflow

Creating a browser extension that drafts content using an API offers a distinct advantage: you keep your context within the browser’s secure environment while offloading the heavy lifting to a remote model. This approach allows you to maintain a lightweight client that can react to page changes, select text, or capture sidebar input without requiring a full desktop application or complex server infrastructure.
The core challenge lies in managing state and context efficiently. Unlike a desktop app, a browser extension has limited memory and must handle intermittent connectivity gracefully. By designing an extension that sends only relevant diffs or structured prompts, you can reduce token usage and latency, ensuring that the drafting experience feels responsive even on slower connections.
However, not every API endpoint is suitable for this workflow. The free tier’s keyless access simplifies authentication but introduces specific rate limits and usage constraints that must be respected. Understanding these boundaries allows you to build an extension that remains reliable over time, avoiding sudden interruptions during critical drafting sessions.
This guide walks you through the process of building such an extension, from setting up the manifest to handling streaming responses and managing context. You will learn how to balance speed and accuracy, optimize token usage, and ensure that your extension respects the API’s policies while delivering a seamless user experience.
Frequently asked questions
What is a browser extension for API drafting?
A browser extension is a small software program that modifies or enhances your web browser’s behavior. When integrated with an API, it can send text selections, page content, or sidebar inputs to a model for drafting, summarizing, or rewriting. This allows you to generate content directly within your browsing context without switching to a separate application.
How does a browser extension differ from a desktop app?
A browser extension runs within the browser’s sandbox, sharing its memory and context but limited by its scope. A desktop app has broader access to system resources and files but requires installation and management. Extensions are lighter and faster to deploy, while desktop apps offer more robust state management and offline capabilities.
Which is better for drafting: a browser extension or a CLI tool?
Browser extensions excel at context-aware drafting, allowing you to send page content or selections instantly. CLI tools are better for batch processing and complex scripting workflows. If your goal is to draft content directly within your browsing context with minimal setup, an extension is superior. For deep, multi-file projects, a CLI tool may be more efficient.
What is the free tier API?
The free tier API is a keyless, OpenAI-compatible endpoint that allows you to send requests without an API key. It is designed for lightweight usage with specific rate limits and token caps. It is not affiliated with Google, despite the domain name, and offers a simple way to integrate AI drafting into your browser without managing credentials.
How does context loss affect drafting in extensions?
Context loss occurs when the extension fails to retain previous conversation history or page state, leading to disjointed drafts. This can happen if the extension clears its local storage too aggressively or if the API session resets unexpectedly. Proper context management ensures that drafts remain coherent and relevant to the user’s current task.
What are the rate limits for the free tier API?
The free tier API allows one request per second, with bursts of up to three, and supports two parallel connections. Daily limits are set at 10,000 requests or 10 million tokens, resetting at midnight UTC. Exceeding these limits results in a 429 status code, while a 503 indicates the service is busy.
How can I optimize token usage in an extension?
Token usage can be optimized by sending only relevant diffs, using structured prompts, and limiting context length. You can also use techniques like anchor files to preserve context without resending large amounts of data. Monitoring token usage helps you stay within daily limits and ensures that your extension remains cost-effective.
What is the difference between streaming and non-streaming responses?
Streaming responses send data in chunks as they are generated, allowing for real-time updates in the UI. Non-streaming responses wait for the entire content to be generated before sending it back. Streaming is better for user experience, as it provides immediate feedback, while non-streaming is simpler to implement and debug.
Step by step
- Create Manifest — Define permissions and scripts in manifest.json to enable API access and background processing.
- Integrate API — Send requests to the free tier API endpoint, handling streaming responses for real-time updates.
- Manage Context — Use local storage to save context and state, ensuring coherent drafts across sessions.
- Optimize Tokens — Send diffs and use structured prompts to reduce token usage and stay within daily limits.
- Design UI — Create a popup interface for drafting, editing, and saving content directly in the browser.
Setting Up the Extension Manifest
The manifest file is the foundation of any browser extension, defining its permissions, scripts, and behavior. For an API-driven drafting tool, you need to declare permissions for fetching data from the API endpoint and accessing the current page’s content. This ensures that your extension can interact with the browser’s DOM and send requests to the API without being blocked by security policies.
Start by creating a manifest.json file with the necessary permissions. You will need access to the active tab to read page content, and permissions to make network requests to the API endpoint. Additionally, you should declare any background scripts or popup interfaces that your extension will use. This setup ensures that your extension has the necessary permissions to function correctly.
Defining Permissions
Permissions in the manifest control what your extension can access. For an API drafting tool, you need access to the active tab to read page content, and permissions to make network requests to the API endpoint. This ensures that your extension can interact with the browser’s DOM and send requests to the API without being blocked by security policies.
Configuring Background Scripts
Background scripts run independently of the user interface and can handle long-running tasks like API requests. They are essential for managing state and ensuring that your extension remains responsive even when the user is interacting with other tabs. Configure your background script to handle API responses and update the UI accordingly.
{
"manifest_version": 3,
"name": "API Drafting Extension",
"version": "1.0",
"permissions": ["activeTab", "storage"],
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html"
}
}Integrating the API Endpoint
Integrating the API endpoint involves sending requests to the free tier API and handling responses. The API is keyless, meaning you do not need to manage API keys, which simplifies the integration process. However, you must ensure that your requests comply with the rate limits and token caps to avoid interruptions.
Use the POST /v1/chat/completions endpoint to send text selections or page content to the model. The API supports streaming responses, which allow you to update the UI in real-time as content is generated. This provides a smoother user experience, as users can see the draft being created rather than waiting for the entire response to complete.
Sending Requests
Sending requests to the API involves constructing a payload with the user’s input and any relevant context. The payload should include the message content, model name, and any additional parameters like max_tokens or stream. Ensure that your requests include a valid User-Agent header to avoid being blocked by the API’s security policies.
Handling Responses
Responses from the API can be handled using streaming or non-streaming methods. Streaming responses allow you to update the UI in real-time, providing immediate feedback to the user. Non-streaming responses are simpler to implement but may result in longer wait times. Choose the method that best fits your user experience goals.
fetch('https://api.geminifreetierapi.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0'
},
body: JSON.stringify({
model: 'free-ai',
messages: [{ role: 'user', content: 'Draft a summary' }],
stream: true
})
})
Managing Context and State
Context management is crucial for maintaining coherent drafts, especially when the user switches between different pages or tabs. Browser extensions have limited memory, so it is important to store context efficiently and avoid retaining unnecessary data. Use local storage or session storage to save context between requests, ensuring that the extension remains lightweight.
Implement a context management system that tracks the user’s current task and relevant page content. This allows the extension to send only the necessary information to the API, reducing token usage and improving response times. Consider using anchor files to preserve context without resending large amounts of data.
Using Local Storage
Local storage allows you to persist data across browser sessions, ensuring that context is retained even if the user closes the extension. Use local storage to save context, user preferences, and draft history. This ensures that the extension can resume where the user left off, providing a seamless experience.
Handling Context Loss
Context loss can occur if the extension clears its storage too aggressively or if the API session resets. To prevent this, implement a robust context management system that saves state regularly and handles errors gracefully. This ensures that drafts remain coherent and relevant to the user’s current task.
chrome.storage.local.set({
context: {
lastDraft: 'Sample draft text',
pageUrl: 'https://example.com'
}
});
chrome.storage.local.get(['context'], (data) => {
console.log(data.context);
});Optimizing Token Usage
Token usage is a critical factor in managing API costs and ensuring that your extension stays within daily limits. By sending only relevant content and using structured prompts, you can reduce the number of tokens consumed per request. This is particularly important for extensions that send large amounts of page content or context to the API.
Implement token optimization techniques such as sending diffs instead of full page content, using concise prompts, and limiting context length. Monitor token usage to ensure that your extension remains within the daily limits of 10,000 requests or 10 million tokens. This helps you avoid interruptions and ensures that your extension remains reliable.
Sending Diffs
Sending diffs instead of full page content reduces the number of tokens consumed per request. This is particularly useful when the user is editing a document or making small changes to a page. By sending only the changes, you can reduce token usage and improve response times.
Monitoring Usage
Monitor token usage to ensure that your extension stays within daily limits. Track the number of requests and tokens consumed, and alert the user if they are approaching their limit. This helps you manage usage and avoid interruptions during critical drafting sessions.
let tokenCount = 0;
function updateTokenCount(count) {
tokenCount += count;
if (tokenCount > 10000) {
alert('Token limit approaching');
}
}
Implementing Streaming Responses
Streaming responses allow you to update the UI in real-time as content is generated, providing a smoother user experience. Instead of waiting for the entire response to complete, you can display content as it becomes available. This is particularly useful for long drafts, where users may lose interest if they have to wait too long for the response.
Using EventSource
EventSource is a browser API that allows you to receive server-sent events (SSE) from the API. This enables you to handle streaming responses and update the UI in real-time. Use EventSource to listen for incoming data chunks and update the draft as they arrive.
Handling Errors
Errors in streaming responses can occur due to network issues or API limits. Implement error handling to retry requests or notify the user if the stream is interrupted. This ensures that the extension remains robust and provides a seamless experience even when connectivity is unstable.
const eventSource = new EventSource('https://api.geminifreetierapi.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'free-ai',
messages: [{ role: 'user', content: 'Draft a summary' }],
stream: true
})
});
eventSource.onmessage = (event) => {
console.log(event.data);
};
eventSource.onerror = (error) => {
console.error('Error:', error);
};Designing the User Interface
The user interface of your extension should be intuitive and easy to use, allowing users to draft content seamlessly. Design a popup interface that displays the draft, allows the user to edit it, and provides options to save or discard changes. Ensure that the UI is responsive and adapts to different screen sizes.
Creating a Popup Interface
A popup interface is the primary way users interact with your extension. Design it to display the draft, allow editing, and provide options to save or discard changes. Use HTML and CSS to create a clean, responsive layout that is easy to navigate.
Adding Input Fields
Input fields allow users to provide context or instructions for the draft. Include fields for text selection, page URL, or custom prompts. Ensure that the input fields are clearly labeled and easy to use, providing a smooth drafting experience.
<div id="popup">
<textarea id="draft" placeholder="Draft will appear here..."></textarea>
<button id="save">Save Draft</button>
<button id="discard">Discard</button>
</div>
Handling Rate Limits and Errors
Rate limits and errors are common when using the free tier API. Understanding how to handle these ensures that your extension remains reliable and provides a good user experience. Implement retry logic to handle 429 and 503 errors, and notify the user if the API is busy or if they have exceeded their limits.
Retrying Requests
Retry logic allows your extension to handle transient errors and rate limits gracefully. Implement exponential backoff to retry requests after a 429 or 503 error, ensuring that the extension remains responsive even when the API is busy.
Notifying Users
Notify users if they have exceeded their rate limits or if the API is busy. Use clear messages to inform them of the issue and provide options to retry or wait. This ensures that users are aware of the status and can adjust their expectations accordingly.
async function fetchWithRetry(url, options, retries = 3) {
try {
const response = await fetch(url, options);
if (response.status === 429 || response.status === 503) {
await new Promise(resolve => setTimeout(resolve, 2000));
return fetchWithRetry(url, options, retries - 1);
}
return response;
} catch (error) {
console.error('Error:', error);
}
}Testing and Debugging
Testing and debugging are essential steps in ensuring that your extension works as expected. Use browser developer tools to inspect network requests, check for errors, and monitor token usage. Test your extension with different inputs and scenarios to ensure that it handles edge cases gracefully.
Using Developer Tools
Browser developer tools allow you to inspect network requests, check for errors, and monitor performance. Use the Network tab to view API requests and responses, and the Console tab to log errors and debug issues.
Testing Edge Cases
Test your extension with different inputs, such as long text selections, empty inputs, and rapid requests. Ensure that your extension handles these scenarios gracefully and provides a consistent user experience.
console.log('Testing API integration...');
fetch('https://api.geminifreetierapi.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'free-ai',
messages: [{ role: 'user', content: 'Test' }]
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Start drafting content instantly with our keyless API endpoint, no credit card required.