p-typed Context API

p-typed Context API

OpenAI-compatible chat completions and embeddings. Swap models, create OpenAI vectors, stream tokens, and search Uganda's Legal Knowledge Graph (UKG) with single-line SDK adjustments.

Quick Start — Python & JS SDKs

Any OpenAI-compatible SDK can be re-pointed to p-typed Context API seamlessly. Create an API key in the Developer Portal, then use the following patterns:

Python SDK Setup

from openai import OpenAI

# Just point Base URL and provide your p-typed Key:
client = OpenAI(
    api_key="alfie_sk_live_xxxxxxxxxx...",
    base_url="https://api.157.230.94.55.sslip.io/v1",
)

response = client.chat.completions.create(
    model="grok-4.3",  # or gemini-3-flash-preview, deepseek/deepseek-v4-pro
    messages=[
        {"role": "system", "content": "Reply in one short sentence."},
        {"role": "user", "content": "What is the capital of Uganda?"},
    ],
    temperature=0.3,
)

print(response.choices[0].message.content)

Node.js SDK Setup

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: "alfie_sk_live_xxxxxxxxxx...",
  baseURL: "https://api.157.230.94.55.sslip.io/v1",
});

const completion = await client.chat.completions.create({
  model: "grok-4.3",
  messages: [{ role: "user", content: "Say hello!" }],
});

Authentication

Authenticated calls require a Bearer key in the HTTP Authorization header:

Authorization: Bearer your_p_typed_api_key

API keys are formatted as alfie_sk_live_[32-hex-characters]. Programmatic operations count strictly toward your primary owner's subscription tier.

OpenAI-Compatible Embeddings

Create vectors in the real OpenAI text-embedding-3 semantic spaces through the same p-typed API key. Existing OpenAI SDK code works unchanged after setting the p-typed base URL.

from openai import OpenAI

client = OpenAI(
    api_key="alfie_sk_live_xxxxxxxxxx...",
    base_url="https://api.157.230.94.55.sslip.io/v1",
)

response = client.embeddings.create(
    model="text-embedding-3-small",
    input=["Ugandan employment law", "Constitutional land rights"],
    encoding_format="float",
)

print(len(response.data[0].embedding))  # 1536

text-embedding-3-small returns 1,536 values by default; text-embedding-3-large returns 3,072. Provider-prefixed aliases are accepted, but responses use the standard OpenAI model IDs.

Server-Sent Events (SSE) Streaming

Setting stream: true causes tokens to stream dynamically. In the Python SDK, simply loop over chunks:

stream = client.chat.completions.create(
    model="grok-4.3",
    messages=[{"role": "user", "content": "Explain quantum entanglement briefly."}],
    stream=True,
)
for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)

Totals are re-calculated and provided at the final chunk. (Note: server-side tool groups cannot be streamed).

p-typed Extension — Server-Side Tool Groups

The ukg_groups extension hooks the model directly into state-of-the-art server-side tools (e.g. Uganda legal archives), bypassing client-side processing roundtrips. Specify desired groups in `extra_body`:

response = client.chat.completions.create(
    model="grok-4.3",
    messages=[{"role": "user", "content": "What is the penalty for directorship breach?"}],
    extra_body={"ukg_groups": ["legal"]},  # Enable Uganda Knowledge Graph
)

Discover valid tool group tags from GET /v1/ukg/groups. This is non-streamable.

AI_OCR — Image Data Extraction

Accurately extract all data from images — receipts, IDs, forms, screenshots, documents — into structured JSON, without hallucination. Powered by Google Gemini flash models, tuned for faithful, verbatim transcription.

  • Stateless: no memory or conversation context — each image is read in isolation.
  • One image at a time: multiple images are queued and processed sequentially, returning a list with one extracted object per image (in order). This prevents data bleeding between images.
  • Honest uncertainty: anything blurry, cut off, or ambiguous is reported in a notes field instead of being guessed.

Available models

ModelBest for
gemini-2.5-flash-liteDefault — fastest, accurate, broadly tier-accessible
gemini-3-flash-previewNewest preview model (slower; deep reasoning)
gemini-2.5-flashGeneral extraction (may require a higher tier)

Python example

import httpx

resp = httpx.post(
    "https://api.157.230.94.55.sslip.io/api/ai-ocr",
    headers={"Authorization": "Bearer ALFIE_KEY"},
    json={
        "images": [
            "data:image/png;base64,iVBORw0KGgo...",   # data URL
            "https://example.com/receipt.jpg",          # or a public URL
        ],
        "model": "gemini-2.5-flash-lite",
    },
    timeout=180,
)

for item in resp.json()["results"]:
    print(item["index"], item["confidence"], item["full_text"])
    if item["notes"]:
        print("  ⚠ uncertain:", item["notes"])

Each image consumes one unit of your daily quota. Failed images are automatically refunded. Accepted inputs: data: URLs, public http(s) URLs, or raw base64. Up to 20 images per request.

Rate Limits & Quotas

Programmatic API requests are rate-limited per minutes to safeguard downstream endpoints:

  • Base rate limit: 60 requests / minute, per key.
  • Daily quota: Shared across your subscription tier.

Unsuccessful model attempts do not deplete daily quotas. Limit parameters arrive in the HTTP headers:

HeaderDescription
x-ratelimit-limitBucket allocation limit
x-ratelimit-remainingRemaining allocation
x-ratelimit-resetEpoch reset Unix timestamp

Endpoints

POST /v1/chat/completions
Create chat completion (OpenAI-compatible)

Creates model generation from standard messages. Supports streaming, custom tools, and p-typed server-side groups.

Key Request Parameters

FieldTypeDescription
modelstringRequired. Model ID (e.g. grok-4.3)
messagesarrayRequired. Array of message dicts {role, content}
streamboolBoolean flag for SSE streaming
response_formatobjecte.g. {"type": "json_object"} (requires JSON prompt direction)
ukg_groupsstring[]Enable server-side integrations (e.g. ["legal", "search"])

Example curl calling model

curl -X POST https://api.157.230.94.55.sslip.io/v1/chat/completions \
  -H "Authorization: Bearer PTYPED_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-4.3",
    "messages": [{"role": "user", "content": "Who is the Chief Justice of Uganda?"}],
    "ukg_groups": ["legal"]
  }'
POST /v1/embeddings
Create OpenAI embeddings

Creates ordered embeddings with OpenAI's text-embedding-3-small or text-embedding-3-large model through the Vercel AI Gateway.

Request Body

FieldTypeDescription
modelstringRequired. Standard model ID or openai/-prefixed alias.
inputstring | string[]Required. One non-empty string or an ordered batch.
encoding_formatstringfloat (default) or base64.
dimensionsintOptional reduced vector size: 1–1,536 for small or 1–3,072 for large.
userstringOptional stable end-user identifier forwarded to OpenAI.
curl -X POST https://api.157.230.94.55.sslip.io/v1/embeddings \
  -H "Authorization: Bearer PTYPED_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "text-embedding-3-small",
    "input": ["Ugandan employment law", "Constitutional land rights"],
    "encoding_format": "float"
  }'
GET /v1/models
Retrieve available catalog

Lists models supported for the authenticated user's tier. Responds in OpenAPI-compat models layout.

curl -H "Authorization: Bearer PTYPED_KEY" \
  https://api.157.230.94.55.sslip.io/v1/models
GET /v1/ukg/groups
Details of server tool groups

Exposes all pre-registered server-side UKG integration groups.

curl -H "Authorization: Bearer PTYPED_KEY" \
  https://api.157.230.94.55.sslip.io/v1/ukg/groups
POST /api/ai-ocr
AI_OCR — extract structured data from images

Stateless image-to-structured-data extraction. Processes images one at a time and returns one object per image.

Request Body

FieldTypeDescription
imagesstring[]Required. List of images: data: URLs, public URLs, or raw base64. Max 20.
modelstringOne of gemini-2.5-flash-lite (default), gemini-3-flash-preview, gemini-2.5-flash.

Per-image result fields

FieldTypeDescription
indexintPosition of the image in the input list
successboolWhether extraction succeeded for this image
full_textstringAll readable text, transcribed verbatim
key_valuesobjectDetected label → value pairs
objectsstring[]Notable visual elements/fields present
document_typestringBest-effort label (e.g. receipt) or unknown
confidencestringhigh | medium | low
notesstring?Anything unclear/uncertain, or null if fully clear
errorstring?Error message if this image failed, else null

Example — curl

curl -X POST https://api.157.230.94.55.sslip.io/api/ai-ocr \
  -H "Authorization: Bearer PTYPED_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "images": ["https://example.com/receipt.jpg"],
    "model": "gemini-2.5-flash-lite"
  }'

Example response

{
  "success": true,
  "model": "gemini-2.5-flash-lite",
  "count": 1,
  "results": [
    {
      "index": 0,
      "success": true,
      "full_text": "P-TYPED STORE\nReceipt #4471\nTOTAL UGX 10,500",
      "key_values": {"Receipt #": "4471", "TOTAL": "UGX 10,500"},
      "objects": ["store name", "receipt number", "total amount"],
      "document_type": "receipt",
      "confidence": "high",
      "notes": null,
      "error": null
    }
  ]
}
POST /api/alfie/chat
Main p-typed Stateful Endpoint

Stateful entrypoint. Preserves continuous thread history on p-typed database.

curl -X POST https://api.157.230.94.55.sslip.io/api/alfie/chat \
  -H "Authorization: Bearer PTYPED_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "Continuing our previous topic",
    "user_id": "YOUR_FIREBASE_UID"
  }'
GET /health
Verify api service state

No auth required. Returns 200 setup confirmation.

🎉 API Key Created Successfully!

Save this key securely now. You will not be able to see it again!

alfie_sk_live_...

Using this key will route all usage and billing directly to your active subscription quota.

Manage Developer Keys

Sign in with your registered Google p-typed account to retrieve, create, and revoke your custom API keys.

Active API Keys

List of all issued credentials on your developer account. Revoked or expired keys block authorization instantly.

Subscription Tier
Active Credentials
0
Name Prefix Scopes Expires Actions
Sign in to view your credentials.