Skip to content

API Integration

This guide provides comprehensive information on integrating with the Bluefly LLM ecosystem through its APIs.

API Overview

The Bluefly LLM ecosystem exposes a RESTful API that allows integration with various services:

  • Authentication API: User and service authentication
  • Model API: Access to ML models and inference
  • Learning API: Feedback and continuous learning
  • Analyze API: Text and document analysis

Authentication

API Keys

For server-to-server communication, use API key authentication:

GET /api/v1/models HTTP/1.1
Host: api.bluefly.io
Authorization: Bearer YOUR_API_KEY

JWT Authentication

For user-based authentication, use JWT tokens:

  1. Obtain a token by authenticating the user
POST /api/v1/auth/login HTTP/1.1
Host: api.bluefly.io
Content-Type: application/json

{
  "username": "[email protected]",
  "password": "your_password"
}

Response:

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
  "refreshToken": "abc123...",
  "expiresIn": 3600
}
  1. Use the token in subsequent requests
GET /api/v1/user/profile HTTP/1.1
Host: api.bluefly.io
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Core API Endpoints

Model API

List Available Models

GET /api/v1/models HTTP/1.1
Host: api.bluefly.io
Authorization: Bearer YOUR_API_KEY

Response:

{
  "models": [
    {
      "id": "bluefly-text-1",
      "name": "Bluefly Text Processing Model",
      "version": "1.0.0",
      "description": "General-purpose text processing model",
      "capabilities": ["text-generation", "summarization", "classification"],
      "inputTypes": ["text"],
      "maxInputLength": 4096
    },
    {
      "id": "bluefly-doc-1",
      "name": "Bluefly Document Processing Model",
      "version": "1.0.0",
      "description": "Document analysis and extraction model",
      "capabilities": ["document-analysis", "information-extraction"],
      "inputTypes": ["text", "pdf", "docx"],
      "maxInputLength": 10240
    }
  ]
}

Generate Text

POST /api/v1/models/bluefly-text-1/generate HTTP/1.1
Host: api.bluefly.io
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

{
  "prompt": "Write a short explanation of machine learning for beginners.",
  "maxTokens": 150,
  "temperature": 0.7,
  "format": "text"
}

Response:

{
  "id": "gen_123abc",
  "model": "bluefly-text-1",
  "output": "Machine learning is a subset of artificial intelligence that enables computers to learn from data without being explicitly programmed. Think of it like teaching a child...",
  "usage": {
    "promptTokens": 12,
    "completionTokens": 138,
    "totalTokens": 150
  }
}

Analyze API

Analyze Text

POST /api/v1/analyze/text HTTP/1.1
Host: api.bluefly.io
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

{
  "text": "Bluefly Inc. reported Q3 revenue of $1.2M, a 15% increase from the previous quarter.",
  "analyses": ["entities", "sentiment", "keywords"]
}

Response:

{
  "text": "Bluefly Inc. reported Q3 revenue of $1.2M, a 15% increase from the previous quarter.",
  "entities": [
    { "text": "Bluefly Inc.", "type": "ORGANIZATION", "start": 0, "end": 12 },
    { "text": "Q3", "type": "TIME", "start": 22, "end": 24 },
    { "text": "$1.2M", "type": "MONEY", "start": 36, "end": 41 },
    { "text": "15%", "type": "PERCENT", "start": 45, "end": 48 }
  ],
  "sentiment": {
    "score": 0.6,
    "label": "POSITIVE"
  },
  "keywords": ["revenue", "increase", "quarter"]
}

Analyze Document

POST /api/v1/analyze/document HTTP/1.1
Host: api.bluefly.io
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Authorization: Bearer YOUR_API_KEY

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="document"; filename="report.pdf"
Content-Type: application/pdf

(Binary PDF data)
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="analyses"

["text", "structure", "topics"]
------WebKitFormBoundary7MA4YWxkTrZu0gW--

Response:

{
  "documentId": "doc_456def",
  "text": "...",
  "structure": {
    "title": "Quarterly Financial Report",
    "sections": [
      { "title": "Executive Summary", "level": 1, "pageStart": 1, "pageEnd": 2 },
      { "title": "Financial Results", "level": 1, "pageStart": 3, "pageEnd": 5 },
      { "title": "Revenue", "level": 2, "pageStart": 3, "pageEnd": 4 },
      { "title": "Expenses", "level": 2, "pageStart": 4, "pageEnd": 5 },
      { "title": "Outlook", "level": 1, "pageStart": 6, "pageEnd": 7 }
    ]
  },
  "topics": ["financial performance", "quarterly results", "revenue growth"]
}

Learning API

Submit Feedback

POST /api/v1/learning/feedback HTTP/1.1
Host: api.bluefly.io
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

{
  "modelId": "bluefly-text-1",
  "requestId": "gen_123abc",
  "rating": 4,
  "feedback": "The response was helpful but could be more concise.",
  "improvedResponse": "Machine learning is a field of AI that enables computers to learn patterns from data and make predictions without explicit programming. It's like how humans learn from experience but using algorithms and statistics."
}

Response:

{
  "id": "feedback_789ghi",
  "status": "received",
  "message": "Thank you for your feedback"
}

Error Handling

API errors are returned with appropriate HTTP status codes and error messages:

{
  "error": {
    "code": "invalid_request",
    "message": "The request was unacceptable, often due to missing a required parameter.",
    "details": "Parameter 'prompt' is required"
  }
}

Common error codes:

Status Code Error Code Description
400 invalid_request The request was invalid
401 authentication_error Authentication failed
403 permission_denied The authenticated user doesn't have access
404 not_found The requested resource doesn't exist
429 rate_limit_exceeded Too many requests
500 server_error An error occurred on the server

Rate Limiting

API requests are rate-limited based on your subscription tier. Rate limit information is included in the response headers:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1620000000

Code Examples

JavaScript/Node.js

const axios = require('axios');

async function generateText(prompt) {
  try {
    const response = await axios.post(
      'https://api.bluefly.io/api/v1/models/bluefly-text-1/generate',
      {
        prompt,
        maxTokens: 150,
        temperature: 0.7,
        format: 'text'
      },
      {
        headers: {
          'Authorization': `Bearer ${process.env.BLUEFLY_API_KEY}`,
          'Content-Type': 'application/json'
        }
      }
    );

    return response.data;
  } catch (error) {
    console.error('Error generating text:', error.response?.data || error.message);
    throw error;
  }
}

Python

import requests
import os

def generate_text(prompt):
    try:
        response = requests.post(
            'https://api.bluefly.io/api/v1/models/bluefly-text-1/generate',
            json={
                'prompt': prompt,
                'maxTokens': 150,
                'temperature': 0.7,
                'format': 'text'
            },
            headers={
                'Authorization': f"Bearer {os.environ.get('BLUEFLY_API_KEY')}",
                'Content-Type': 'application/json'
            }
        )
        response.raise_for_status()
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error generating text: {e}")
        raise

Using the BFCLI

The Bluefly Command Line Interface (BFCLI) can be used for API interaction during development:

# Install the CLI
npm install -g @bluefly/cli

# Configure API key
bfcli config set apiKey YOUR_API_KEY

# Generate text
bfcli model generate --model bluefly-text-1 --prompt "Explain quantum computing"

# Analyze text
bfcli analyze text "Bluefly Inc. reported Q3 revenue of $1.2M"

Webhooks

You can configure webhooks to receive notifications for asynchronous operations:

POST /api/v1/webhooks HTTP/1.1
Host: api.bluefly.io
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

{
  "url": "https://your-app.com/webhooks/bluefly",
  "events": ["model.trained", "document.processed"],
  "secret": "your_webhook_secret"
}

When events occur, Bluefly will send a POST request to your webhook URL:

{
  "event": "document.processed",
  "data": {
    "documentId": "doc_456def",
    "status": "completed",
    "resultUrl": "https://api.bluefly.io/api/v1/analyze/document/doc_456def"
  },
  "timestamp": 1620000000
}