BLACKFUEL
Guides

Best Practices

Recommendations for building reliable, efficient applications with the Blackfuel API

Security

Protect Your API Keys

# Good: Use environment variables
import os
api_key = os.environ["BLACKFUEL_API_KEY"]

# Bad: Hardcoded keys
api_key = "bf_mykey_xxxxxx"  # Never do this!

Never Expose Keys in Client-Side Code

API keys should only be used server-side. For web applications, proxy requests through your backend:

// Frontend: Call your backend
const response = await fetch('/api/chat', {
  method: 'POST',
  body: JSON.stringify({ message: userInput })
});

// Backend: Make the API call
app.post('/api/chat', async (req, res) => {
  const result = await client.chat.completions.create({
    model: 'deepseek-ai/DeepSeek-V4-Flash-0731',
    messages: [{ role: 'user', content: req.body.message }]
  });
  res.json(result);
});

Performance

Stream Long Responses

Streaming is required for long-running requests: a non-streaming request that produces no response before the response timeout fails with a 524. It also improves perceived performance, since the first token reaches the user immediately.

stream = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Flash-0731",
    messages=messages,
    stream=True
)

for chunk in stream:
    # The stream ends with a usage chunk whose choices array is empty
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

Set Appropriate max_tokens

Avoid generating more tokens than needed:

# Good: Set reasonable limits
response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Flash-0731",
    messages=messages,
    max_tokens=500  # Limit based on expected response length
)

# Avoid: No limit can result in very long responses
response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Flash-0731",
    messages=messages
    # max_tokens defaults to model maximum
)

An unbounded max_tokens on a non-streaming request is the common way to hit the response timeout described above. Cap it, stream, or both.

Cache Repeated Requests

Cache responses for identical or similar requests:

import hashlib
from functools import lru_cache

def get_cache_key(messages, model):
    content = f"{model}:{str(messages)}"
    return hashlib.sha256(content.encode()).hexdigest()

# Simple in-memory cache
cache = {}

def cached_completion(messages, model="deepseek-ai/DeepSeek-V4-Flash-0731"):
    key = get_cache_key(messages, model)

    if key in cache:
        return cache[key]

    response = client.chat.completions.create(
        model=model,
        messages=messages
    )
    cache[key] = response
    return response

Use Async for High Concurrency

For applications handling many concurrent requests:

import asyncio
import os

import openai

client = openai.AsyncOpenAI(
    base_url="https://api.blackfuel.ai/v1",
    api_key=os.environ["BLACKFUEL_API_KEY"],
)

async def process_messages(messages_list):
    tasks = [
        client.chat.completions.create(
            model="deepseek-ai/DeepSeek-V4-Flash-0731",
            messages=msgs
        )
        for msgs in messages_list
    ]
    return await asyncio.gather(*tasks)

Prompt Engineering

Use System Messages Effectively

messages = [
    {
        "role": "system",
        "content": "You are a helpful customer support agent for a software company. Be concise and professional."
    },
    {"role": "user", "content": user_question}
]

Keep Context Focused

Include only relevant conversation history:

# Good: Keep recent, relevant messages
def get_context_messages(history, max_messages=10):
    return history[-max_messages:]

# Avoid: Sending entire conversation history
messages = entire_conversation_history  # May exceed context limits

Use Appropriate Temperature

Use CaseTemperature
Factual Q&A0.0 - 0.3
General conversation0.5 - 0.7
Creative writing0.8 - 1.0
Brainstorming1.0 - 1.5
# For consistent, factual responses
response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Flash-0731",
    messages=messages,
    temperature=0.2
)

# For creative tasks
response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Flash-0731",
    messages=messages,
    temperature=0.9
)

Error Handling

Implement Retry Logic

import time
from tenacity import retry, stop_after_attempt, wait_exponential

@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=1, max=10)
)
def reliable_completion(messages):
    return client.chat.completions.create(
        model="deepseek-ai/DeepSeek-V4-Flash-0731",
        messages=messages
    )

Handle Rate Limits Gracefully

from openai import RateLimitError

try:
    response = client.chat.completions.create(...)
except RateLimitError as e:
    # Queue for later or notify user
    queue_for_retry(request)
    return {"status": "queued", "message": "Request queued due to high demand"}

Cost Optimization

Choose the Right Model

Match the model to the work, then to its per-token rate. Read both from the catalog at run time: task and context_length tell you what fits, and pricing.prompt / pricing.completion give the rate. See Available Models or GET /v1/models.

Monitor Token Usage

from functools import lru_cache

response = client.chat.completions.create(
    model="deepseek-ai/DeepSeek-V4-Flash-0731",
    messages=messages
)

usage = response.usage
print(f"Prompt tokens: {usage.prompt_tokens}")
print(f"Completion tokens: {usage.completion_tokens}")
print(f"Total tokens: {usage.total_tokens}")

# Cost: read the model's per-token rates from GET /v1/models so a catalog
# change cannot silently skew your accounting. Cache per model — the rates
# change far less often than you make requests.
@lru_cache(maxsize=None)
def token_rates(model: str) -> tuple[float, float]:
    pricing = client.models.retrieve(model).pricing
    if pricing["prompt"] is None or pricing["completion"] is None:
        raise ValueError(f"{model} has no published per-token price")
    return float(pricing["prompt"]), float(pricing["completion"])

prompt_rate, completion_rate = token_rates(response.model)
total_cost = usage.prompt_tokens * prompt_rate + usage.completion_tokens * completion_rate
print(f"Estimated cost: ${total_cost:.6f}")

Reduce Prompt Size

  • Remove unnecessary whitespace
  • Use concise instructions
  • Summarize long context instead of including everything

Reliability

Set Timeouts

import os

import httpx
import openai

client = openai.OpenAI(
    base_url="https://api.blackfuel.ai/v1",
    api_key=os.environ["BLACKFUEL_API_KEY"],
    timeout=httpx.Timeout(600.0, connect=5.0)
)

Size these to the platform limits; Client timeouts covers sizing read timeouts for streaming and non-streaming requests.

Implement Circuit Breakers

For production systems, prevent cascading failures:

from circuitbreaker import circuit

@circuit(failure_threshold=5, recovery_timeout=60)
def api_call(messages):
    return client.chat.completions.create(
        model="deepseek-ai/DeepSeek-V4-Flash-0731",
        messages=messages
    )

Log Everything

import logging

logger = logging.getLogger(__name__)

def logged_completion(messages):
    start = time.time()
    try:
        response = client.chat.completions.create(
            model="deepseek-ai/DeepSeek-V4-Flash-0731",
            messages=messages
        )
        logger.info(f"Completion succeeded in {time.time() - start:.2f}s, "
                   f"tokens: {response.usage.total_tokens}")
        return response
    except Exception as e:
        logger.error(f"Completion failed after {time.time() - start:.2f}s: {e}")
        raise

On this page