
Introduction to Polyfire
Building AI-powered applications traditionally requires significant backend infrastructure. Developers must manage model APIs, user authentication, data storage, prompt engineering, and billing systems. Polyfire eliminates this complexity by providing an open-source React library combined with a backend-as-a-service platform. With Polyfire, you can build sophisticated AI applications entirely from the front end, keeping your entire codebase in one place.
Polyfire gives you pre-coded React components, hooks, and a hosted API that handles user management, model routing across 72+ AI models, data services, and prompt engineering tools. Whether you are building a chatbot, a content generator, a semantic search tool, or a personalized recommendation engine, Polyfire lets you focus on user experience rather than backend configuration.
This tutorial will guide you through everything you need to know to start building with Polyfire, from initial setup to advanced features like vector storage and prompt engineering. By the end, you will have a practical understanding of how to integrate AI capabilities into your React applications quickly and efficiently.
Getting Started with Polyfire
Prerequisites
Before you begin, ensure you have the following:
- Node.js version 16 or higher installed on your machine
- npm or yarn package manager
- A basic understanding of React (components, hooks, state management)
- A Polyfire account (sign up at https://polyfire.com/)
Step 1: Create a New React Project
If you do not already have a React project, create one using Vite or Create React App. For this tutorial, we will use Vite for faster development:
Command: npm create vite@latest my-ai-app — –template react
Command: cd my-ai-app
Command: npm install
Step 2: Install Polyfire
Install the Polyfire React library using npm or yarn:
Command: npm install polyfire
This package includes all React hooks, components, and the client SDK for communicating with the Polyfire backend.
Step 3: Set Up Your Polyfire Project
Log in to your Polyfire dashboard at https://polyfire.com/. Create a new project and obtain your API keys. You will need the following:
- Project ID – A unique identifier for your application
- Public API Key – Used for client-side initialization
Store these securely. For development, you can use environment variables in a .env file:
File: .env
VITE_POLYFIRE_PROJECT_ID=your_project_id
VITE_POLYFIRE_PUBLIC_KEY=your_public_key
Step 4: Initialize Polyfire in Your App
Wrap your application with the Polyfire provider to make all hooks and components available throughout your component tree. Open your main.jsx or App.jsx file:
Example: src/main.jsx
import React from ‘react’;
import ReactDOM from ‘react-dom/client’;
import App from ‘./App’;
import { PolyfireProvider } from ‘polyfire’;
ReactDOM.createRoot(document.getElementById(‘root’)).render(
<PolyfireProvider
projectId={import.meta.env.VITE_POLYFIRE_PROJECT_ID}
publicKey={import.meta.env.VITE_POLYFIRE_PUBLIC_KEY}
>
<App />
</PolyfireProvider>
);
The provider handles authentication, API routing, and session management automatically. You are now ready to use any Polyfire feature.
Key Features of Polyfire
1. React Hooks and Components for AI Features
Polyfire provides a set of React hooks that abstract away the complexity of calling AI models. The most important hooks include:
- usePolyfire – Returns the Polyfire client instance and user authentication state
- useChat – Manages conversational AI with streaming responses
- useCompletion – Handles single-turn text generation
- useEmbeddings – Generates vector embeddings from text
- useVectorStore – Manages vector storage and semantic search
These hooks handle loading states, error handling, and streaming automatically, so you can focus on building your UI.
2. Hosted API with Auth, Billing, and Rate Limits
Polyfire manages the entire backend for you. This includes:
- User Authentication – Built-in sign-up, login, and session management. Users can authenticate via email/password or social providers.
- Billing – You can set usage limits and charge users per request or subscription. Polyfire handles payment processing and invoicing.
- Rate Limits – Protect your application from abuse with configurable rate limits per user or per API key.
All of this is configured from the Polyfire dashboard without writing any backend code.
3. Router for 72+ AI Models
Polyfire’s model router lets you access over 72 AI models from a single API. Supported providers include OpenAI (GPT-4, GPT-3.5), Anthropic (Claude), Google (Gemini), Meta (Llama), Mistral, and many open-source models. You can switch models by simply changing a string parameter in your code:
Example: model=”gpt-4″ or model=”claude-3-opus” or model=”llama-3-70b”
Polyfire automatically handles API key management, fallback logic, and model-specific optimizations.
4. Vector Store, Embeddings, and Key-Value Data Service
Polyfire includes a fully managed vector database for semantic search and retrieval-augmented generation (RAG). Features include:
- Embeddings Generation – Convert text into vector embeddings using models like text-embedding-3-small or ada-002
- Vector Search – Query similar documents based on semantic meaning
- Key-Value Store – Store and retrieve structured data (e.g., user preferences, session data) without setting up a database
This allows you to build features like “ask your documents,” personalized recommendations, and memory-augmented chatbots.
5. Prompt Engineering Tools with Logs and Playground
Polyfire provides a built-in playground and logging system for prompt engineering:
- Playground – Test and iterate on prompts in real-time from the dashboard
- Logs – View every API call, including input, output, latency, and cost
- Versioning – Save and compare different prompt versions
This helps you optimize your prompts for quality, cost, and performance without redeploying your application.
How to Use Polyfire: Practical Examples
Example 1: Building a Simple Chatbot
Create a chatbot component using the useChat hook. This hook manages message history and streaming responses.
File: src/components/Chatbot.jsx
import { useChat } from ‘polyfire’;
import { useState } from ‘react’;
export default function Chatbot() {
const { sendMessage, messages, isLoading } = useChat({
model: ‘gpt-3.5-turbo’,
systemPrompt: ‘You are a helpful assistant.’,
});
const [input, setInput] = useState(”);
const handleSubmit = async (e) => {
e.preventDefault();
if (!input.trim()) return;
await sendMessage(input);
setInput(”);
};
return (
<div>
<div style={{ height: ‘400px’, overflowY: ‘auto’ }}>
{messages.map((msg, index) => (
<div key={index}>
<strong>{msg.role}:</strong> {msg.content}
</div>
))}
</div>
<form onSubmit={handleSubmit}>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
disabled={isLoading}
placeholder=”Type your message…”
/>
<button type=”submit” disabled={isLoading}>Send</button>
</form>
</div>
);
}
The hook automatically manages conversation history and streaming. You can switch models by changing the model parameter.
Example 2: Semantic Search with Vector Store
Use the useVectorStore hook to store documents and perform semantic searches.
File: src/components/Search.jsx
import { useVectorStore, useEmbeddings } from ‘polyfire’;
import { useState } from ‘react’;
export default function Search() {
const { addDocuments, search } = useVectorStore(‘my-knowledge-base’);
const { generateEmbedding } = useEmbeddings();
const [query, setQuery] = useState(”);
const [results, setResults] = useState([]);
const handleAddDocuments = async () => {
const docs = [
{ text: ‘Polyfire is an AI backend service.’, metadata: { source: ‘docs’ } },
{ text: ‘React hooks simplify AI integration.’, metadata: { source: ‘tutorial’ } },
];
await addDocuments(docs);
alert(‘Documents added!’);
};
const handleSearch = async () => {
if (!query.trim()) return;
const searchResults = await search(query, { topK: 3 });
setResults(searchResults);
};
return (
<div>
<button onClick={handleAddDocuments}>Add Sample Documents</button>
<br /><br />
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder=”Search your documents…”
/>
<button onClick={handleSearch}>Search</button>
<ul>
{results.map((result, index) => (
<li key={index}>
<strong>Score:</strong> {result.score.toFixed(2)} – {result.text}
</li>
))}
</ul>
</div>
);
}
Polyfire automatically generates embeddings for your documents and stores them in a managed vector database. No separate database setup is required.
Example 3: User Authentication
Polyfire’s usePolyfire hook provides authentication state and methods.
File: src/components/Auth.jsx
import { usePolyfire } from ‘polyfire’;
import { useState } from ‘react’;
export default function Auth() {
const { user, login, logout, signup } = usePolyfire();
const [email, setEmail] = useState(”);
const [password, setPassword] = useState(”);
if (user) {
return (
<div>
<p>Welcome, {user.email}!</p>
<button onClick={logout}>Logout</button>
</div>
);
}
return (
<div>
<h3>Login or Sign Up</h3>
<input
type=”email”
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder=”Email”
/>
<input
type=”password”
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder=”Password”
/>
<button onClick={() => login(email, password)}>Login</button>
<button onClick={() => signup(email, password)}>Sign Up</button>
</div>
);
}
The user object contains profile information and authentication tokens. Polyfire manages session persistence and token refresh automatically.
Tips for Using Polyfire Effectively
1. Start with the Playground
Before writing any code, use the Polyfire playground in your dashboard to experiment with different models and prompts. This helps you understand model behavior, token costs, and response quality without affecting your application. Once you have a working prompt, copy it directly into your code.
2. Use Environment Variables for Configuration
Never hardcode API keys or project IDs in your source code. Use environment variables (.env files) and access them through your build tool (e.g., import.meta.env.VITE_POLYFIRE_PUBLIC_KEY for Vite). This keeps your credentials secure and makes it easy to switch between development and production environments.
3. Optimize Model Selection for Cost and Performance
Polyfire gives you access to 72+ models, but not all models are equal. Use cheaper and faster models (like GPT-3.5-turbo or Mistral-7B) for simple tasks like basic Q&A. Reserve expensive models (like GPT-4 or Claude-3) for complex reasoning, creative writing, or tasks requiring high accuracy. You can dynamically switch models based on the user’s subscription tier or the complexity of the request.
4. Leverage the Key-Value Store for User Data
Instead of setting up a separate database for user preferences or session data, use Polyfire’s built-in key-value store. This is perfect for storing things like user settings, conversation history summaries, or feature flags. It reduces your application’s dependency on external infrastructure and keeps your data management simple.
5. Monitor Logs for Debugging and Optimization
Regularly check the Polyfire logs in your dashboard. Logs show you every API call, including the exact prompt sent, the model response, latency, and cost. Use this data to identify slow prompts, high-cost models, or unexpected user behavior. The logs are invaluable for iterating on your prompt engineering and optimizing your application’s performance.
6. Handle Errors Gracefully in Your UI
AI models can occasionally fail due to rate limits, network issues, or content filtering. Always wrap your Polyfire calls in try-catch blocks and display user-friendly error messages. The hooks like useChat provide an error state that you can use to show error notifications without crashing your app.
7. Use Streaming for a Better User Experience
Polyfire supports streaming responses for chat and completion endpoints. Streaming means users see the AI’s response as it is being generated, rather than waiting for the full response. This creates a more interactive and responsive feel. The useChat hook handles streaming
Polyfire
React library and backend-as-a-service for building AI apps.