Fuse AI Services API

Fuse AI LLM Service - v1.0.0

Dashboard

Introduction

Welcome to the Fuse AI Services API documentation. This API provides a comprehensive suite of endpoints for interacting with various LLM models, vector databases, NoSQL storage, agent tools and related services for building Enterprise grade customer applications and embedded AI services. Fuse AIs was built from the ground up as a highly scalable platform with Fuse Analytics and AWS cloud for global reach, enterprise security features and data privacy at the forefront of features.

We maintain access to the most current and largest LLM models and offer a selection of Public and Private AI Endpoints from OpenAI, Cohere, Anthropic, Amazon, Microsoft and other local (VPC) specialized models.

Base URL

All API requests should be made to:

https://api.fuseais.com/api/v1

Available Models

Public Cloud

Fastest response times, but not safe for PII use cases unless you first use FuseAis API Privacy endpoints to scrub PII first:
openai claude gemini cohere

Private Cloud

PII safe, Largest AWS VPC hosted models:
aws_claude aws_llama aws_mistral aws_nova_lite

Local (VPC)

Smallest models, PII safe, VPN/VPC hosted FuseAis managed models. Best for very specific few shot, niche tasks:
phi4 gemma3

Authentication

Fuse AI Services API uses a token-based authentication system to secure API requests. All API endpoints, except for the health check and authentication endpoints, require authentication.

Authentication Methods

The API supports two authentication methods:

API Key Authentication

For API requests, pass your credential (an API key or a JWT) in the X-API-Key header, or equivalently in the standard Authorization: Bearer header:

X-API-Key: YOUR_API_KEY
# or
Authorization: Bearer YOUR_API_KEY

API keys are associated with both a specific user account and a customer/organization. They have no expiration date by default but can be configured with an expiration. API keys include rate limiting at both the user and organization levels. They provide a simple way to access the API programmatically. API keys should be kept secure and not exposed in client-side code.

JWT Token Authentication

For session-based authentication (e.g., web applications), use JWT tokens:

Authorization: Bearer YOUR_JWT_TOKEN

JWT tokens are obtained by authenticating with a username and password. They expire after 8 hours (configurable via JWT_EXPIRATION_MINUTES) and provide a secure way to authenticate users in the application in place of session IDs for more secure applications.

Authentication Flow

To authenticate with the API:

  1. Obtain an authentication token or API key:
    • For JWT tokens: use the Get Auth Token endpoint with your username and password
    • For API keys: use the Create API Key endpoint (admin access required) or contact your administrator
  2. Include the token in API requests: Add the token to the Authorization header of your requests using the Bearer scheme
  3. Handle token expiration: For JWT tokens, refresh the token before it expires to maintain session continuity

Security Recommendations

Best Practices

  • Store tokens securely: Never store tokens in client-side code, cookies without proper security flags, or local storage
  • Use environment variables: Store API keys in environment variables, not in code repositories
  • Implement token refresh: For JWT tokens, implement a refresh mechanism to handle token expiration
  • Use HTTPS: Always use HTTPS when communicating with the API to protect credentials and data
  • Limit token scope: When creating API keys, limit their scope to only what's necessary
  • Rotate keys regularly: Periodically rotate API keys to limit the impact of potential key exposure

Authentication Errors

Status Code Error Description
401 Unauthorized Invalid Credentials The username or password is incorrect
401 Unauthorized Invalid Token The provided token is invalid or malformed
401 Unauthorized Token Expired The JWT token has expired and needs to be refreshed
403 Forbidden Insufficient Permissions The authenticated user doesn't have permission to access the requested resource

For detailed information on how to obtain authentication tokens, see the Get Auth Token endpoint documentation.

Base path: all endpoints below are served under /api/v1 (e.g. https://api.fuseais.com/api/v1/file/upload) — the code samples show full URLs. The only exception is the health check at /health.

Health Check

GET
/health

Check the health and status of the API

Response
Response
{
  "status": "healthy",
  "version": "1.0.0",
  "timestamp": "2025-03-17T12:34:56.789Z",
  "available_models": [
    "openai", "claude", "aws_claude", "cohere", 
    "aws_llama", "aws_mistral", "aws_nova_lite", 
    "gemini", "ollama"
  ]
}
Sample Code
cURL
JavaScript
Python
Java
curl -X GET \
  "https://api.fuseais.com/health" \
  -H "X-API-Key: YOUR_API_KEY"
fetch('https://api.fuseais.com/health', {
  method: 'GET',
  headers: {
    'X-API-Key': 'YOUR_API_KEY'
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
import requests

url = "https://api.fuseais.com/health"
headers = {
    "X-API-Key": "YOUR_API_KEY"
}

response = requests.get(url, headers=headers)
print(response.json())

    import java.net.URI;
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.time.Duration;
    
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class HealthCheckExample {
        public static void main(String[] args) {
            try {
                // Create HTTP client
                HttpClient client = HttpClient.newHttpClient();
                
                // Build the request
                HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://api.fuseais.com/health"))
                    .header("X-API-Key", "YOUR_API_KEY")
                    .timeout(Duration.ofSeconds(10))
                    .GET()
                    .build();
                    
                // Send the request and get the response
                HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
                
                // Check response status
                if (response.statusCode() != 200) {
                    System.out.println("Health check failed: HTTP status code " + response.statusCode());
                    return;
                }
                
                // Parse the JSON response
                ObjectMapper mapper = new ObjectMapper();
                JsonNode healthData = mapper.readTree(response.body());
                
                // Extract and display health information
                String status = healthData.get("status").asText();
                String version = healthData.get("version").asText();
                
                System.out.println("Health Check Result:");
                System.out.println("Status: " + status);
                System.out.println("Version: " + version);
                
                // Also show available models if present
                if (healthData.has("available_models")) {
                    System.out.println("Available Models:");
                    healthData.get("available_models").forEach(model -> 
                        System.out.println("- " + model.asText()));
                }
                
            } catch (Exception e) {
                System.out.println("Error performing health check: " + e.getMessage());
            }
        }
    }
                        

Get Authentication Token

POST
/admin/token

Authenticate with username and password to receive a JWT token that can be used for subsequent API calls. The token expires after 30 minutes.

Request Parameters
Parameter Type Required Description
username string Required Your registered username
password string Required Your account password
Request Body Example
{
    "username": "admin",
    "password": "secure_password"
}
Response
{
    "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "token_type": "bearer"
}
Error Responses
Status Code Description
401 Unauthorized Incorrect username or password
Sample Code
cURL
JavaScript
Python
Java
curl -X POST \
"https://api.fuseais.com/api/v1/admin/token" \
-H "Content-Type: application/json" \
-d '{
    "username": "admin",
    "password": "secure_password"
}'
fetch('https://api.fuseais.com/api/v1/admin/token', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            username: 'admin',
            password: 'secure_password'
        })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Authentication failed: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        // Store the token for future API calls
        localStorage.setItem('api_token', data.access_token);
        console.log('Authentication successful');
    })
    .catch(error => console.error('Error:', error));
import requests
import json

url = "https://api.fuseais.com/api/v1/admin/token"
headers = {
    "Content-Type": "application/json"
}
payload = {
    "username": "admin",
    "password": "secure_password"
}

try:
    response = requests.post(url, headers=headers, json=payload)
    response.raise_for_status()  # Raise an exception for 4XX/5XX responses
    
    data = response.json()
    
    # Store the token for future API calls
    token = data["access_token"]
    print("Authentication successful")
except requests.exceptions.HTTPError as err:
    if response.status_code == 401:
        print("Authentication failed: Invalid credentials")
    else:
        print(f"HTTP Error: {err}")
except Exception as err:
    print(f"Error: {err}")
import java.net.URI;
    import java.net.http.HttpClient;
    import java.net.http.HttpRequest;
    import java.net.http.HttpResponse;
    import java.util.Map;
    
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class GetAuthTokenExample {
        public static void main(String[] args) {
            try {
                ObjectMapper objectMapper = new ObjectMapper();
                
                Map credentials = Map.of(
                    "username", "admin", 
                    "password", "secure_password"
                );
                
                String requestBody = objectMapper.writeValueAsString(credentials);
                
                HttpClient client = HttpClient.newHttpClient();
                
                HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://api.fuseais.com/api/v1/admin/token"))
                    .header("Content-Type", "application/json")
                    .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                    .build();
                    
                HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
                
                int statusCode = response.statusCode();
                if (statusCode == 401) {
                    System.out.println("Authentication failed: Invalid credentials");
                    return;
                } else if (statusCode != 200) {
                    throw new RuntimeException("Failed: HTTP error code: " + statusCode);
                }
                
                JsonNode jsonResponse = objectMapper.readTree(response.body());
                
                String accessToken = jsonResponse.get("access_token").asText();
                String tokenType = jsonResponse.get("token_type").asText();
                
                System.out.println("Authentication successful");
                System.out.println("Token: " + accessToken);
                System.out.println("Token type: " + tokenType);
                
            } catch (Exception e) {
                System.err.println("Error during authentication: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }
                    

Get Current User

GET
/admin/users/me

Returns information about the currently authenticated user. Accepts either an API key (X-API-Key header) or a JWT Bearer token.

Response
{
  "username": "alice",
  "role": "user",
  "is_active": true,
  "customer_id": "cust_abc123"
}
Sample Code
cURL
Python
Java
curl -X GET "https://api.fuseais.com/api/v1/admin/users/me" \
  -H "X-API-Key: YOUR_API_KEY"
import requests

url = "https://api.fuseais.com/api/v1/admin/users/me"
headers = {"X-API-Key": "YOUR_API_KEY"}

response = requests.get(url, headers=headers)
print(response.json())
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class GetCurrentUserExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/admin/users/me"))
            .header("X-API-Key", "YOUR_API_KEY")
            .GET()
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

List Users

GET
/admin/users

Returns a list of all users in the system. Requires an admin role. Non-admin tokens receive a 403 response.

Response
[
  {
    "username": "alice",
    "role": "user",
    "is_active": true,
    "customer_id": "cust_abc123"
  },
  {
    "username": "bob",
    "role": "admin",
    "is_active": true,
    "customer_id": "cust_def456"
  }
]
Sample Code
cURL
Python
Java
curl -X GET "https://api.fuseais.com/api/v1/admin/users" \
  -H "X-API-Key: YOUR_ADMIN_API_KEY"
import requests

url = "https://api.fuseais.com/api/v1/admin/users"
headers = {"X-API-Key": "YOUR_ADMIN_API_KEY"}

response = requests.get(url, headers=headers)
for user in response.json():
    print(user["username"], user["role"])
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class ListUsersExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/admin/users"))
            .header("X-API-Key", "YOUR_ADMIN_API_KEY")
            .GET()
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

View Rate Limits

GET
/admin/rate-limits

Returns current rate-limit counters for all tracked clients, along with the configured window size and per-window request cap. Admin only.

Response
{
  "status": "success",
  "rate_limits": {
    "user123": 42,
    "user456": 7
  },
  "window_size": 60,
  "max_requests": 100
}
Sample Code
cURL
Python
Java
curl -X GET "https://api.fuseais.com/api/v1/admin/rate-limits" \
  -H "X-API-Key: YOUR_ADMIN_API_KEY"
import requests

url = "https://api.fuseais.com/api/v1/admin/rate-limits"
headers = {"X-API-Key": "YOUR_ADMIN_API_KEY"}

response = requests.get(url, headers=headers)
data = response.json()
print(f"Window: {data['window_size']}s, Max: {data['max_requests']} requests")
for client_id, count in data["rate_limits"].items():
    print(f"  {client_id}: {count} requests")
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class GetRateLimitsExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/admin/rate-limits"))
            .header("X-API-Key", "YOUR_ADMIN_API_KEY")
            .GET()
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Create API Key

POST
/admin/api-keys

Create a new API key for a user. The generated key is returned only once — store it securely. Admin only.

Request Parameters
Parameter Type Required Description
user_id string Required The user the key will be assigned to
customer_id string Required The customer tenant this key belongs to
scope string Optional Permission scope string (default: "read:write")
expires_at datetime Optional ISO 8601 expiry date-time; omit for non-expiring keys
Request Body Example
{
  "user_id": "alice",
  "customer_id": "cust_abc123",
  "scope": "read:write",
  "expires_at": "2027-01-01T00:00:00Z"
}
Response
{
  "status": "success",
  "api_key": "fai_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "key_info": {
    "key_id": "ki_abc123",
    "user_id": "alice",
    "customer_id": "cust_abc123",
    "scope": "read:write",
    "created_at": "2026-05-10T12:00:00Z",
    "created_by": "admin",
    "expires_at": "2027-01-01T00:00:00Z",
    "last_used": null,
    "status": "active"
  }
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/admin/api-keys" \
  -H "X-API-Key: YOUR_ADMIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "alice",
    "customer_id": "cust_abc123",
    "scope": "read:write"
  }'
import requests

url = "https://api.fuseais.com/api/v1/admin/api-keys"
headers = {"X-API-Key": "YOUR_ADMIN_API_KEY", "Content-Type": "application/json"}
payload = {
    "user_id": "alice",
    "customer_id": "cust_abc123",
    "scope": "read:write"
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
print("New API key:", data["api_key"])  # save this — shown only once
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class CreateApiKeyExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"user_id\":\"alice\",\"customer_id\":\"cust_abc123\",\"scope\":\"read:write\"}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/admin/api-keys"))
            .header("X-API-Key", "YOUR_ADMIN_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Revoke API Key

DELETE
/admin/api-keys/{key_id}

Permanently revokes and deletes the specified API key. The key_id is the key_id field from the key's metadata (not the raw key string). Admin only.

Path Parameter
Parameter Type Required Description
key_id string Required The key_id of the API key to revoke (e.g. ki_abc123)
Response
{
  "status": "success"
}
Sample Code
cURL
Python
Java
curl -X DELETE "https://api.fuseais.com/api/v1/admin/api-keys/ki_abc123" \
  -H "X-API-Key: YOUR_ADMIN_API_KEY"
import requests

key_id = "ki_abc123"
url = f"https://api.fuseais.com/api/v1/admin/api-keys/{key_id}"
headers = {"X-API-Key": "YOUR_ADMIN_API_KEY"}

response = requests.delete(url, headers=headers)
print(response.json())  # {"status": "success"}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class RevokeApiKeyExample {
    public static void main(String[] args) throws Exception {
        String keyId = "ki_abc123";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/admin/api-keys/" + keyId))
            .header("X-API-Key", "YOUR_ADMIN_API_KEY")
            .DELETE()
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Get My Scopes

GET
/admin/scopes

Returns the authenticated user's enabled scopes. Human users receive all available scopes. Bot users receive only the scopes that have been explicitly granted to them. This endpoint is used by agents on startup to discover which tools they can use.

Response
{
    "status": "success",
    "user": "my-bot",
    "is_bot": true,
    "scopes": [
        "web_search",
        "email_send",
        "email_list",
        "llm_query"
    ]
}
Notes
  • Human users always receive all scope keys (scopes only restrict bot users)
  • Bot scopes are managed via the dashboard at Admin → Bots → Manage Scopes
  • If a bot calls an endpoint it lacks the scope for, it receives a 403 Forbidden response

List Available Scopes

GET
/admin/scopes/available

Returns the full catalogue of available scopes grouped by category. Useful for building scope management UIs or understanding which endpoints are available.

Response (abbreviated)
{
    "status": "success",
    "scopes": {
        "web_search": {
            "endpoint": "/tools/web-search",
            "tool_name": "web_search",
            "category": "Web"
        },
        "email_send": {
            "endpoint": "/tools/email/send",
            "tool_name": "send_email",
            "category": "Email"
        }
    },
    "categories": {
        "Web": ["web_search", "scrape_webpage", "scrape_pdf"],
        "Email": ["email_send", "email_list", "email_get", "email_mark_read", "email_thread", "email_draft"],
        "Calendar": ["calendar_create", "calendar_list", "calendar_get", "calendar_update", "calendar_delete"],
        "LLM": ["llm_query", "llm_summarize"],
        "Privacy": ["privacy_redact", "privacy_detect", "privacy_tokenize"]
    }
}

Query LLM

POST
/llm/query

Send a query to a language model and receive a response. This endpoint provides access to various LLM models, handles rate limiting, and tracks token usage.

Request Parameters
Parameter Type Required Description
query string Required The text query to send to the model
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
model string Optional The model to use (default: "claude")
system_prompt string Optional Custom system prompt to use
Request Body Example
{
                                "query": "What is the capital of France?",
                                "user_id": "user123",
                                "model": "claude",
                                "system_prompt": "You are a helpful assistant."
                            }
Response
{
                                "response": "The capital of France is Paris.",
                                "model_used": "claude",
                                "tokens_used": 15,
                                "tokens_remaining": 985,
                                "request_id": "550e8400-e29b-41d4-a716-446655440000"
                                }
                            
Error Responses
Status Code Description
400 Bad Request Invalid request parameters
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Error processing the query
Sample Code
cURL
JavaScript
Python
Java
curl -X POST \
                          "https://api.fuseais.com/api/v1/llm/query" \
                          -H "X-API-Key: YOUR_API_KEY" \
                          -H "Content-Type: application/json" \
                          -d '{
                            "query": "What is the capital of France?",
                            "user_id": "user123",
                            "model": "claude"
                          }'
fetch('https://api.fuseais.com/api/v1/llm/query', {
                          method: 'POST',
                          headers: {
                            'X-API-Key': 'YOUR_API_KEY',
                            'Content-Type': 'application/json'
                          },
                          body: JSON.stringify({
                            query: 'What is the capital of France?',
                            user_id: 'user123',
                            model: 'claude'
                          })
                        })
                        .then(response => {
                          if (!response.ok) {
                            throw new Error('API request failed: ' + response.status);
                          }
                          return response.json();
                        })
                        .then(data => {
                          console.log('Response:', data.response);
                          console.log('Tokens used:', data.tokens_used);
                          console.log('Tokens remaining:', data.tokens_remaining);
                        })
                        .catch(error => console.error('Error:', error));
import requests
                        import json
                        
                        url = "https://api.fuseais.com/api/v1/llm/query"
                        headers = {
                            "X-API-Key": "YOUR_API_KEY",
                            "Content-Type": "application/json"
                        }
                        payload = {
                            "query": "What is the capital of France?",
                            "user_id": "user123",
                            "model": "claude"
                        }
                        
                        try:
                            response = requests.post(url, headers=headers, json=payload)
                            response.raise_for_status()  # Raise exception for 4XX/5XX responses
                            
                            data = response.json()
                            print("Response:", data["response"])
                            print("Model used:", data["model_used"])
                            print("Tokens used:", data["tokens_used"])
                            print("Tokens remaining:", data["tokens_remaining"])
                            
                        except requests.exceptions.HTTPError as err:
                            print(f"HTTP Error: {err}")
                            print(f"Response: {response.text}")
                        except Exception as err:
                            print(f"Error: {err}")
import java.net.URI;
                        import java.net.http.HttpClient;
                        import java.net.http.HttpRequest;
                        import java.net.http.HttpResponse;
                        import java.util.Map;
                        
                        import com.fasterxml.jackson.databind.JsonNode;
                        import com.fasterxml.jackson.databind.ObjectMapper;
                        
                        public class QueryLLMExample {
                            public static void main(String[] args) {
                                try {
                                    // Create request body using Map
                                    Map<String, String> requestData = Map.of(
                                        "query", "What is the capital of France?",
                                        "user_id", "user123",
                                        "model", "claude"
                                    );
                        
                                    // Convert to JSON and send request
                                    ObjectMapper objectMapper = new ObjectMapper();
                                    String requestBody = objectMapper.writeValueAsString(requestData);
                        
                                    HttpClient client = HttpClient.newHttpClient();
                                    HttpRequest request = HttpRequest.newBuilder()
                                        .uri(URI.create("https://api.fuseais.com/api/v1/llm/query"))
                                        .header("X-API-Key", "YOUR_API_KEY")
                                        .header("Content-Type", "application/json")
                                        .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                                        .build();
                        
                                    HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
                        
                                    // Check response status
                                    if (response.statusCode() != 200) {
                                        System.out.println("Error: HTTP status code " + response.statusCode());
                                        return;
                                    }
                        
                                    // Parse response
                                    JsonNode node = objectMapper.readTree(response.body());
                                    String llmResponse = node.get("response").asText();
                                    int tokensUsed = node.get("tokens_used").asInt();
                                    int tokensRemaining = node.get("tokens_remaining").asInt();
                                    
                                    System.out.println("Response: " + llmResponse);
                                    System.out.println("Tokens used: " + tokensUsed);
                                    System.out.println("Tokens remaining: " + tokensRemaining);
                                    
                                } catch (Exception e) {
                                    System.out.println("Error: " + e.getMessage());
                                }
                            }
                        }
Notes
  • This endpoint enforces rate limiting to prevent abuse.
  • Token usage is tracked and deducted from your account's token allocation.
  • The request_id can be used when submitting feedback or reporting issues.
  • Available models include: openai, claude, aws_claude, cohere, aws_llama, aws_mistral, aws_nova_lite, gemini, and ollama.

Upload File

Upload a single file to S3 storage. Supports automatic ZIP extraction.

POST /api/file/upload

Request

Content-Type: multipart/form-data

Field Type Required Description
customer_id string Yes Customer identifier for organizing uploads
file file Yes The file to upload
extract_zip boolean No If true and file is a ZIP, extracts and uploads all contents (default: false)

Example Request

curl -X POST "https://api.fuseais.com/api/v1/api/file/upload" \
  -H "X-API-Key: your_api_key" \
  -F "customer_id=cust_123" \
  -F "file=@document.pdf"

Example with ZIP Extraction

curl -X POST "https://api.fuseais.com/api/v1/api/file/upload" \
  -H "X-API-Key: your_api_key" \
  -F "customer_id=cust_123" \
  -F "file=@documents.zip" \
  -F "extract_zip=true"

Response

{
  "status": "success",
  "message": "File uploaded successfully",
  "customer_id": "cust_123",
  "session_id": "550e8400-e29b-41d4-a716-446655440000",
  "file_details": [
    {
      "filename": "document.pdf",
      "s3_key": "tmp/cust_123/550e8400-e29b-41d4-a716-446655440000/document.pdf",
      "size": 125432
    }
  ],
  "files": ["document.pdf"]
}

Response Fields

Field Type Description
status string Request status ("success" or "error")
message string Human-readable status message
customer_id string The customer ID provided in the request
session_id string Unique session ID for this upload batch (use for subsequent operations)
file_details array Array of uploaded file information
files array List of filenames (for use in processing steps)

Supported File Types

PDF, CSV, TXT, JSON, XML, HTML, JPG, PNG, GIF, WebP, SVG, MP3, WAV, MP4, WebM, DOC, DOCX, XLS, XLSX, PPT, PPTX, ZIP

Error Responses

Status Code Description
400 Invalid request (missing required fields)
401 Invalid or missing API key
500 Server error during upload

Upload Multiple Files

POST
/file/upload/multiple

Upload multiple files in a single multipart/form-data request. All files are stored under the authenticated user's customer tenant and share a single session ID.

Request Parameters
Parameter Type Required Description
files file[] Required One or more files sent as multipart/form-data file fields named files
Response
{
  "status": "success",
  "message": "Successfully uploaded 3 files",
  "customer_id": "cust_abc123",
  "session_id": "550e8400-e29b-41d4-a716-446655440000",
  "file_details": [
    {"filename": "doc1.txt", "size": 1024, "content_type": "text/plain"},
    {"filename": "doc2.txt", "size": 2048, "content_type": "text/plain"},
    {"filename": "image.png", "size": 51200, "content_type": "image/png"}
  ],
  "files": ["doc1.txt", "doc2.txt", "image.png"]
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/file/upload/multiple" \
  -H "X-API-Key: YOUR_API_KEY" \
  -F "files=@doc1.txt" \
  -F "files=@doc2.txt" \
  -F "files=@image.png"
import requests

url = "https://api.fuseais.com/api/v1/file/upload/multiple"
headers = {"X-API-Key": "YOUR_API_KEY"}
files = [
    ("files", open("doc1.txt", "rb")),
    ("files", open("doc2.txt", "rb")),
    ("files", open("image.png", "rb")),
]

response = requests.post(url, headers=headers, files=files)
data = response.json()
print(f"Session: {data['session_id']}")
print(f"Uploaded: {data['files']}")
// Use a multipart HTTP client library such as OkHttp for multipart uploads.
// Example shown with OkHttp:
// OkHttpClient client = new OkHttpClient();
// MultipartBody body = new MultipartBody.Builder()
//     .setType(MultipartBody.FORM)
//     .addFormDataPart("files", "doc1.txt", RequestBody.create(new File("doc1.txt"), MediaType.parse("text/plain")))
//     .addFormDataPart("files", "doc2.txt", RequestBody.create(new File("doc2.txt"), MediaType.parse("text/plain")))
//     .build();
// Request request = new Request.Builder()
//     .url("https://api.fuseais.com/api/v1/file/upload/multiple")
//     .header("X-API-Key", "YOUR_API_KEY")
//     .post(body)
//     .build();
// Response response = client.newCall(request).execute();
// System.out.println(response.body().string());

Generate Presigned URLs

POST
/file/upload/presigned

Generate presigned S3 PUT URLs so that clients can upload files directly to S3 without routing the binary through the API server. The customer tenant is determined from the API key.

Request Body

An array of objects, each describing one file to be uploaded.

Parameter Type Required Description
file_name string Required The original filename (used to derive the S3 key)
content_type string Required MIME type of the file (e.g. application/pdf)
Request Body Example
[
  {"file_name": "report.pdf", "content_type": "application/pdf"},
  {"file_name": "data.csv",   "content_type": "text/csv"}
]
Response
{
  "status": "success",
  "message": "Successfully generated 2 presigned URLs",
  "customer_id": "cust_abc123",
  "session_id": "550e8400-e29b-41d4-a716-446655440000",
  "urls": [
    {
      "file_name": "report.pdf",
      "upload_url": "https://s3.amazonaws.com/bucket/...?X-Amz-Signature=...",
      "s3_key": "tmp/cust_abc123/550e.../report.pdf"
    },
    {
      "file_name": "data.csv",
      "upload_url": "https://s3.amazonaws.com/bucket/...?X-Amz-Signature=...",
      "s3_key": "tmp/cust_abc123/550e.../data.csv"
    }
  ],
  "files": ["report.pdf", "data.csv"]
}
Sample Code
cURL
Python
Java
# Step 1: Get presigned URLs
curl -X POST "https://api.fuseais.com/api/v1/file/upload/presigned" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '[{"file_name": "report.pdf", "content_type": "application/pdf"}]'

# Step 2: Upload directly to S3 using the returned upload_url
curl -X PUT "PRESIGNED_UPLOAD_URL" \
  -H "Content-Type: application/pdf" \
  --data-binary @report.pdf
import requests

# Step 1: Get presigned URLs
url = "https://api.fuseais.com/api/v1/file/upload/presigned"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = [{"file_name": "report.pdf", "content_type": "application/pdf"}]

resp = requests.post(url, json=payload, headers=headers)
data = resp.json()

# Step 2: Upload directly to S3
for item in data["urls"]:
    with open(item["file_name"], "rb") as f:
        requests.put(item["upload_url"], data=f,
                     headers={"Content-Type": "application/pdf"})
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;

public class PresignedUploadExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();

        // Step 1: Get presigned URL
        String body = "[{\"file_name\":\"report.pdf\",\"content_type\":\"application/pdf\"}]";
        HttpRequest req1 = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/file/upload/presigned"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> resp1 = client.send(req1, HttpResponse.BodyHandlers.ofString());
        System.out.println(resp1.body());

        // Step 2: PUT file to the presigned URL (parse upload_url from resp1)
    }
}

Download File

GET
/file/{file_id}

Download a previously uploaded file by its ID. Returns the raw file content as an octet-stream with a Content-Disposition: attachment header.

Path Parameter
Parameter Type Required Description
file_id string Required The S3 key or file identifier returned when the file was uploaded
Response

Binary file content with Content-Type: application/octet-stream and Content-Disposition: attachment; filename=<original_name>.

Sample Code
cURL
Python
Java
curl -X GET "https://api.fuseais.com/api/v1/file/tmp%2Fcust_abc123%2Fsession123%2Freport.pdf" \
  -H "X-API-Key: YOUR_API_KEY" \
  -o report.pdf
import requests

file_id = "tmp/cust_abc123/session123/report.pdf"
url = f"https://api.fuseais.com/api/v1/file/{requests.utils.quote(file_id, safe='')}"
headers = {"X-API-Key": "YOUR_API_KEY"}

response = requests.get(url, headers=headers)
with open("report.pdf", "wb") as f:
    f.write(response.content)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Path;

public class DownloadFileExample {
    public static void main(String[] args) throws Exception {
        String fileId = "tmp%2Fcust_abc123%2Fsession123%2Freport.pdf";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/file/" + fileId))
            .header("X-API-Key", "YOUR_API_KEY")
            .GET()
            .build();
        HttpResponse<Path> response = client.send(request,
            HttpResponse.BodyHandlers.ofFile(Path.of("report.pdf")));
        System.out.println("Saved to: " + response.body());
    }
}

Process File

POST
/file/process

Extract text from a previously uploaded file and compute an approximate token count. PDFs and images (jpg/png/tiff) are processed with AWS Textract OCR; detected tables are appended to the text as markdown pipe tables under a ***Tables detected:*** marker; text formats (txt/csv/json/docx/html) are extracted directly. Useful for preparing files before sending to an LLM.

Request Parameters
Parameter Type Required Description
file_id string Required The file identifier (S3 key) returned at upload time
options object Optional Processing options. For PDFs: {"max_pages": 25} limits pages processed. Documents over 100 pages are rejected with a 400 before any processing.
Request Body Example
{
  "file_id": "tmp/cust_abc123/session123/report.txt",
  "options": {"max_pages": 25}
}
Response
{
  "status": "success",
  "file_id": "tmp/cust_abc123/session123/report.txt",
  "processed_content": "The extracted text content of the file...",
  "tokens": 312
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/file/process" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "file_id": "tmp/cust_abc123/session123/report.txt"
  }'
import requests

url = "https://api.fuseais.com/api/v1/file/process"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {"file_id": "tmp/cust_abc123/session123/report.txt"}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
print(f"Tokens: {data['tokens']}")
print(data["processed_content"][:200])
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class ProcessFileExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"file_id\":\"tmp/cust_abc123/session123/report.txt\"}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/file/process"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Process PDF

POST
/file/pdf/process

Extract text, metadata, and page count from a PDF that was previously uploaded. Returns structured content suitable for LLM input. Detected tables are appended to the extracted text as markdown pipe tables under a ***Tables detected:*** marker.

Request Parameters
Parameter Type Required Description
file_id string Required The S3 key of the uploaded PDF
options object Optional PDF-specific options (e.g. {"pages": [1, 2, 3]})
Request Body Example
{
  "file_id": "tmp/cust_abc123/session123/contract.pdf"
}
Response
{
  "status": "success",
  "file_id": "tmp/cust_abc123/session123/contract.pdf",
  "page_count": 12,
  "extracted_text": "Contract agreement between...",
  "metadata": {
    "author": "Legal Dept",
    "created": "2026-01-15",
    "title": "Service Agreement"
  }
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/file/pdf/process" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"file_id": "tmp/cust_abc123/session123/contract.pdf"}'
import requests

url = "https://api.fuseais.com/api/v1/file/pdf/process"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {"file_id": "tmp/cust_abc123/session123/contract.pdf"}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
print(f"Pages: {data['page_count']}")
print(data["extracted_text"][:500])
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class ProcessPdfExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"file_id\":\"tmp/cust_abc123/session123/contract.pdf\"}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/file/pdf/process"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Transcribe Audio

⚠ Not yet available. This endpoint is a placeholder and currently returns an error. Do not integrate against it yet.
POST
/file/audio/transcribe

Transcribe a previously uploaded audio or video file into text. Returns the transcript, detected language, audio duration, and a confidence score.

Request Parameters
Parameter Type Required Description
file_id string Required S3 key of the uploaded audio file
language string Optional BCP-47 language hint (e.g. "en-US"). Omit for auto-detection.
options object Optional Additional transcription options (e.g. {"punctuation": true})
Request Body Example
{
  "file_id": "tmp/cust_abc123/session123/meeting.mp3",
  "language": "en-US"
}
Response
{
  "status": "success",
  "file_id": "tmp/cust_abc123/session123/meeting.mp3",
  "transcription": "Good morning everyone, let's get started with today's agenda...",
  "language": "en-US",
  "duration_seconds": 3642,
  "confidence": 0.97
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/file/audio/transcribe" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "file_id": "tmp/cust_abc123/session123/meeting.mp3",
    "language": "en-US"
  }'
import requests

url = "https://api.fuseais.com/api/v1/file/audio/transcribe"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "file_id": "tmp/cust_abc123/session123/meeting.mp3",
    "language": "en-US"
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
print(f"Duration: {data['duration_seconds']}s, Confidence: {data['confidence']}")
print(data["transcription"][:300])
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class TranscribeAudioExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"file_id\":\"tmp/cust_abc123/session123/meeting.mp3\",\"language\":\"en-US\"}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/file/audio/transcribe"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Textract Form

POST
/file/textract/form

Extract the filled-in values from a completed form (PDF, PNG, JPEG) as key/value pairs. Claude reads the document by default; a second, calibrated pass with AWS Textract FORMS is added automatically when the page carries deterministic risk signals (handwritten entries, no text layer, a required field missing). Pass schema_fields to have the form's own wording mapped onto your field names, and the response reports matched / unmatched / missing. Set mode: "structure" instead to get a blank template's field names. One page per request.

Request Parameters
Parameter Type Required Description
file_id string Required S3 key of the uploaded document
form_type string Optional Free-text label echoed back in the response (e.g. "w4", "invoice") for your own bookkeeping; does not change extraction
mode string Optional "values" (default) reads a filled form; "structure" returns a blank template's field names
schema_fields array or object Optional Field names you expect back — a list, or {"field": {"required": true}}. Supplied to the reader so the form's wording is mapped onto your names. Not a validation contract (see /llm/format/json for that)
engine string Optional "auto" (default), "claude", or "textract". textract must be enabled for your account
Request Body Example
{
  "file_id": "tmp/cust_abc123/session123/w4_blank.pdf",
  "form_type": "w4"
}
Response
{
  "status": "success",
  "file_id": "tmp/cust_abc123/session123/w4_blank.pdf",
  "form_type": "w4",
  "mode": "values",
  "source": "claude+textract",
  "engine": "auto",
  "fields": {
    "first_name": {"value": "Alice", "confidence": 0.93,
                   "confidence_source": "textract", "matched_from": "First name",
                   "match_status": "matched", "handwritten": true,
                   "alt_value": "Alcie", "engines_agreed": false},
    "social_security_number": {"value": "123-45-6789", "confidence": 0.97,
                   "confidence_source": "textract", "match_status": "matched"}
  },
  "unmatched": {},
  "missing": ["date_signed"],
  "escalation": {"escalated": true, "reasons": ["handwritten_fields_present"]},
  "review_recommended": true,
  "has_acroform": true,
  "pages_processed": 1
}
Response Fields
FieldDescription
fieldsExtracted values keyed by your field names. Each carries value, confidence, confidence_source (textract = calibrated, model = self-reported), matched_from (the form's own label) and match_status
unmatchedValues found on the form that don't correspond to any field you asked for
missingFields you asked for that weren't found
review_recommendedTrue when something warrants a human look — missing/unmatched fields, engine disagreement, or low confidence
escalationWhether a Textract pass was added, and why
alt_value / engines_agreedPresent when both engines read a field differently; value is Textract's reading, alt_value is Claude's
sourceclaude, textract, or claude+textract
form_structure / form_dataReturned in mode: "structure" only — field names mapped to empty strings
Errors
StatusMeaning
400Document has more than one page — split it and submit the page you need
403Form extraction is not enabled for your account, or your key lacks the file_textract_form scope
422No fillable fields found — the document may not be a form, or may need a clean original template
429Monthly form-page allowance exhausted; the response names the reset date
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/file/textract/form" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"file_id": "tmp/cust_abc123/session123/w2_form.pdf", "form_type": "w2"}'
import requests

url = "https://api.fuseais.com/api/v1/file/textract/form"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {"file_id": "tmp/cust_abc123/session123/w2_form.pdf", "form_type": "w2"}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
for field, value in data["form_data"].items():
    print(f"{field}: {value}")
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class TextractFormExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"file_id\":\"tmp/cust_abc123/session123/w2_form.pdf\",\"form_type\":\"w2\"}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/file/textract/form"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Textract Text

⚠ Not yet available. This endpoint is a placeholder and currently returns an error. Do not integrate against it yet.
POST
/file/textract/text

Extract raw text from a document using AWS Textract. Unlike the form endpoint, this returns all detected text across every page in reading order, without attempting field-label pairing.

Request Parameters
Parameter Type Required Description
file_id string Required S3 key of the uploaded document
options object Optional Extraction options (e.g. {"include_tables": true})
Request Body Example
{
  "file_id": "tmp/cust_abc123/session123/scanned_doc.pdf"
}
Response
{
  "status": "success",
  "file_id": "tmp/cust_abc123/session123/scanned_doc.pdf",
  "extracted_text": "INVOICE\nDate: 2026-04-01\nItem: Consulting services...",
  "page_count": 3,
  "confidence": 0.96
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/file/textract/text" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"file_id": "tmp/cust_abc123/session123/scanned_doc.pdf"}'
import requests

url = "https://api.fuseais.com/api/v1/file/textract/text"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {"file_id": "tmp/cust_abc123/session123/scanned_doc.pdf"}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
print(f"Pages: {data['page_count']}, Confidence: {data['confidence']}")
print(data["extracted_text"][:500])
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class TextractTextExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"file_id\":\"tmp/cust_abc123/session123/scanned_doc.pdf\"}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/file/textract/text"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Verify Photo ID

⚠ Not yet available. This endpoint is a placeholder and currently returns an error. Do not integrate against it yet.
POST
/file/id/verify

Verify and extract information from a government-issued photo ID (driver's license, passport, etc.). Upload the ID image directly as a multipart form file. Returns validity, detected ID type, confidence, and extracted fields.

Request Parameters
Parameter Type Required Description
id_image file Required Image of the government-issued ID (JPEG, PNG) sent as multipart/form-data
Response
{
  "status": "success",
  "is_valid": true,
  "confidence": 0.98,
  "id_type": "drivers_license",
  "verification_details": {
    "name": "Alice Smith",
    "date_of_birth": "1990-03-15",
    "expiry_date": "2028-03-15",
    "id_number": "D1234567",
    "state": "CA"
  }
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/file/id/verify" \
  -H "X-API-Key: YOUR_API_KEY" \
  -F "id_image=@drivers_license.jpg"
import requests

url = "https://api.fuseais.com/api/v1/file/id/verify"
headers = {"X-API-Key": "YOUR_API_KEY"}

with open("drivers_license.jpg", "rb") as f:
    response = requests.post(url, headers=headers, files={"id_image": f})

data = response.json()
print(f"Valid: {data['is_valid']}, Type: {data['id_type']}")
print(data["verification_details"])
// Use OkHttp or similar library for multipart file uploads.
// OkHttpClient client = new OkHttpClient();
// RequestBody fileBody = RequestBody.create(new File("drivers_license.jpg"),
//     MediaType.parse("image/jpeg"));
// MultipartBody body = new MultipartBody.Builder()
//     .setType(MultipartBody.FORM)
//     .addFormDataPart("id_image", "drivers_license.jpg", fileBody)
//     .build();
// Request request = new Request.Builder()
//     .url("https://api.fuseais.com/api/v1/file/id/verify")
//     .header("X-API-Key", "YOUR_API_KEY")
//     .post(body)
//     .build();

Summarize Text

POST
/llm/summarize

Summarize a long piece of text into a shorter form. Supports paragraph and bullet-list output formats, and configurable minimum/maximum output length.

Request Parameters
Parameter Type Required Description
text string Required The text to summarize
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
max_length integer Optional Maximum character length of the summary (default: 500)
min_length integer Optional Minimum character length of the summary (default: 100)
format string Optional Output format: "paragraph" (default) or "bullets"
Request Body Example
{
  "text": "The quarterly earnings report shows significant growth across all business units...",
  "user_id": "user123",
  "max_length": 300,
  "format": "bullets"
}
Response
{
  "status": "success",
  "summary": "- Revenue increased 18% year-over-year\n- Operating margin expanded to 24%\n- All regions exceeded targets",
  "original_length": 4200,
  "summary_length": 112,
  "tokens_used": 820,
  "tokens_remaining": 9180
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/llm/summarize" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "The quarterly earnings report shows significant growth...",
    "user_id": "user123",
    "max_length": 300,
    "format": "bullets"
  }'
import requests

url = "https://api.fuseais.com/api/v1/llm/summarize"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "text": "The quarterly earnings report shows significant growth...",
    "user_id": "user123",
    "max_length": 300,
    "format": "bullets"
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
print(data["summary"])
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class SummarizeExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"text\":\"The quarterly earnings report...\",\"user_id\":\"user123\",\"max_length\":300,\"format\":\"bullets\"}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/llm/summarize"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Format Output

POST
/llm/format/{format_type}

Convert unstructured text into a specific output format. For json, supply an output_schema and the result is parsed and validated against it — an output that violates the contract comes back with schema_valid: false and the specific failures, rather than silently passing. The format_type path parameter selects the target format.

Path Parameter
ValueDescription
jsonStructured JSON object
csvComma-separated values
htmlHTML markup
txtOrganized plain text
Request Parameters
ParameterTypeRequiredDescription
text string Required The text to format
output_schema object Optional JSON format only. A JSON Schema describing the contract the output must satisfy. The result is parsed and validated against it, and the response reports schema_valid and validation_errors
repair boolean Optional When validation fails, make one corrective retry that feeds the errors back to the model (default false; costs a second call)
Request Body Example
{
  "text": "Name: Alice Smith, Age: 30, Role: Engineer",
  "output_schema": {
    "type": "object",
    "properties": {
      "name": {"type": "string"},
      "age": {"type": "integer"}
    },
    "required": ["name", "age"],
    "additionalProperties": false
  },
  "repair": true
}
Response
{
  "status": "success",
  "formatted_data": {"name": "Alice Smith", "age": 30},
  "schema_valid": true,
  "validation_errors": [],
  "tokens_used": 48,
  "tokens_remaining": 1999952
}
Sample Code
cURL
Python
curl -X POST "https://api.fuseais.com/api/v1/llm/format/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "Name: Alice Smith, Age: 34, Department: Engineering"
  }'
import requests

format_type = "json"  # json | csv | html | txt
url = f"https://api.fuseais.com/api/v1/llm/format/{format_type}"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {"content": "Name: Alice Smith, Age: 34, Department: Engineering"}

response = requests.post(url, json=payload, headers=headers)
print(response.json()["result"])

Agent Execute

POST
/llm/agent/execute

Execute a task using a named agent that can chain multiple tools and LLM reasoning steps. Returns the final result along with the number of reasoning steps taken.

Request Parameters
Parameter Type Required Description
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
agent_id string Required ID of the agent to execute
input string Required The task or question to send to the agent
context object Optional Additional key-value context passed to the agent
Request Body Example
{
  "user_id": "user123",
  "agent_id": "research-agent",
  "input": "Summarize the latest SEC filings for ACME Corp and flag any risks.",
  "context": {"year": 2026, "industry": "technology"}
}
Response
{
  "status": "success",
  "agent_id": "research-agent",
  "result": "ACME Corp's most recent 10-K filing highlights...",
  "steps_taken": 4,
  "tokens_used": 3200,
  "tokens_remaining": 6800
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/llm/agent/execute" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "agent_id": "research-agent",
    "input": "Summarize the latest SEC filings for ACME Corp and flag any risks."
  }'
import requests

url = "https://api.fuseais.com/api/v1/llm/agent/execute"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "user_id": "user123",
    "agent_id": "research-agent",
    "input": "Summarize the latest SEC filings for ACME Corp and flag any risks."
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
print(f"Steps taken: {data['steps_taken']}")
print(data["result"])
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class AgentExecuteExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"user_id\":\"user123\",\"agent_id\":\"research-agent\","
            + "\"input\":\"Summarize the latest SEC filings for ACME Corp.\"}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/llm/agent/execute"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Submit Feedback

POST
/llm/feedback

Submit positive or negative feedback on a previous LLM response. Use the request_id returned by the /llm/query endpoint to associate feedback with the correct response.

Request Parameters
Parameter Type Required Description
request_id string Required The request_id from the LLM query response
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
feedback string Required Feedback rating: "positive" or "negative"
comments string Optional Free-text explanation of the feedback
Request Body Example
{
  "request_id": "550e8400-e29b-41d4-a716-446655440000",
  "user_id": "user123",
  "feedback": "positive",
  "comments": "The response was accurate and well-structured."
}
Response
{
  "status": "success"
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/llm/feedback" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "request_id": "550e8400-e29b-41d4-a716-446655440000",
    "user_id": "user123",
    "feedback": "positive",
    "comments": "Very helpful response."
  }'
import requests

url = "https://api.fuseais.com/api/v1/llm/feedback"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "request_id": "550e8400-e29b-41d4-a716-446655440000",
    "user_id": "user123",
    "feedback": "positive",
    "comments": "Very helpful response."
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())  # {"status": "success"}
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class SubmitFeedbackExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"request_id\":\"550e8400-e29b-41d4-a716-446655440000\","
            + "\"user_id\":\"user123\",\"feedback\":\"positive\"}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/llm/feedback"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Send SMS

POST
/tools/sms/send

Send an SMS message using Twilio. Users must provide their own Twilio credentials. See setup instructions below.

Request Parameters
Parameter Type Required Description
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
to_number string Required Recipient phone number in E.164 format (e.g., +15551234567)
message string Required Message body text (max 1600 characters)
from_number string Required Your Twilio phone number (sender) in E.164 format
account_sid string Required Your Twilio Account SID
auth_token string Required Your Twilio Auth Token
Request Body Example
{
    "user_id": "user123",
    "to_number": "+15551234567",
    "message": "Hello from FuseAIs API!",
    "from_number": "+18551234567",
    "account_sid": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "auth_token": "your_auth_token_here"
}
Response
{
    "status": "success",
    "message_sid": "SM3e370028fc522e292f3d4ba8b1315c3b",
    "to": "+15551234567",
    "from": "+18551234567",
    "body": "Hello from FuseAIs API!",
    "segments": "1",
    "price": null,
    "price_unit": "USD",
    "status_detail": "queued",
    "date_created": "2026-01-18T20:40:40+00:00"
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/tools/sms/send" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{
    "user_id": "user123",
    "to_number": "+15551234567",
    "message": "Hello from FuseAIs API!",
    "from_number": "+18551234567",
    "account_sid": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "auth_token": "your_auth_token_here"
  }'
import requests

url = "https://api.fuseais.com/api/v1/tools/sms/send"
headers = {
    "Content-Type": "application/json",
    "X-API-Key": "YOUR_API_KEY"
}

payload = {
    "user_id": "user123",
    "to_number": "+15551234567",
    "message": "Hello from FuseAIs API!",
    "from_number": "+18551234567",
    "account_sid": "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    "auth_token": "your_auth_token_here"
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()

if data["status"] == "success":
    print(f"SMS sent successfully!")
    print(f"Message SID: {data['message_sid']}")
    print(f"Status: {data['status_detail']}")
else:
    print(f"SMS failed: {data}")
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
import java.util.HashMap;

public class SMSSendExample {
    public static void main(String[] args) {
        try {
            HttpClient client = HttpClient.newHttpClient();
            ObjectMapper objectMapper = new ObjectMapper();

            // Build request payload
            Map<String, Object> payload = new HashMap<>();
            payload.put("user_id", "user123");
            payload.put("to_number", "+15551234567");
            payload.put("message", "Hello from FuseAIs API!");
            payload.put("from_number", "+18551234567");
            payload.put("account_sid", "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
            payload.put("auth_token", "your_auth_token_here");

            String requestBody = objectMapper.writeValueAsString(payload);

            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.fuseais.com/api/v1/tools/sms/send"))
                .header("Content-Type", "application/json")
                .header("X-API-Key", "YOUR_API_KEY")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

            HttpResponse<String> response = client.send(request,
                HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 200) {
                JsonNode jsonResponse = objectMapper.readTree(response.body());

                String status = jsonResponse.get("status").asText();
                if ("success".equals(status)) {
                    System.out.println("SMS sent successfully!");
                    System.out.println("Message SID: " +
                        jsonResponse.get("message_sid").asText());
                    System.out.println("Status: " +
                        jsonResponse.get("status_detail").asText());
                }
            } else {
                System.out.println("SMS failed: HTTP " + response.statusCode());
            }

        } catch (Exception e) {
            System.err.println("Error sending SMS: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
Setting Up Twilio

Why use Twilio?

Twilio is a cloud communications platform that provides APIs for sending SMS messages, making phone calls, and more. This integration allows you to programmatically send SMS messages to any phone number worldwide.

Step 1: Create a Twilio Account

  1. Go to Twilio Sign Up
  2. Create a free account (includes trial credits)
  3. Verify your email and phone number

Step 2: Get Your Credentials

  1. Log in to the Twilio Console
  2. On the Dashboard, find your Account SID (starts with "AC")
  3. Click on "Show" to reveal your Auth Token
  4. Copy both values - these are your account_sid and auth_token parameters

Step 3: Get a Twilio Phone Number

  1. In the Twilio Console, go to "Phone Numbers" → "Manage" → "Buy a number"
  2. Search for a number with SMS capability
  3. Purchase the number (free trial accounts get one free number)
  4. Copy the phone number in E.164 format (e.g., +18551234567) - this is your from_number

Trial Account Limitations: Free trial accounts can only send SMS to verified phone numbers. To send to any number, you'll need to upgrade your account. See Twilio's trial guide for details.

Message Status Values
Status Description
queued Message is queued for sending
sending Message is being sent
sent Message was successfully sent to the carrier
delivered Message was delivered to the recipient
failed Message could not be sent
undelivered Carrier failed to deliver the message

Send Email (Gmail)

POST
/tools/email/send

Send emails via Gmail API. Requires OAuth access token with gmail.send scope. Supports plain text and HTML emails, CC/BCC, and email threading.

Token Refresh: Gmail access tokens expire after 1 hour. For long-lived integrations, provide refresh_token, client_id, and client_secret - the API will automatically refresh expired tokens.
Request Parameters
Parameter Type Required Description
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
access_token string Required* Gmail OAuth access token (can be expired if refresh credentials provided)
refresh_token string Optional OAuth refresh token for auto-refresh when access_token expires
client_id string Optional Google OAuth client ID (required with refresh_token)
client_secret string Optional Google OAuth client secret (required with refresh_token)
to_email string Required Recipient email (or comma-separated list)
subject string Required Email subject line
body string Required Plain text email body
from_email string Optional Sender email (defaults to authenticated user)
cc array Optional List of CC recipients
bcc array Optional List of BCC recipients
html_body string Optional HTML version of email body
thread_id string Optional Gmail thread ID to continue conversation
reply_to_message_id string Optional Message-ID header for threading
Request Example
{
    "user_id": "user123",
    "access_token": "ya29.a0AfH6SMBx...",
    "to_email": "recipient@example.com",
    "subject": "Hello from FuseAIs",
    "body": "This is a test email sent via the API.",
    "html_body": "<h1>Hello</h1><p>This is a <b>test</b> email.</p>"
}
Response
{
    "status": "success",
    "message_id": "18d1234567890abc",
    "thread_id": "18d1234567890abc",
    "to": "recipient@example.com",
    "subject": "Hello from FuseAIs"
}
Sample Code
cURL
Python
curl -X POST "https://api.fuseais.com/api/v1/tools/email/send" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{
    "user_id": "user123",
    "access_token": "ya29.a0AfH6SMBx...",
    "to_email": "recipient@example.com",
    "subject": "Hello from FuseAIs",
    "body": "This is a test email."
  }'
import requests

url = "https://api.fuseais.com/api/v1/tools/email/send"
headers = {
    "Content-Type": "application/json",
    "X-API-Key": "YOUR_API_KEY"
}

payload = {
    "user_id": "user123",
    "access_token": "ya29.a0AfH6SMBx...",  # Gmail OAuth token
    "to_email": "recipient@example.com",
    "subject": "Hello from FuseAIs",
    "body": "This is a test email.",
    "html_body": "<h1>Hello</h1><p>Test email</p>"
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()

if data["status"] == "success":
    print(f"Email sent! Message ID: {data['message_id']}")
    print(f"Thread ID: {data['thread_id']}")

Read Emails (Gmail)

POST
/tools/email/list

List emails from Gmail inbox with optional search filters. Supports automatic token refresh for long-lived integrations.

Request Parameters
Parameter Type Required Description
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
access_token string Required* Gmail OAuth access token
refresh_token string Optional OAuth refresh token for auto-refresh
client_id string Optional Google OAuth client ID
client_secret string Optional Google OAuth client secret
query string Optional Gmail search query (e.g., "is:unread", "from:boss@company.com")
max_results integer Optional Maximum messages to return (default: 10, max: 100)
label_ids array Optional Filter by labels (e.g., ["INBOX", "UNREAD"])
Common Gmail Search Queries
Query Description
is:unreadUnread messages
is:starredStarred messages
from:someone@example.comFrom specific sender
to:meSent directly to you
subject:meetingSubject contains "meeting"
newer_than:1dMessages from last day
has:attachmentHas attachments
Response
{
    "status": "success",
    "count": 2,
    "messages": [
        {
            "id": "18d1234567890abc",
            "thread_id": "18d1234567890abc",
            "from": "sender@example.com",
            "to": "you@company.com",
            "subject": "Project Update",
            "date": "Sat, 18 Jan 2026 15:30:00 -0500",
            "snippet": "Here's the latest update on the project...",
            "label_ids": ["INBOX", "UNREAD"]
        }
    ]
}
POST
/tools/email/get

Get full content of a specific email by message ID. Supports token refresh.

Request
{
    "user_id": "user123",
    "access_token": "ya29.a0AfH6SMBx...",
    "message_id": "18d1234567890abc",
    "refresh_token": "1//0gxxxxxxx...",
    "client_id": "123456789.apps.googleusercontent.com",
    "client_secret": "GOCSPX-xxxxxxx"
}
Response
{
    "status": "success",
    "id": "18d1234567890abc",
    "thread_id": "18d1234567890abc",
    "from": "sender@example.com",
    "to": "you@company.com",
    "subject": "Project Update",
    "date": "Sat, 18 Jan 2026 15:30:00 -0500",
    "body_text": "Here's the latest update on the project...",
    "body_html": "<div>Here's the latest update...</div>",
    "snippet": "Here's the latest update on the project...",
    "label_ids": ["INBOX", "IMPORTANT"]
}
POST
/tools/email/mark-read

Mark an email as read. Supports token refresh.

Request
{
    "user_id": "user123",
    "access_token": "ya29.a0AfH6SMBx...",
    "message_id": "18d1234567890abc",
    "refresh_token": "1//0gxxxxxxx...",
    "client_id": "123456789.apps.googleusercontent.com",
    "client_secret": "GOCSPX-xxxxxxx"
}
Response
{
    "status": "success",
    "message_id": "18d1234567890abc",
    "marked_as": "read"
}
Setting Up Gmail API Access

For a company bot inbox:

Use a Google Workspace service account with domain-wide delegation, or set up OAuth for a dedicated bot account that the team shares access to.

Step 1: Create Google Cloud Project

  1. Go to Google Cloud Console
  2. Create a new project or select existing
  3. Navigate to "APIs & Services" → "Library"
  4. Search for "Gmail API" and enable it

Step 2: Configure OAuth Consent Screen

  1. Go to "APIs & Services" → "OAuth consent screen"
  2. Select "Internal" (for Workspace) or "External"
  3. Fill in app name and required fields
  4. Add scopes:
    • https://www.googleapis.com/auth/gmail.send
    • https://www.googleapis.com/auth/gmail.readonly
    • https://www.googleapis.com/auth/gmail.modify

Step 3: Create OAuth Credentials

  1. Go to "APIs & Services" → "Credentials"
  2. Click "Create Credentials" → "OAuth client ID"
  3. Select application type (Web, Desktop, etc.)
  4. Download the client credentials JSON
  5. Use OAuth flow to obtain access tokens

Automatic Token Refresh:

Access tokens expire after 1 hour. The API automatically refreshes expired tokens when you provide refresh_token, client_id, and client_secret in your requests. This enables long-lived integrations without manual token management.

Send Slack Message

POST
/tools/slack/send

Send messages to Slack channels or users. Supports two methods: Incoming Webhooks (simple) or Bot Token API (full control).

Request Parameters
Parameter Type Required Description
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
message string Required Message text to send
Method 1: Webhook (Simple)
webhook_url string Optional* Slack Incoming Webhook URL. Use this for simple channel posts.
username string Optional Custom username for the message (webhook only)
icon_emoji string Optional Emoji for bot icon, e.g., ":robot_face:" (webhook only)
Method 2: Bot Token (Full Control)
bot_token string Optional* Slack Bot OAuth Token (xoxb-...). Use this for full API access.
channel string Optional Channel ID or name (required with bot_token for channel posts)
dm_user_id string Optional Slack user ID for direct message (alternative to channel)
thread_ts string Optional Thread timestamp to reply in a thread
Rich Formatting (Both Methods)
blocks array Optional Slack Block Kit blocks for rich formatting

* Either webhook_url OR bot_token is required

Webhook Example
{
    "user_id": "user123",
    "message": "Hello from FuseAIs API!",
    "webhook_url": "https://hooks.slack.com/services/T.../B.../xxx",
    "username": "FuseAIs Bot",
    "icon_emoji": ":robot_face:"
}
Bot Token Example (Channel Post)
{
    "user_id": "user123",
    "message": "Hello team!",
    "bot_token": "xoxb-your-bot-token",
    "channel": "#general"
}
Bot Token Example (Direct Message)
{
    "user_id": "user123",
    "message": "Hello! This is a private message.",
    "bot_token": "xoxb-your-bot-token",
    "dm_user_id": "U1234567890"
}
Response (Webhook)
{
    "status": "success",
    "method": "webhook",
    "message": "Message sent successfully"
}
Response (Bot Token)
{
    "status": "success",
    "method": "bot_api",
    "message_ts": "1234567890.123456",
    "channel": "C1234567890",
    "message": "Hello team!"
}
Sample Code
cURL
Python
Java
# Using Webhook
curl -X POST "https://api.fuseais.com/api/v1/tools/slack/send" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{
    "user_id": "user123",
    "message": "Hello from FuseAIs!",
    "webhook_url": "https://hooks.slack.com/services/T.../B.../xxx"
  }'

# Using Bot Token
curl -X POST "https://api.fuseais.com/api/v1/tools/slack/send" \
  -H "Content-Type: application/json" \
  -H "X-API-Key: YOUR_API_KEY" \
  -d '{
    "user_id": "user123",
    "message": "Hello team!",
    "bot_token": "xoxb-your-bot-token",
    "channel": "#general"
  }'
import requests

url = "https://api.fuseais.com/api/v1/tools/slack/send"
headers = {
    "Content-Type": "application/json",
    "X-API-Key": "YOUR_API_KEY"
}

# Method 1: Using Webhook
payload_webhook = {
    "user_id": "user123",
    "message": "Hello from FuseAIs!",
    "webhook_url": "https://hooks.slack.com/services/T.../B.../xxx",
    "username": "FuseAIs Bot",
    "icon_emoji": ":rocket:"
}

# Method 2: Using Bot Token
payload_bot = {
    "user_id": "user123",
    "message": "Hello team!",
    "bot_token": "xoxb-your-bot-token",
    "channel": "#general"
}

response = requests.post(url, json=payload_webhook, headers=headers)
data = response.json()

if data["status"] == "success":
    print(f"Message sent via {data['method']}")
else:
    print(f"Failed: {data}")
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
import java.util.HashMap;

public class SlackSendExample {
    public static void main(String[] args) {
        try {
            HttpClient client = HttpClient.newHttpClient();
            ObjectMapper objectMapper = new ObjectMapper();

            // Using Webhook method
            Map<String, Object> payload = new HashMap<>();
            payload.put("user_id", "user123");
            payload.put("message", "Hello from FuseAIs!");
            payload.put("webhook_url", "https://hooks.slack.com/services/T.../B.../xxx");

            String requestBody = objectMapper.writeValueAsString(payload);

            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.fuseais.com/api/v1/tools/slack/send"))
                .header("Content-Type", "application/json")
                .header("X-API-Key", "YOUR_API_KEY")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

            HttpResponse<String> response = client.send(request,
                HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() == 200) {
                JsonNode jsonResponse = objectMapper.readTree(response.body());
                System.out.println("Message sent via: " +
                    jsonResponse.get("method").asText());
            }

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}
Setting Up Slack Integration

Which method should I use?

  • Webhook: Simple setup, posts to one specific channel. Best for notifications and alerts.
  • Bot Token: Full API access, post to any channel, send DMs, reply to threads. Best for interactive bots.

Option 1: Setting Up Incoming Webhook

  1. Go to Slack API Apps
  2. Click "Create New App" → "From scratch"
  3. Name your app and select your workspace
  4. Go to "Incoming Webhooks" in the sidebar
  5. Toggle "Activate Incoming Webhooks" to On
  6. Click "Add New Webhook to Workspace"
  7. Select the channel and click "Allow"
  8. Copy the Webhook URL - this is your webhook_url

Option 2: Setting Up Bot Token

  1. Go to Slack API Apps
  2. Click "Create New App" → "From scratch"
  3. Name your app and select your workspace
  4. Go to "OAuth & Permissions" in the sidebar
  5. Under "Scopes" → "Bot Token Scopes", add:
    • chat:write - Send messages
    • chat:write.public - Send to public channels without joining
    • im:write - Send direct messages (optional)
  6. Click "Install to Workspace" at the top
  7. Copy the "Bot User OAuth Token" (starts with xoxb-) - this is your bot_token

Note: For bot tokens, you may need to invite the bot to private channels with /invite @YourBotName before it can post there.

Receive Slack Messages

POST
/tools/slack/receive

Webhook endpoint for receiving Slack messages via the Events API. Configure this URL in your Slack app to receive real-time message events.

How it works:

When users send messages in Slack channels or DMs where your bot is present, Slack sends an HTTP POST to this endpoint. Your application can then process the message, trigger AI agents, store in archives, and send responses back via the /slack/send endpoint.

Event Types Handled
Event Type Description
url_verification Initial handshake when configuring the webhook URL. Returns the challenge token.
event_callback (message) New message in a channel or DM. Contains user, channel, text, and timestamp.
event_callback (app_mention) Someone mentioned your bot with @BotName.
Incoming Event Payload (Message)
{
    "type": "event_callback",
    "token": "verification_token",
    "team_id": "T1234567890",
    "event_id": "Ev1234567890",
    "event_time": 1234567890,
    "event": {
        "type": "message",
        "user": "U1234567890",
        "text": "Hello bot, can you help me?",
        "channel": "C1234567890",
        "ts": "1234567890.123456"
    }
}
Response
{
    "status": "success",
    "event_type": "message",
    "user": "U1234567890",
    "channel": "C1234567890",
    "message_ts": "1234567890.123456",
    "message": "Event processed"
}
Setting Up Event Subscriptions
  1. Go to your Slack App Settings
  2. Select your app and go to "Event Subscriptions" in the sidebar
  3. Toggle "Enable Events" to On
  4. Set the Request URL to: https://api.fuseais.com/api/v1/tools/slack/receive
  5. Slack will send a verification challenge - the endpoint handles this automatically
  6. Under "Subscribe to bot events", add:
    • message.channels - Messages in public channels
    • message.groups - Messages in private channels
    • message.im - Direct messages to the bot
    • app_mention - When someone @mentions the bot
  7. Click "Save Changes"
  8. Reinstall the app to your workspace if prompted
Building a Conversational Bot

To create a two-way conversation flow:

# Pseudocode for handling incoming Slack messages

# 1. Receive message via webhook
incoming_event = receive_slack_webhook(request)

# 2. Extract message details
user_id = incoming_event["event"]["user"]
channel = incoming_event["event"]["channel"]
message_text = incoming_event["event"]["text"]
thread_ts = incoming_event["event"]["ts"]

# 3. Process with AI agent
response = await llm_service.query(
    prompt=message_text,
    model="aws_claude",
    system_prompt="You are a helpful assistant..."
)

# 4. Send response back to Slack (reply in thread)
await slack_service.send_via_bot(
    bot_token="xoxb-your-token",
    channel=channel,
    message=response["response"],
    thread_ts=thread_ts  # Reply in same thread
)

Important Notes:

  • The endpoint ignores bot messages to prevent infinite loops
  • Slack expects a 200 response within 3 seconds - do heavy processing async
  • Use thread_ts to reply in the same thread for organized conversations
  • Store messages in an archive to maintain conversation context for AI

Create Calendar Event

POST /tools/calendar/create

Create a new event in Google Calendar. Supports regular events and all-day events.

Google Calendar OAuth Setup:
  1. Create a project in Google Cloud Console
  2. Enable the Google Calendar API
  3. Create OAuth 2.0 credentials (Web application type)
  4. Get access token with scope: https://www.googleapis.com/auth/calendar

Request Body

ParameterTypeRequiredDescription
user_idstringYesUser identifier for rate limiting
access_tokenstringYes*Google Calendar OAuth access token
titlestringYesEvent title/summary
start_timestringYesISO 8601 format (e.g., 2026-01-20T10:00:00 or 2026-01-20 for all-day)
end_timestringYesISO 8601 format
descriptionstringNoEvent description
locationstringNoEvent location
attendeesarrayNoList of attendee email addresses
calendar_idstringNoCalendar ID (default: "primary")
timezonestringNoTimezone (e.g., "America/New_York")
send_updatesstringNo"all", "externalOnly", or "none" (default: "none")
refresh_tokenstringNoFor automatic token refresh
client_idstringNoRequired with refresh_token
client_secretstringNoRequired with refresh_token

Example Request

curl
curl -X POST "/tools/calendar/create" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "access_token": "ya29.your_access_token",
    "title": "Team Meeting",
    "start_time": "2026-01-20T10:00:00",
    "end_time": "2026-01-20T11:00:00",
    "description": "Weekly sync meeting",
    "location": "Conference Room A",
    "attendees": ["colleague@example.com"],
    "timezone": "America/New_York"
  }'

Example Response

json
{
  "status": "success",
  "event_id": "abc123def456",
  "html_link": "https://www.google.com/calendar/event?eid=...",
  "title": "Team Meeting",
  "start": {"dateTime": "2026-01-20T10:00:00-05:00", "timeZone": "America/New_York"},
  "end": {"dateTime": "2026-01-20T11:00:00-05:00", "timeZone": "America/New_York"},
  "location": "Conference Room A",
  "attendees": ["colleague@example.com"],
  "created": "2026-01-19T15:30:00.000Z"
}

List Calendar Events

POST /tools/calendar/list

List upcoming calendar events. By default returns events starting from now.

Request Body

ParameterTypeRequiredDescription
user_idstringYesUser identifier for rate limiting
access_tokenstringYes*Google Calendar OAuth access token
calendar_idstringNoCalendar ID (default: "primary")
time_minstringNoLower bound (ISO 8601). Default: now
time_maxstringNoUpper bound (ISO 8601)
max_resultsintegerNoMaximum events to return (default: 10, max: 100)
querystringNoFree text search query
refresh_tokenstringNoFor automatic token refresh
client_idstringNoRequired with refresh_token
client_secretstringNoRequired with refresh_token

Example Request

curl
curl -X POST "/tools/calendar/list" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "access_token": "ya29.your_access_token",
    "time_min": "2026-01-20T00:00:00Z",
    "max_results": 10
  }'

Example Response

json
{
  "status": "success",
  "count": 3,
  "events": [
    {
      "event_id": "abc123",
      "title": "Team Meeting",
      "start": {"dateTime": "2026-01-20T10:00:00-05:00"},
      "end": {"dateTime": "2026-01-20T11:00:00-05:00"},
      "location": "Conference Room A",
      "status": "confirmed",
      "html_link": "https://www.google.com/calendar/event?eid=..."
    },
    ...
  ],
  "next_page_token": null
}

Get Calendar Event

POST /tools/calendar/get

Get detailed information about a specific calendar event.

Request Body

ParameterTypeRequiredDescription
user_idstringYesUser identifier for rate limiting
access_tokenstringYes*Google Calendar OAuth access token
event_idstringYesEvent ID to retrieve
calendar_idstringNoCalendar ID (default: "primary")
refresh_tokenstringNoFor automatic token refresh
client_idstringNoRequired with refresh_token
client_secretstringNoRequired with refresh_token

Example Request

curl
curl -X POST "/tools/calendar/get" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "access_token": "ya29.your_access_token",
    "event_id": "abc123def456"
  }'

Update Calendar Event

POST /tools/calendar/update

Update an existing calendar event. Only the provided fields will be updated.

Request Body

ParameterTypeRequiredDescription
user_idstringYesUser identifier for rate limiting
access_tokenstringYes*Google Calendar OAuth access token
event_idstringYesEvent ID to update
titlestringNoNew event title
start_timestringNoNew start time (ISO 8601)
end_timestringNoNew end time (ISO 8601)
descriptionstringNoNew description
locationstringNoNew location
attendeesarrayNoNew list of attendees
calendar_idstringNoCalendar ID (default: "primary")
send_updatesstringNo"all", "externalOnly", or "none"
refresh_tokenstringNoFor automatic token refresh
client_idstringNoRequired with refresh_token
client_secretstringNoRequired with refresh_token

Example Request

curl
curl -X POST "/tools/calendar/update" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "access_token": "ya29.your_access_token",
    "event_id": "abc123def456",
    "title": "Updated Meeting Title",
    "location": "New Conference Room"
  }'

Delete Calendar Event

POST /tools/calendar/delete

Delete a calendar event.

Request Body

ParameterTypeRequiredDescription
user_idstringYesUser identifier for rate limiting
access_tokenstringYes*Google Calendar OAuth access token
event_idstringYesEvent ID to delete
calendar_idstringNoCalendar ID (default: "primary")
send_updatesstringNo"all", "externalOnly", or "none"
refresh_tokenstringNoFor automatic token refresh
client_idstringNoRequired with refresh_token
client_secretstringNoRequired with refresh_token

Example Request

curl
curl -X POST "/tools/calendar/delete" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "access_token": "ya29.your_access_token",
    "event_id": "abc123def456"
  }'

Example Response

json
{
  "status": "success",
  "event_id": "abc123def456",
  "message": "Event deleted"
}

Scrape Webpage

POST /tools/scrape/webpage

Extract text content from a web page URL. Uses multiple fallback strategies including CloudScraper and headless Chrome for JavaScript-heavy pages. Rate limited to 1,000 scrapes per month per user.

Request Body

ParameterTypeRequiredDescription
user_idstringYesUser identifier for rate limiting
urlstringYesURL of the webpage to scrape
max_lengthintegerNoMaximum characters to return (default: 100,000)

Example Request

curl
curl -X POST "/tools/scrape/webpage" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "url": "https://example.com/article"
  }'

Example Response

json
{
  "status": "success",
  "url": "https://example.com/article",
  "title": "Example Article Title",
  "text": "The full text content of the page...",
  "char_count": 5432,
  "method": "cloudscraper"
}

Scrape PDF URL

POST /tools/scrape/pdf

Download and extract text from a PDF at a given URL. Handles anti-bot detection and uses AWS Textract for text extraction. Rate limited to 1,000 scrapes per month per user.

Request Body

ParameterTypeRequiredDescription
user_idstringYesUser identifier for rate limiting
urlstringYesURL of the PDF file
max_pagesintegerNoMaximum pages to extract (default: all, up to the 100-page limit; larger documents are rejected with a 400)
save_to_s3booleanNoSave PDF to S3 for later processing

Example Request

curl
curl -X POST "/tools/scrape/pdf" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "url": "https://example.com/document.pdf",
    "max_pages": 50
  }'

Example Response

json
{
  "status": "success",
  "url": "https://example.com/document.pdf",
  "text": "Extracted text from the PDF...",
  "page_count": 25,
  "char_count": 45230
}

Async PDF Extraction

POST /tools/async/pdf

Start an async PDF extraction job for large documents. Returns immediately with a job ID for polling. Use this for PDFs that may take longer to process.

Request Body

ParameterTypeRequiredDescription
user_idstringYesUser identifier for rate limiting and job ownership
urlstringYesURL of the PDF file to process
max_pagesintegerNoMaximum pages to extract (default: all, up to the 100-page limit; larger documents are rejected with a 400)
ttl_daysintegerNoDays until job auto-deletion (1-30, default: 7)

Example Request

curl
curl -X POST "/tools/async/pdf" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "url": "https://example.com/large-document.pdf",
    "max_pages": 100,
    "ttl_days": 7
  }'

Example Response

json
{
  "status": "accepted",
  "job_id": "550e8400-e29b-41d4-a716-446655440000",
  "message": "PDF extraction job started. Poll the job status endpoint to check progress.",
  "poll_url": "/jobs/550e8400-e29b-41d4-a716-446655440000?user_id=user123"
}

Async Audio Transcription

POST /tools/async/audio

Start an async audio transcription job using AWS Transcribe. Supports long audio files (up to hours). Returns immediately - transcription runs independently. Monthly limit of 500,000 tokens (~50 hours of audio).

Supported Formats: mp3, mp4, wav, flac, ogg, amr, webm, m4a

Request Body

ParameterTypeRequiredDescription
user_idstringYesUser identifier for rate limiting and job ownership
s3_keystringOne of*S3 key of already-uploaded audio file
urlstringOne of*URL of audio file to download and transcribe
language_codestringNoLanguage code (default: "en-US"). Examples: "es-ES", "fr-FR"
ttl_daysintegerNoDays until job auto-deletion (1-30, default: 7)

* Provide either s3_key OR url, not both.

Example Request (URL)

curl
curl -X POST "/tools/async/audio" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "url": "https://example.com/podcast.mp3",
    "language_code": "en-US",
    "ttl_days": 7
  }'

Example Request (S3 Key)

curl
curl -X POST "/tools/async/audio" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "s3_key": "tmp/user123/session456/audio.mp3",
    "language_code": "en-US"
  }'

Example Response

json
{
  "status": "accepted",
  "job_id": "660e8400-e29b-41d4-a716-446655440001",
  "message": "Audio transcription job started. AWS Transcribe is processing. Poll the job status endpoint to check progress.",
  "poll_url": "/jobs/660e8400-e29b-41d4-a716-446655440001?user_id=user123"
}

Get Job Status

GET /jobs/{job_id}

Get the current status of an async job. For audio transcription jobs, this checks AWS Transcribe status on-demand and updates the job record if completed.

Query Parameters

ParameterTypeRequiredDescription
user_idstringYesUser ID for authorization

Example Request

curl
curl "/jobs/550e8400-e29b-41d4-a716-446655440000?user_id=user123"

Example Response (Processing)

json
{
  "job_id": "550e8400-e29b-41d4-a716-446655440000",
  "user_id": "user123",
  "status": "processing",
  "job_type": "audio_transcribe",
  "input": {
    "url": "https://example.com/podcast.mp3",
    "language_code": "en-US"
  },
  "result_summary": {
    "transcribe_job_name": "fuseais_550e8400_abc12345",
    "source": "https://example.com/podcast.mp3"
  },
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:30:05Z"
}

Example Response (Completed)

json
{
  "job_id": "550e8400-e29b-41d4-a716-446655440000",
  "user_id": "user123",
  "status": "completed",
  "job_type": "audio_transcribe",
  "result_key": "results/user123/550e8400.../result.txt",
  "result_summary": {
    "char_count": 45230,
    "token_count": 11307,
    "language_code": "en-US"
  },
  "created_at": "2024-01-15T10:30:00Z",
  "updated_at": "2024-01-15T10:45:00Z"
}
Job Statuses:
  • pending - Job created, not yet started
  • processing - Job is running
  • completed - Job finished successfully
  • failed - Job failed (check error field)

List Jobs

GET /jobs

List all jobs for a user, optionally filtered by status.

Query Parameters

ParameterTypeRequiredDescription
user_idstringYesUser ID
statusstringNoFilter by status: pending, processing, completed, failed
limitintegerNoMax jobs to return (1-100, default: 20)

Example Request

curl
curl "/jobs?user_id=user123&status=completed&limit=10"

Example Response

json
{
  "jobs": [
    {
      "job_id": "550e8400-e29b-41d4-a716-446655440000",
      "user_id": "user123",
      "status": "completed",
      "job_type": "audio_transcribe",
      "result_summary": {"char_count": 45230, "token_count": 11307},
      "created_at": "2024-01-15T10:30:00Z",
      "updated_at": "2024-01-15T10:45:00Z"
    }
  ],
  "count": 1
}

Get Job Result

GET /jobs/{job_id}/result

Get the full result text for a completed job. Returns the extracted/transcribed text from S3.

Query Parameters

ParameterTypeRequiredDescription
user_idstringYesUser ID for authorization

Example Request

curl
curl "/jobs/550e8400-e29b-41d4-a716-446655440000/result?user_id=user123"

Example Response (Completed)

json
{
  "job_id": "550e8400-e29b-41d4-a716-446655440000",
  "status": "completed",
  "text": "The full transcribed or extracted text content...",
  "metadata": {
    "source": "https://example.com/podcast.mp3",
    "language_code": "en-US",
    "char_count": 45230,
    "token_count": 11307
  },
  "char_count": 45230
}

Example Response (Still Processing)

json
{
  "job_id": "550e8400-e29b-41d4-a716-446655440000",
  "status": "processing",
  "text": null,
  "char_count": 0,
  "error": "Job is still processing. Check back later."
}

Delete Job

DELETE /jobs/{job_id}

Delete a job and its results. Jobs are automatically deleted after the TTL expires, but you can delete them earlier if needed.

Query Parameters

ParameterTypeRequiredDescription
user_idstringYesUser ID for authorization

Example Request

curl
curl -X DELETE "/jobs/550e8400-e29b-41d4-a716-446655440000?user_id=user123"

Example Response

json
{
  "status": "success",
  "message": "Job 550e8400-e29b-41d4-a716-446655440000 deleted"
}

Upsert Documents

⚠ Not yet available. This endpoint is a placeholder and currently returns empty results. A knowledge-base build & query API is planned to replace it — do not integrate against it yet.
POST
/vectordb/documents

Insert or update a document in the vector database. If an embedding is not supplied, the service computes one from the text field. Documents are tagged with the caller's customer ID for multi-tenant isolation.

Request Parameters
Parameter Type Required Description
text string Required The document text content to store and embed
collection_name string Required Name of the vector collection to store the document in
id string Optional Document ID; auto-generated if omitted
metadata object Optional Arbitrary key-value metadata stored alongside the vector
embedding number[] Optional Pre-computed embedding vector; computed server-side if omitted
Request Body Example
{
  "text": "Quarterly revenue increased 18% year-over-year driven by enterprise sales.",
  "collection_name": "financial-docs",
  "metadata": {"source": "q1-2026-earnings.pdf", "page": 3}
}
Response
{
  "id": "doc_abc123",
  "text": "Quarterly revenue increased 18% year-over-year driven by enterprise sales.",
  "collection_name": "financial-docs",
  "metadata": {"source": "q1-2026-earnings.pdf", "page": 3},
  "embedding": null
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/vectordb/documents" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Quarterly revenue increased 18% year-over-year.",
    "collection_name": "financial-docs",
    "metadata": {"source": "q1-2026-earnings.pdf"}
  }'
import requests

url = "https://api.fuseais.com/api/v1/vectordb/documents"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "text": "Quarterly revenue increased 18% year-over-year.",
    "collection_name": "financial-docs",
    "metadata": {"source": "q1-2026-earnings.pdf"}
}

response = requests.post(url, json=payload, headers=headers)
print(response.json())
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class VectorUpsertExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"text\":\"Quarterly revenue increased 18%.\","
            + "\"collection_name\":\"financial-docs\","
            + "\"metadata\":{\"source\":\"q1-2026-earnings.pdf\"}}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/vectordb/documents"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Query Vector DB

⚠ Not yet available. This endpoint is a placeholder and currently returns empty results. A knowledge-base build & query API is planned to replace it — do not integrate against it yet.
POST
/vectordb/query

Perform a semantic search against the vector database. Results are filtered to the caller's customer tenant. Supports text queries (embedding computed server-side) or direct embedding vectors.

Request Parameters
Parameter Type Required Description
query string Required Natural-language query string
collection_name string Optional Restrict results to this collection
top_k integer Optional Number of nearest-neighbor results to return (default: 10)
filter object Optional Metadata filter object (e.g. {"source": "q1-2026-earnings.pdf"})
include_metadata boolean Optional Whether to include metadata in results (default: true)
embedding number[] Optional Pre-computed query embedding; if provided, query is used only for the response echo
Request Body Example
{
  "query": "What was the revenue growth last quarter?",
  "collection_name": "financial-docs",
  "top_k": 5,
  "filter": {"source": "q1-2026-earnings.pdf"}
}
Response
{
  "results": [
    {
      "id": "doc_abc123",
      "text": "Quarterly revenue increased 18% year-over-year driven by enterprise sales.",
      "metadata": {"source": "q1-2026-earnings.pdf", "page": 3},
      "score": 0.94
    }
  ],
  "total_results": 1,
  "query": "What was the revenue growth last quarter?"
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/vectordb/query" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What was the revenue growth last quarter?",
    "collection_name": "financial-docs",
    "top_k": 5
  }'
import requests

url = "https://api.fuseais.com/api/v1/vectordb/query"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "query": "What was the revenue growth last quarter?",
    "collection_name": "financial-docs",
    "top_k": 5
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
for r in data["results"]:
    print(f"[{r['score']:.2f}] {r['text'][:100]}")
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class VectorQueryExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"query\":\"What was the revenue growth last quarter?\","
            + "\"collection_name\":\"financial-docs\",\"top_k\":5}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/vectordb/query"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Document Code

POST
/code/document

Automatically generate inline documentation and docstrings for a code snippet. Supports multiple documentation styles and can optionally include usage examples.

Request Parameters
Parameter Type Required Description
code string Required Source code to document
language string Optional Programming language (e.g. "python", "javascript"); auto-detected if omitted
style string Optional Documentation style: "standard" (default), "detailed", or "minimal"
include_examples boolean Optional Whether to include usage examples (default: false)
Request Body Example
{
  "code": "def add(a, b):\n    return a + b",
  "language": "python",
  "style": "standard",
  "include_examples": true
}
Response
{
  "status": "success",
  "result": "def add(a, b):\n    \"\"\"Add two numbers and return their sum.\n\n    Args:\n        a: First number.\n        b: Second number.\n\n    Returns:\n        The sum of a and b.\n\n    Example:\n        >>> add(2, 3)\n        5\n    \"\"\"\n    return a + b",
  "language": "python",
  "metadata": {
    "tokens_used": 100,
    "model_used": "claude"
  }
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/code/document" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "def add(a, b):\n    return a + b",
    "language": "python",
    "include_examples": true
  }'
import requests

url = "https://api.fuseais.com/api/v1/code/document"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "code": "def add(a, b):\n    return a + b",
    "language": "python",
    "include_examples": True
}

response = requests.post(url, json=payload, headers=headers)
print(response.json()["result"])
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class DocumentCodeExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"code\":\"def add(a, b):\\n    return a + b\","
            + "\"language\":\"python\",\"include_examples\":true}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/code/document"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Audit Code

POST
/code/audit

Perform a security and best-practices audit on a code snippet. Returns a list of issues with severity, type, description, and recommended fix, plus an overall risk level.

Request Parameters
Parameter Type Required Description
code string Required Source code to audit
language string Optional Programming language; auto-detected if omitted
audit_type string Optional Audit focus: "security" (default), "performance", or "quality"
Request Body Example
{
  "code": "def process_data(user_input):\n    exec(user_input)",
  "language": "python",
  "audit_type": "security"
}
Response
{
  "status": "success",
  "result": "1 high severity security issue found",
  "metadata": {
    "tokens_used": 150,
    "model_used": "claude"
  }
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/code/audit" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "def process_data(user_input):\n    exec(user_input)",
    "language": "python",
    "audit_type": "security"
  }'
import requests

url = "https://api.fuseais.com/api/v1/code/audit"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "code": "def process_data(user_input):\n    exec(user_input)",
    "language": "python",
    "audit_type": "security"
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
print(data["result"])
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class AuditCodeExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"code\":\"def process_data(user_input):\\n    exec(user_input)\","
            + "\"language\":\"python\",\"audit_type\":\"security\"}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/code/audit"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Validate Code

POST
/code/validate

Validate code for syntax errors, logical issues, or style compliance. Returns a pass/fail result and a list of any violations found.

Request Parameters
Parameter Type Required Description
code string Required The code to validate
language string Required Programming language (e.g. "python", "javascript")
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
validation_type string Optional Type of validation: "syntax" (default), "security", or "best_practices"
Request Body Example
{
  "code": "def hello_world():\n    print('Hello, world!')",
  "language": "python",
  "user_id": "user123",
  "validation_type": "syntax"
}
Response
{
  "status": "success",
  "result": "Code validation completed",
  "metadata": {
    "tokens_used": 120,
    "model_used": "claude"
  }
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/code/validate" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "def hello_world():\n    print(\"Hello, world!\")",
    "language": "python",
    "user_id": "user123"
  }'
import requests

url = "https://api.fuseais.com/api/v1/code/validate"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "code": "def hello_world():\n    print('Hello, world!')",
    "language": "python",
    "user_id": "user123",
    "validation_type": "syntax"
}

response = requests.post(url, json=payload, headers=headers)
print(response.json()["result"])
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class ValidateCodeExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"code\":\"def hello_world():\\n    print('Hello!')\","
            + "\"language\":\"python\",\"user_id\":\"user123\"}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/code/validate"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Execute Code

POST
/code/execute

Execute Python code in a secure, sandboxed Lambda environment. The sandbox provides 60+ whitelisted packages including pandas, numpy, matplotlib, Pillow, requests, and more. Dangerous operations (exec, eval, unrestricted imports) are blocked by AST-level policy checks before execution.

Request Parameters
Parameter Type Required Description
code string Required Python source code to execute
files array Optional Files to inject into the sandbox. Each file has a name (string) and either content (base64-encoded, <4 MB) or s3_key (key in the code-exec bucket). Files are accessible inside the code via a FILES dict mapping name → path.
timeout integer Optional Maximum execution time in seconds (1–900). Defaults to 840 (14 min).
Request Body Example
{
  "code": "import pandas as pd\ndf = pd.DataFrame({'a': [1,2,3]})\nprint(df.describe())",
  "timeout": 30
}
Request with Files Example
{
  "code": "import pandas as pd\ndf = pd.read_csv(FILES['report.csv'])\nprint(df.head())",
  "files": [
    {
      "name": "report.csv",
      "s3_key": "uploads/customer123/report.csv"
    }
  ],
  "timeout": 60
}
Response (Success)
Success
Error
Policy Violation
{
  "status": "success",
  "output": "         a\ncount  3.0\nmean   2.0\nstd    1.0\nmin    1.0\n25%    1.5\n50%    2.0\n75%    2.5\nmax    3.0\n",
  "error": null,
  "stats": {
    "execution_time_ms": 10.71,
    "output_size_bytes": 99,
    "had_errors": false,
    "timestamp": "2026-02-12T14:10:12.022099"
  },
  "output_files": []
}
{
  "status": "error",
  "output": "",
  "error": {
    "error_type": "NameError",
    "message": "name 'undefined_var' is not defined",
    "line_number": 3,
    "code_context": {"3": "print(undefined_var)"},
    "traceback": "Traceback (most recent call last):\n  ..."
  },
  "stats": {
    "execution_time_ms": 1.2,
    "output_size_bytes": 0,
    "had_errors": true
  },
  "output_files": []
}
{
  "status": "error",
  "output": "",
  "error": {
    "error_type": "PolicyViolation",
    "message": "Use of 'exec()' is not permitted in sandboxed execution"
  },
  "stats": {},
  "output_files": []
}
Output Files

Code can write files to the /tmp/agent_output/ directory. These are automatically collected, uploaded to S3, and returned as presigned download URLs:

"output_files": [
  {
    "name": "chart.png",
    "url": "https://fuseais-code-exec-files.s3.amazonaws.com/agent-outputs/...",
    "s3_key": "agent-outputs/abc123/chart.png",
    "size_bytes": 24576
  }
]
Sample Code
cURL
JavaScript
Python
curl -X POST \
  "https://api.fuseais.com/api/v1/code/execute" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "import pandas as pd\ndf = pd.DataFrame({\"a\": [1,2,3]})\nprint(df.describe())",
    "timeout": 30
  }'
const response = await fetch('https://api.fuseais.com/api/v1/code/execute', {
  method: 'POST',
  headers: {
    'X-API-Key': 'YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    code: "import pandas as pd\ndf = pd.DataFrame({'a': [1,2,3]})\nprint(df.describe())",
    timeout: 30
  })
});

const result = await response.json();
console.log(result.output);

// If the code generated files:
if (result.output_files?.length) {
  result.output_files.forEach(f =>
    console.log(`${f.name}: ${f.url}`)
  );
}
import requests

url = "https://api.fuseais.com/api/v1/code/execute"
headers = {
    "X-API-Key": "YOUR_API_KEY",
    "Content-Type": "application/json"
}

payload = {
    "code": "import pandas as pd\ndf = pd.DataFrame({'a': [1,2,3]})\nprint(df.describe())",
    "timeout": 30
}

response = requests.post(url, json=payload, headers=headers)
result = response.json()

print(result["output"])
print(f"Executed in {result['stats']['execution_time_ms']}ms")
Available Packages

The sandbox includes 60+ whitelisted Python packages:

Category Packages
Data pandas, numpy, scipy, scikit-learn, statsmodels, pyarrow
Visualization matplotlib, seaborn, plotly
Images Pillow, opencv-python-headless
Documents PyMuPDF, pdfplumber, reportlab, python-docx
Web/HTTP requests, httpx, beautifulsoup4, lxml
Serialization json, csv, PyYAML, toml, xmltodict
Excel openpyxl, xlsxwriter, xlrd
Security Restrictions

The following are blocked by the AST policy checker before code runs:

  • exec(), eval(), compile(), __import__()
  • Imports outside the allowlist
  • File I/O outside /tmp/
  • Dunder attribute access (__subclasses__, __class__, etc.)
  • Recursion depth > 100
  • Output > 512 KB

Convert Code

POST
/code/convert

Convert a code snippet from one programming language to another while preserving logic and, optionally, comments. Useful for migrating legacy code or producing multi-language SDKs.

Request Parameters
Parameter Type Required Description
code string Required Source code to convert
source_language string Required Language of the input code (e.g. "javascript")
target_language string Required Desired output language (e.g. "python")
preserve_comments boolean Optional Whether to carry over comments to the target (default: true)
Request Body Example
{
  "code": "function add(a, b) {\n    return a + b;\n}",
  "source_language": "javascript",
  "target_language": "python",
  "preserve_comments": true
}
Response
{
  "status": "success",
  "result": "def add(a, b):\n    return a + b",
  "metadata": {
    "tokens_used": 250,
    "model_used": "claude"
  }
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/code/convert" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "function add(a, b) { return a + b; }",
    "source_language": "javascript",
    "target_language": "python"
  }'
import requests

url = "https://api.fuseais.com/api/v1/code/convert"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "code": "function add(a, b) { return a + b; }",
    "source_language": "javascript",
    "target_language": "python"
}

response = requests.post(url, json=payload, headers=headers)
print(response.json()["result"])
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class ConvertCodeExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"code\":\"function add(a, b) { return a + b; }\","
            + "\"source_language\":\"javascript\",\"target_language\":\"python\"}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/code/convert"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Profile Data

POST
/data/profile

Analyze a dataset to produce a statistical profile including row/column counts, data types, missing value rates, and summary statistics. Optionally returns recommendations for data cleaning.

Request Parameters
Parameter Type Required Description
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
data object | array Required A Dataset object or an array of JSON records to profile
sample_size integer Optional Number of rows to sample for large datasets
include_statistics boolean Optional Include descriptive statistics per column (default: true)
include_recommendations boolean Optional Include data-quality recommendations (default: true)
Request Body Example
{
  "user_id": "user123",
  "data": [
    {"name": "Alice", "age": 34, "department": "Engineering"},
    {"name": "Bob",   "age": null, "department": "Finance"}
  ],
  "include_statistics": true,
  "include_recommendations": true
}
Response
{
  "status": "success",
  "user_id": "user123",
  "profile": {
    "row_count": 1000,
    "column_count": 15,
    "missing_values": {"age": 50, "department": 10},
    "data_types": {"name": "categorical", "age": "numeric"},
    "statistics": {
      "age": {"mean": 34.2, "median": 33.0, "min": 22, "max": 65}
    }
  },
  "recommendations": [
    "Column 'age' has 5% missing values — consider mean imputation",
    "Column 'department' has 1% missing values"
  ],
  "timestamp": "2026-05-10T12:00:00"
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/data/profile" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "data": [
      {"name": "Alice", "age": 34},
      {"name": "Bob", "age": null}
    ]
  }'
import requests

url = "https://api.fuseais.com/api/v1/data/profile"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "user_id": "user123",
    "data": [{"name": "Alice", "age": 34}, {"name": "Bob", "age": None}]
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
print(f"Rows: {data['profile']['row_count']}")
for rec in data["recommendations"]:
    print(f"  - {rec}")
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class ProfileDataExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"user_id\":\"user123\","
            + "\"data\":[{\"name\":\"Alice\",\"age\":34},{\"name\":\"Bob\",\"age\":null}]}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/data/profile"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Data Density

POST
/data/density

Analyze data density across a dataset to identify sparse and dense regions. Useful for understanding where data is well-populated versus where gaps exist before running ML pipelines.

Request Parameters
Parameter Type Required Description
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
data object | array Required Dataset to analyze
columns string[] Optional Subset of columns to analyze; all columns analyzed if omitted
threshold number Optional Density threshold below which a region is flagged as sparse (default: 0.5)
Request Body Example
{
  "user_id": "user123",
  "data": [
    {"col1": 1, "col2": null},
    {"col1": 2, "col2": 5},
    {"col1": null, "col2": null}
  ],
  "threshold": 0.6
}
Response
{
  "status": "success",
  "user_id": "user123",
  "density_analysis": {
    "overall_density": 0.67,
    "sparse_regions": [
      {"columns": ["col2"], "density": 0.33, "row_count": 1}
    ],
    "dense_regions": [
      {"columns": ["col1"], "density": 0.67, "row_count": 2}
    ]
  },
  "recommendations": [
    "col2 has 67% missing values — consider dropping or imputing"
  ],
  "timestamp": "2026-05-10T12:00:00"
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/data/density" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "data": [{"col1": 1, "col2": null}, {"col1": 2, "col2": 5}],
    "threshold": 0.6
  }'
import requests

url = "https://api.fuseais.com/api/v1/data/density"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "user_id": "user123",
    "data": [{"col1": 1, "col2": None}, {"col1": 2, "col2": 5}],
    "threshold": 0.6
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
print(f"Overall density: {data['density_analysis']['overall_density']}")
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class DataDensityExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"user_id\":\"user123\","
            + "\"data\":[{\"col1\":1,\"col2\":null},{\"col1\":2,\"col2\":5}],"
            + "\"threshold\":0.6}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/data/density"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Deduplicate Data

POST
/data/deduplicate

Identify and remove duplicate records from a dataset. Supports exact matching, fuzzy matching (similarity threshold), or a hybrid of both. Returns counts and optional examples of the duplicates found.

Request Parameters
Parameter Type Required Description
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
data object | array Required Dataset to deduplicate
method string Optional Deduplication method: "exact", "fuzzy", or "hybrid" (default)
threshold number Optional Similarity threshold for fuzzy matching (0–1, default: 0.9)
columns string[] Optional Columns to consider for deduplication; all columns used if omitted
return_duplicates boolean Optional Whether to include duplicate examples in the response (default: false)
Request Body Example
{
  "user_id": "user123",
  "data": [
    {"id": "r1", "name": "Alice Smith", "email": "alice@example.com"},
    {"id": "r2", "name": "Alice  Smith", "email": "alice@example.com"},
    {"id": "r3", "name": "Bob Jones", "email": "bob@example.com"}
  ],
  "method": "fuzzy",
  "threshold": 0.9,
  "return_duplicates": true
}
Response
{
  "status": "success",
  "user_id": "user123",
  "original_count": 3,
  "deduplicated_count": 2,
  "duplicate_count": 1,
  "duplicate_examples": [
    {
      "id": "r2",
      "duplicate_of": "r1",
      "similarity_score": 0.97,
      "matching_fields": ["name", "email"]
    }
  ],
  "deduplication_method": "fuzzy",
  "timestamp": "2026-05-10T12:00:00"
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/data/deduplicate" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "data": [
      {"id": "r1", "name": "Alice Smith"},
      {"id": "r2", "name": "Alice  Smith"}
    ],
    "method": "fuzzy",
    "threshold": 0.9
  }'
import requests

url = "https://api.fuseais.com/api/v1/data/deduplicate"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "user_id": "user123",
    "data": [
        {"id": "r1", "name": "Alice Smith"},
        {"id": "r2", "name": "Alice  Smith"}
    ],
    "method": "fuzzy",
    "threshold": 0.9,
    "return_duplicates": True
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
print(f"Duplicates found: {data['duplicate_count']}")
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class DeduplicateDataExample {
    public static void main(String[] args) throws Exception {
        String body = "{\"user_id\":\"user123\","
            + "\"data\":[{\"id\":\"r1\",\"name\":\"Alice Smith\"},{\"id\":\"r2\",\"name\":\"Alice  Smith\"}],"
            + "\"method\":\"fuzzy\",\"threshold\":0.9}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/data/deduplicate"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Join Data

POST
/data/join

Join two or more datasets on specified key columns. Supports inner, left, right, outer, and fuzzy joins. Returns match statistics and optional sample rows from the result set.

Request Parameters
Parameter Type Required Description
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
datasets Dataset[] Required Array of Dataset objects to join (each has id, source, format, content)
join_type string Optional Join type: "inner" (default), "left", "right", "outer", "fuzzy"
join_keys object Required Map of dataset ID to the column name to join on (e.g. {"ds1": "customer_id", "ds2": "id"})
fuzzy_threshold number Optional Similarity threshold for fuzzy joins (default: 0.8)
return_sample boolean Optional Whether to include sample rows in the response (default: true)
Request Body Example
{
  "user_id": "user123",
  "datasets": [
    {"id": "ds1", "source": "crm", "format": "json", "content": [{"customer_id": "C1", "name": "Alice"}]},
    {"id": "ds2", "source": "billing", "format": "json", "content": [{"id": "C1", "amount": 500}]}
  ],
  "join_type": "inner",
  "join_keys": {"ds1": "customer_id", "ds2": "id"},
  "return_sample": true
}
Response
{
  "status": "success",
  "user_id": "user123",
  "join_type": "inner",
  "dataset_count": 2,
  "result_row_count": 950,
  "join_keys": {"ds1": "customer_id", "ds2": "id"},
  "match_statistics": {
    "exact_matches": 900,
    "fuzzy_matches": 50,
    "unmatched_records": 100
  },
  "sample_rows": [
    {"customer_id": "C1", "name": "Alice", "amount": 500}
  ],
  "timestamp": "2026-05-10T12:00:00"
}
Sample Code
cURL
Python
Java
curl -X POST "https://api.fuseais.com/api/v1/data/join" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user123",
    "datasets": [
      {"id": "ds1", "source": "crm", "format": "json",
       "content": [{"customer_id": "C1", "name": "Alice"}]},
      {"id": "ds2", "source": "billing", "format": "json",
       "content": [{"id": "C1", "amount": 500}]}
    ],
    "join_type": "inner",
    "join_keys": {"ds1": "customer_id", "ds2": "id"}
  }'
import requests

url = "https://api.fuseais.com/api/v1/data/join"
headers = {"X-API-Key": "YOUR_API_KEY", "Content-Type": "application/json"}
payload = {
    "user_id": "user123",
    "datasets": [
        {"id": "ds1", "source": "crm", "format": "json",
         "content": [{"customer_id": "C1", "name": "Alice"}]},
        {"id": "ds2", "source": "billing", "format": "json",
         "content": [{"id": "C1", "amount": 500}]}
    ],
    "join_type": "inner",
    "join_keys": {"ds1": "customer_id", "ds2": "id"}
}

response = requests.post(url, json=payload, headers=headers)
data = response.json()
print(f"Result rows: {data['result_row_count']}")
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class JoinDataExample {
    public static void main(String[] args) throws Exception {
        // Build JSON body — use a JSON library in production
        String body = "{\"user_id\":\"user123\","
            + "\"datasets\":[{\"id\":\"ds1\",\"source\":\"crm\",\"format\":\"json\","
            + "\"content\":[{\"customer_id\":\"C1\",\"name\":\"Alice\"}]},"
            + "{\"id\":\"ds2\",\"source\":\"billing\",\"format\":\"json\","
            + "\"content\":[{\"id\":\"C1\",\"amount\":500}]}],"
            + "\"join_type\":\"inner\","
            + "\"join_keys\":{\"ds1\":\"customer_id\",\"ds2\":\"id\"}}";
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/data/join"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Redact PII

POST
/privacy/redact

Identify and redact PII (Personally Identifiable Information) from text. This endpoint detects various types of PII and replaces them based on your chosen strategy. Use this before sending sensitive data to public LLM models.

Request Parameters
Parameter Type Required Description
text string Required Text to redact PII from
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
pii_types array Optional Specific PII types to redact. Options: NAME, EMAIL, PHONE_NUMBER, SSN, ADDRESS, CREDIT_CARD, DATE_OF_BIRTH. Redacts all PII if not specified.
replacement_strategy string Optional Strategy for replacing PII: "label" (replace with [TYPE]), "mask" (replace with ***), or "remove" (remove entirely). Default: "label"
Request Body Example
{
    "text": "My name is John Doe and my email is john.doe@example.com",
    "user_id": "user123",
    "pii_types": ["NAME", "EMAIL"],
    "replacement_strategy": "label"
}
Response
{
    "status": "success",
    "redacted_text": "My name is [NAME] and my email is [EMAIL]",
    "pii_found": [
        {
            "type": "NAME",
            "confidence": 0.98,
            "start": 11,
            "end": 19,
            "value": "John Doe"
        },
        {
            "type": "EMAIL",
            "confidence": 0.99,
            "start": 33,
            "end": 52,
            "value": "john.doe@example.com"
        }
    ],
    "pii_count": 2
}
Error Responses
Status Code Description
400 Bad Request Invalid request parameters
403 Forbidden Reserved (per-customer usage quotas planned; not currently enforced)
500 Internal Server Error Failed to redact PII
Sample Code
cURL
Python
Java
curl -X POST \
  "https://api.fuseais.com/api/v1/privacy/redact" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "My name is John Doe and my email is john.doe@example.com",
    "user_id": "user123",
    "pii_types": ["NAME", "EMAIL"],
    "replacement_strategy": "label"
  }'
import requests

url = "https://api.fuseais.com/api/v1/privacy/redact"
headers = {
    "X-API-Key": "YOUR_API_KEY",
    "Content-Type": "application/json"
}
payload = {
    "text": "My name is John Doe and my email is john.doe@example.com",
    "user_id": "user123",
    "pii_types": ["NAME", "EMAIL"],
    "replacement_strategy": "label"
}

try:
    response = requests.post(url, headers=headers, json=payload)
    response.raise_for_status()

    data = response.json()
    print("Redacted text:", data["redacted_text"])
    print("PII found:", data["pii_count"])

    for pii in data["pii_found"]:
        print(f"  - {pii['type']}: {pii['value']} (confidence: {pii['confidence']})")

except requests.exceptions.HTTPError as err:
    print(f"HTTP Error: {err}")
except Exception as err:
    print(f"Error: {err}")
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class RedactPIIExample {
    public static void main(String[] args) {
        try {
            ObjectMapper mapper = new ObjectMapper();

            Map<String, Object> payload = Map.of(
                "text", "My name is John Doe and my email is john.doe@example.com",
                "user_id", "user123",
                "pii_types", List.of("NAME", "EMAIL"),
                "replacement_strategy", "label"
            );

            String requestBody = mapper.writeValueAsString(payload);

            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.fuseais.com/api/v1/privacy/redact"))
                .header("X-API-Key", "YOUR_API_KEY")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                .build();

            HttpResponse<String> response = client.send(request,
                HttpResponse.BodyHandlers.ofString());

            if (response.statusCode() != 200) {
                System.out.println("Error: HTTP " + response.statusCode());
                return;
            }

            JsonNode data = mapper.readTree(response.body());
            System.out.println("Redacted text: " + data.get("redacted_text").asText());
            System.out.println("PII count: " + data.get("pii_count").asInt());

            data.get("pii_found").forEach(pii -> {
                System.out.printf("  - %s: %s (confidence: %.2f)%n",
                    pii.get("type").asText(),
                    pii.get("value").asText(),
                    pii.get("confidence").asDouble());
            });

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}
Supported PII Types
Type Description Example
NAME Person names John Doe, Sarah Smith
EMAIL Email addresses john@example.com
PHONE_NUMBER Phone numbers 555-123-4567
SSN Social Security Numbers 123-45-6789
ADDRESS Physical addresses 123 Main St, City, ST 12345
CREDIT_CARD Credit card numbers 4111-1111-1111-1111
DATE_OF_BIRTH Birth dates 01/15/1990

Tokenize PII

POST
/privacy/tokenize

Replace PII with reversible tokens (TOK_1, TOK_2, etc.). This allows you to process text through external systems while maintaining the ability to restore original values. Ideal for maintaining referential integrity across multiple documents.

Request Parameters
Parameter Type Required Description
text string Required Text containing PII to tokenize
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
pii_types array Optional Specific PII types to tokenize. Tokenizes all PII if not specified.
reversible boolean Optional Whether to include the token_map for reversing. Default: true
Request Body Example
{
    "text": "Contact Sarah Smith at sarah@company.com or call 123-456-7890",
    "user_id": "user123",
    "pii_types": ["NAME", "EMAIL", "PHONE_NUMBER"],
    "reversible": true
}
Response
{
    "status": "success",
    "tokenized_text": "Contact TOK_1 at TOK_2 or call TOK_3",
    "token_map": {
        "TOK_1": "Sarah Smith",
        "TOK_2": "sarah@company.com",
        "TOK_3": "123-456-7890"
    },
    "pii_found": [
        {
            "type": "NAME",
            "value": "Sarah Smith",
            "confidence": 0.95,
            "start": 8,
            "end": 19
        },
        {
            "type": "EMAIL",
            "value": "sarah@company.com",
            "confidence": 0.99,
            "start": 23,
            "end": 40
        },
        {
            "type": "PHONE_NUMBER",
            "value": "123-456-7890",
            "confidence": 0.98,
            "start": 49,
            "end": 61
        }
    ],
    "token_count": 3
}
Sample Code
cURL
Python
Java
curl -X POST \
  "https://api.fuseais.com/api/v1/privacy/tokenize" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "Contact Sarah Smith at sarah@company.com",
    "user_id": "user123",
    "reversible": true
  }'
import requests

url = "https://api.fuseais.com/api/v1/privacy/tokenize"
headers = {
    "X-API-Key": "YOUR_API_KEY",
    "Content-Type": "application/json"
}
payload = {
    "text": "Contact Sarah Smith at sarah@company.com",
    "user_id": "user123",
    "reversible": True
}

response = requests.post(url, headers=headers, json=payload)
data = response.json()

print("Tokenized:", data["tokenized_text"])
print("Token map:", data["token_map"])

# Later, you can reverse the tokenization
def detokenize(text, token_map):
    for token, value in token_map.items():
        text = text.replace(token, value)
    return text

original = detokenize(data["tokenized_text"], data["token_map"])
print("Restored:", original)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class TokenizePIIExample {
    public static void main(String[] args) {
        try {
            ObjectMapper mapper = new ObjectMapper();

            Map<String, Object> payload = Map.of(
                "text", "Contact Sarah Smith at sarah@company.com",
                "user_id", "user123",
                "reversible", true
            );

            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.fuseais.com/api/v1/privacy/tokenize"))
                .header("X-API-Key", "YOUR_API_KEY")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(payload)))
                .build();

            HttpResponse<String> response = client.send(request,
                HttpResponse.BodyHandlers.ofString());

            JsonNode data = mapper.readTree(response.body());
            System.out.println("Tokenized: " + data.get("tokenized_text").asText());
            System.out.println("Token map: " + data.get("token_map"));

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

Detect PII

POST
/privacy/detect

Analyze text to identify PII without modifying it. Returns detailed information about each PII instance found, including type, location, confidence score, and an overall sensitivity score. Use this to assess content before processing.

Request Parameters
Parameter Type Required Description
text string Required Text to analyze for PII
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
pii_types array Optional Specific PII types to detect. Detects all types if not specified.
min_confidence number Optional Minimum confidence threshold (0.0-1.0). Default: 0.7
Request Body Example
{
    "text": "My SSN is 123-45-6789 and I live at 456 Oak Street. My credit card is 4111-1111-1111-1111.",
    "user_id": "user123",
    "min_confidence": 0.8
}
Response
{
    "status": "success",
    "pii_found": [
        {
            "type": "SSN",
            "value": "123-45-6789",
            "confidence": 0.99,
            "start": 10,
            "end": 21
        },
        {
            "type": "ADDRESS",
            "value": "456 Oak Street",
            "confidence": 0.90,
            "start": 36,
            "end": 50
        },
        {
            "type": "CREDIT_CARD",
            "value": "4111-1111-1111-1111",
            "confidence": 0.99,
            "start": 70,
            "end": 89
        }
    ],
    "pii_count": 3,
    "pii_types_found": ["SSN", "ADDRESS", "CREDIT_CARD"],
    "sensitive_content_score": 0.9
}
Sample Code
cURL
Python
Java
curl -X POST \
  "https://api.fuseais.com/api/v1/privacy/detect" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "text": "My SSN is 123-45-6789 and my email is john@example.com",
    "user_id": "user123",
    "min_confidence": 0.8
  }'
import requests

url = "https://api.fuseais.com/api/v1/privacy/detect"
headers = {
    "X-API-Key": "YOUR_API_KEY",
    "Content-Type": "application/json"
}
payload = {
    "text": "My SSN is 123-45-6789 and my email is john@example.com",
    "user_id": "user123",
    "min_confidence": 0.8
}

response = requests.post(url, headers=headers, json=payload)
data = response.json()

print(f"Found {data['pii_count']} PII instances")
print(f"Sensitivity score: {data['sensitive_content_score']}")
print(f"PII types: {', '.join(data['pii_types_found'])}")

# Check if content is safe to process
if data['sensitive_content_score'] > 0.7:
    print("WARNING: High sensitivity - redact before processing!")
else:
    print("Content sensitivity is acceptable")
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class DetectPIIExample {
    public static void main(String[] args) {
        try {
            ObjectMapper mapper = new ObjectMapper();

            Map<String, Object> payload = Map.of(
                "text", "My SSN is 123-45-6789 and my email is john@example.com",
                "user_id", "user123",
                "min_confidence", 0.8
            );

            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create("https://api.fuseais.com/api/v1/privacy/detect"))
                .header("X-API-Key", "YOUR_API_KEY")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(mapper.writeValueAsString(payload)))
                .build();

            HttpResponse<String> response = client.send(request,
                HttpResponse.BodyHandlers.ofString());

            JsonNode data = mapper.readTree(response.body());
            System.out.println("PII count: " + data.get("pii_count").asInt());
            System.out.println("Sensitivity: " + data.get("sensitive_content_score").asDouble());

            // Check sensitivity threshold
            if (data.get("sensitive_content_score").asDouble() > 0.7) {
                System.out.println("WARNING: High sensitivity content!");
            }

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}
Sensitivity Score Guide
Score Range Level Recommendation
0.0 - 0.3 Low Safe to process with public LLMs
0.3 - 0.6 Medium Consider redacting before public LLM use
0.6 - 1.0 High Redact PII or use private LLM (AWS Bedrock)

Redact PII in File

POST
/privacy/files/redact

Upload a file and redact PII from its contents. Supports text files. The file is processed and returned with all detected PII redacted according to the specified strategy.

Request Parameters (multipart/form-data)
Parameter Type Required Description
file file Required The text file to process
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
pii_types string Optional Comma-separated PII types to redact (e.g., "NAME,EMAIL,SSN")
replacement_strategy string Optional Redaction strategy: "label", "mask", or "remove". Default: "label"
Sample Code
cURL
Python
Java
curl -X POST \
  "https://api.fuseais.com/api/v1/privacy/files/redact" \
  -H "X-API-Key: YOUR_API_KEY" \
  -F "file=@document.txt" \
  -F "user_id=user123" \
  -F "pii_types=NAME,EMAIL,PHONE_NUMBER" \
  -F "replacement_strategy=label"
import requests

url = "https://api.fuseais.com/api/v1/privacy/files/redact"
headers = {"X-API-Key": "YOUR_API_KEY"}

with open("document.txt", "rb") as f:
    files = {"file": ("document.txt", f, "text/plain")}
    data = {
        "user_id": "user123",
        "pii_types": "NAME,EMAIL,PHONE_NUMBER",
        "replacement_strategy": "label"
    }
    response = requests.post(url, headers=headers, files=files, data=data)

result = response.json()
print("Redacted text:", result["redacted_text"])
print("PII found:", result["pii_count"])
import java.io.File;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;

public class FileRedactExample {
    public static void main(String[] args) throws Exception {
        String boundary = "----WebKitFormBoundary" + System.currentTimeMillis();
        File file = new File("document.txt");

        String body = "--" + boundary + "\r\n" +
            "Content-Disposition: form-data; name=\"file\"; filename=\"document.txt\"\r\n" +
            "Content-Type: text/plain\r\n\r\n" +
            Files.readString(file.toPath()) + "\r\n" +
            "--" + boundary + "\r\n" +
            "Content-Disposition: form-data; name=\"user_id\"\r\n\r\nuser123\r\n" +
            "--" + boundary + "\r\n" +
            "Content-Disposition: form-data; name=\"replacement_strategy\"\r\n\r\nlabel\r\n" +
            "--" + boundary + "--";

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/privacy/files/redact"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "multipart/form-data; boundary=" + boundary)
            .POST(HttpRequest.BodyPublishers.ofString(body))
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Batch Redact PII

POST
/privacy/batch/redact

Process multiple files in a single request, redacting PII from each file. Returns combined results with per-file breakdown. Ideal for batch processing of documents.

Request Parameters (multipart/form-data)
Parameter Type Required Description
files file[] Required Multiple text files to process
user_id string Optional Legacy; ignored — identity always comes from your API key / JWT
pii_types string Optional Comma-separated PII types to redact
replacement_strategy string Optional Redaction strategy: "label", "mask", or "remove". Default: "label"
Response
{
    "status": "success",
    "file_count": 3,
    "total_pii_count": 12,
    "results": [
        {
            "filename": "document1.txt",
            "redacted_text": "Customer [NAME] placed order...",
            "pii_found": [...],
            "pii_count": 4
        },
        {
            "filename": "document2.txt",
            "redacted_text": "Contact [EMAIL] for support...",
            "pii_found": [...],
            "pii_count": 5
        },
        {
            "filename": "document3.txt",
            "redacted_text": "Shipping to [ADDRESS]...",
            "pii_found": [...],
            "pii_count": 3
        }
    ]
}
Sample Code
cURL
Python
Java
curl -X POST \
  "https://api.fuseais.com/api/v1/privacy/batch/redact" \
  -H "X-API-Key: YOUR_API_KEY" \
  -F "files=@document1.txt" \
  -F "files=@document2.txt" \
  -F "files=@document3.txt" \
  -F "user_id=user123" \
  -F "replacement_strategy=label"
import requests

url = "https://api.fuseais.com/api/v1/privacy/batch/redact"
headers = {"X-API-Key": "YOUR_API_KEY"}

# Prepare multiple files
files = [
    ("files", ("doc1.txt", open("doc1.txt", "rb"), "text/plain")),
    ("files", ("doc2.txt", open("doc2.txt", "rb"), "text/plain")),
    ("files", ("doc3.txt", open("doc3.txt", "rb"), "text/plain")),
]
data = {
    "user_id": "user123",
    "replacement_strategy": "label"
}

response = requests.post(url, headers=headers, files=files, data=data)
result = response.json()

print(f"Processed {result['file_count']} files")
print(f"Total PII found: {result['total_pii_count']}")

for file_result in result["results"]:
    print(f"\n{file_result['filename']}: {file_result['pii_count']} PII instances")
import java.io.File;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;

public class BatchRedactExample {
    public static void main(String[] args) throws Exception {
        String boundary = "----Boundary" + System.currentTimeMillis();
        StringBuilder body = new StringBuilder();

        // Add multiple files
        String[] filenames = {"doc1.txt", "doc2.txt", "doc3.txt"};
        for (String filename : filenames) {
            File file = new File(filename);
            body.append("--").append(boundary).append("\r\n")
                .append("Content-Disposition: form-data; name=\"files\"; filename=\"")
                .append(filename).append("\"\r\n")
                .append("Content-Type: text/plain\r\n\r\n")
                .append(Files.readString(file.toPath())).append("\r\n");
        }

        // Add user_id
        body.append("--").append(boundary).append("\r\n")
            .append("Content-Disposition: form-data; name=\"user_id\"\r\n\r\n")
            .append("user123\r\n")
            .append("--").append(boundary).append("--");

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/privacy/batch/redact"))
            .header("X-API-Key", "YOUR_API_KEY")
            .header("Content-Type", "multipart/form-data; boundary=" + boundary)
            .POST(HttpRequest.BodyPublishers.ofString(body.toString()))
            .build();

        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

Get Token Usage

GET
/llm/token-usage

Retrieve token usage statistics for the authenticated user. Returns the number of tokens consumed and remaining in the current allocation period. Token counts are updated after each LLM call.

Response
{
  "status": "success",
  "user_id": "user123",
  "tokens_used": 4200,
  "tokens_remaining": 5800,
  "period": "2026-05"
}
Notes
  • Token counts include input and output tokens from all /llm/* endpoints.
  • Each LLM response also returns tokens_used and tokens_remaining inline.
  • Contact your account administrator to increase your token allocation.
Sample Code
cURL
Python
Java
curl -X GET "https://api.fuseais.com/api/v1/llm/token-usage" \
  -H "X-API-Key: YOUR_API_KEY"
import requests

url = "https://api.fuseais.com/api/v1/llm/token-usage"
headers = {"X-API-Key": "YOUR_API_KEY"}

response = requests.get(url, headers=headers)
data = response.json()
print(f"Used: {data['tokens_used']}, Remaining: {data['tokens_remaining']}")
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class GetTokenUsageExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.fuseais.com/api/v1/llm/token-usage"))
            .header("X-API-Key", "YOUR_API_KEY")
            .GET()
            .build();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.body());
    }
}

List Models

GET
/v1/models

Returns the Claude models available through the FuseAIs Anthropic-compatible proxy. Claude Code probes this endpoint at startup when ANTHROPIC_BASE_URL is set. Authentication uses the same X-API-Key or Authorization: Bearer headers as all other endpoints.

Response
{
  "data": [
    {"id": "claude-opus-4-7",   "display_name": "Claude Opus 4.7",   "created_at": "2025-07-01T00:00:00Z", "type": "model"},
    {"id": "claude-sonnet-4-6", "display_name": "Claude Sonnet 4.6", "created_at": "2025-05-01T00:00:00Z", "type": "model"},
    {"id": "claude-haiku-4-5",  "display_name": "Claude Haiku 4.5",  "created_at": "2025-03-01T00:00:00Z", "type": "model"}
  ],
  "has_more": false,
  "first_id": "claude-opus-4-7",
  "last_id": "claude-haiku-4-5"
}
Sample Code
cURL
Python
curl -X GET "https://api.fuseais.com/v1/models" \
  -H "X-API-Key: YOUR_API_KEY"
import requests

response = requests.get(
    "https://api.fuseais.com/v1/models",
    headers={"X-API-Key": "YOUR_API_KEY"}
)
for model in response.json()["data"]:
    print(model["id"], "-", model["display_name"])

Create Message

POST
/v1/messages

Anthropic Messages API-compatible endpoint. Point Claude Code (or any Anthropic SDK client) at the FuseAIs proxy by setting ANTHROPIC_BASE_URL=https://api.fuseais.com and ANTHROPIC_AUTH_TOKEN=YOUR_API_KEY. Requests are metered per user and forwarded to AWS Bedrock. Supports both streaming (stream: true → SSE) and non-streaming responses.

Request Parameters
ParameterTypeRequiredDescription
model string Required Model ID: claude-opus-4-7, claude-sonnet-4-6, or claude-haiku-4-5
messages array Required Conversation turns. Each object has role (user or assistant) and content (string or content block array)
max_tokens integer Required Maximum tokens to generate
system string Optional System prompt
stream boolean Optional If true, response is streamed as SSE (text/event-stream)
tools array Optional Tool definitions for tool-use turns
temperature float Optional Sampling temperature (0.0–1.0)
Request Body Example
{
  "model": "claude-sonnet-4-6",
  "max_tokens": 1024,
  "messages": [
    {"role": "user", "content": "Summarize the key points of the attached report."}
  ],
  "system": "You are a helpful business analyst."
}
Response
{
  "id": "msg_01XFDUDYJgAACzvnptvVoYEL",
  "type": "message",
  "role": "assistant",
  "model": "claude-sonnet-4-6",
  "content": [{"type": "text", "text": "Here are the key points..."}],
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 42,
    "output_tokens": 218,
    "cache_read_input_tokens": 0,
    "cache_creation_input_tokens": 0
  }
}
Error Responses
Status CodeError TypeDescription
401authentication_errorMissing or invalid credentials
404not_found_errorUnknown model ID
429rate_limit_errorBudget or rate limit exceeded
502api_errorUpstream Bedrock error
Claude Code Setup
Claude Code settings.json
cURL
Python (Anthropic SDK)
{
  "env": {
    "ANTHROPIC_BASE_URL": "https://api.fuseais.com",
    "ANTHROPIC_AUTH_TOKEN": "YOUR_API_KEY",
    "ANTHROPIC_MODEL": "claude-sonnet-4-6"
  }
}
curl -X POST "https://api.fuseais.com/v1/messages" \
  -H "X-API-Key: YOUR_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "claude-sonnet-4-6",
    "max_tokens": 1024,
    "messages": [{"role": "user", "content": "Hello!"}]
  }'
import anthropic

client = anthropic.Anthropic(
    base_url="https://api.fuseais.com",
    api_key="YOUR_API_KEY",
)

message = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello!"}]
)
print(message.content[0].text)