By Fikra DevRel • 4 min read

Firebase Cloud Functions: Fikra API Integration Guide

Firebase Cloud Functions: Fikra API Integration Guide

Firebase Cloud Functions: Fikra API Integration Guide

This guide demonstrates how to integrate Fikra API into Firebase Cloud Functions using the OpenAI-compatible chat-completions interface. Fikra API supports standard OpenAI-style requests, allowing you to use existing OpenAI SDKs or raw HTTP clients.

Prerequisites

  • A Firebase project with Cloud Functions enabled.
  • A Fikra API account with a valid API key (fk_live_...).
  • Node.js 18+ or Python 3.10+ runtime for Cloud Functions.
  • The openai npm package (for Node.js) or openai Python package (for Python).

Environment Variable Setup

Store your Fikra API key in Firebase environment variables to avoid hardcoding secrets.

  1. In the Firebase Console, go to Functions > Settings > Environment variables.
  2. Add a variable named FIKRA_API_KEY with your Fikra API key value.
  3. Alternatively, use the firebase-functions configuration or a secrets manager if preferred.

Node.js Example

Below is a Cloud Function that uses the OpenAI SDK to call Fikra API.

const functions = require('firebase-functions');
const { OpenAI } = require('openai');

// Initialize the OpenAI client with Fikra's base URL
const client = new OpenAI({
  apiKey: process.env.FIKRA_API_KEY,
  baseURL: 'https://api.fikraapi.co.ke/v1',
});

exports.fikraChat = functions.https.onRequest(async (req, res) => {
  try {
    const { messages } = req.body;

    const completion = await client.chat.completions.create({
      model: 'fikra-flash',
      messages: messages,
    });

    res.status(200).json(completion);
  } catch (error) {
    console.error('Fikra API error:', error);
    res.status(500).json({ error: error.message });
  }
});

Python Example

import functions_framework
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.environ.get('FIKRA_API_KEY'),
    base_url='https://api.fikraapi.co.ke/v1',
)

@functions_framework.http
def fikra_chat(request):
    try:
        data = request.get_json()
        messages = data.get('messages', [])

        response = client.chat.completions.create(
            model='fikra-flash',
            messages=messages,
        )

        return response.model_dump(), 200
    except Exception as e:
        return {'error': str(e)}, 500

Streaming Guidance

Fikra API supports streaming via Server-Sent Events (SSE) when stream: true is set. In Cloud Functions, you must handle the stream manually to send chunks to the client.

Node.js Streaming Example

exports.fikraChatStream = functions.https.onRequest(async (req, res) => {
  try {
    const { messages } = req.body;

    const stream = await client.chat.completions.create({
      model: 'fikra-flash',
      messages: messages,
      stream: true,
    });

    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    for await (const chunk of stream) {
      res.write(`data: ${JSON.stringify(chunk)}\n\n`);
    }

    res.write('data: [DONE]\n\n');
    res.end();
  } catch (error) {
    console.error('Fikra API stream error:', error);
    res.status(500).json({ error: error.message });
  }
});

Common Errors

HTTP Status Description Action
400 Bad Request Check that model is a valid Fikra alias (e.g., fikra-flash) and messages is a valid array.
401 Unauthorized Verify that FIKRA_API_KEY is set correctly and starts with fk_live_.
402 Payment Required Your token-credit wallet may be empty. Top up via the Fikra dashboard.
429 Too Many Requests You have exceeded the rate limit (30 RPM for unverified, 100 RPM for trusted accounts). Implement retry logic with exponential backoff.
503 Service Unavailable Fikra API may be temporarily unavailable. Retry after a short delay.

Production Checklist

  • [ ] Store FIKRA_API_KEY in Firebase environment variables, not in code.
  • [ ] Use fikra-flash or another listed Fikra alias; check the model registry for availability.
  • [ ] Implement retry logic with exponential backoff for 429 and 503 errors.
  • [ ] Set appropriate timeouts for Cloud Functions (e.g., 60 seconds for non-streaming, longer for streaming).
  • [ ] Log errors securely without exposing API keys.
  • [ ] Test streaming responses end-to-end to ensure SSE chunks are delivered correctly.
  • [ ] Monitor token usage via the Fikra dashboard to manage costs.

JM
// The Founder

James Miano

CTO & ML Engineer at Lacesse Ventures. James specializes in low-overhead LLM quantization processes, custom ternary weights architectures, and localized server optimization.

Stop paying for overpriced round-trip latency

Why route queries over Western servers when you can use low-overhead hardware located in Nairobi? Save 87% on your monthly inference spend. No minimum credit limits. M-Pesa ready.

usagestatusdashboard