Integration guide · Evidence checked 20 November 2026

OpenAI Python SDK with Plugsky: setup, streaming and errors

The OpenAI Python SDK is the shortest path to a working Plugsky client: change the base URL, keep the Chat Completions calls, and add the error handling that a hosted API needs. This guide covers sync, async, streaming, tool calling, embeddings and the failure modes you will actually hit.

Short answer. Install openai, create OpenAI(api_key=..., base_url="https://api.plugsky.com/v1"), and call client.chat.completions.create(model="plugsky-pro", messages=[...]). Streaming, async, tool calling and embeddings use the same SDK methods as OpenAI; the base URL and model IDs are what change.

What compatibility covers

Plugsky implements OpenAI-shaped chat completions and embeddings. That covers the common production path: messages, streaming deltas, JSON mode, tool definitions, embeddings and token usage in the response. It does not mean every OpenAI product exists behind the same host. Responses, Assistants, audio, image generation and fine-tuning are separate products; do not assume a base URL change makes them appear.

The approved base URL for these examples is https://api.plugsky.com/v1. Plugsky's public docs also show https://plugsky.com/v1 in places; use one host consistently and confirm which one your egress rules and key were issued for.

The SDK itself is the official openai package. Its current README lists Python 3.10 or newer, and the SDK defaults are a ten-minute request timeout and two retries. Both the timeout and the retry count are configurable per client, and you should set them deliberately for a gateway you do not operate.

Install and initialise the client

pip install openai
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["PLUGSKY_API_KEY"],
    base_url="https://api.plugsky.com/v1",
    timeout=120.0,
    max_retries=2,
)

Keep the key in an environment variable or secret manager. The SDK also reads OPENAI_API_KEY by default, but an explicit PLUGSKY_API_KEY avoids accidentally sending a real OpenAI key to the wrong host.

A shorter timeout than the SDK default is usually right for interactive chat. A long-running extraction job may need more. Set per-request timeouts with the timeout argument when one endpoint has different behaviour from the rest.

Make a chat request

response = client.chat.completions.create(
    model="plugsky-pro",
    messages=[
        {"role": "system", "content": "You are a concise support assistant."},
        {"role": "user", "content": "Summarise this ticket in three bullets."},
    ],
    temperature=0.2,
    max_tokens=800,
)

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

usage is returned in the OpenAI shape: prompt tokens, completion tokens and total tokens. Log it per request, because a flat plan still has fair-use limits and a per-request budget that you will want to tune.

max_tokens caps the output for this request. It is not the model's context window. Plugsky's plugsky-pro supports a 262,144-token serving context and a 16,384-token maximum output, but your plan ceiling may be lower: 8K output on Hobby, 16K on Starter and 32K on Builder or Scale.

Stream the response

stream = client.chat.completions.create(
    model="plugsky-pro",
    messages=[{"role": "user", "content": "Count to five, one word per line."}],
    stream=True,
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

delta.content can be None, especially in the first chunk that carries the role and the final chunk that carries the finish reason. Guard before concatenating, and do not read message.content on a streaming chunk; that field belongs to the non-streaming response.

If your web framework buffers the response, streaming will look broken even though the API is fine. Disable proxy buffering and compression for the streaming route, and flush after each delta.

Use the async client

import asyncio
from openai import AsyncOpenAI

aclient = AsyncOpenAI(
    api_key=os.environ["PLUGSKY_API_KEY"],
    base_url="https://api.plugsky.com/v1",
)

async def main() -> None:
    response = await aclient.chat.completions.create(
        model="plugsky-pro",
        messages=[{"role": "user", "content": "Give me one sentence on latency."}],
    )
    print(response.choices[0].message.content)

asyncio.run(main())

For async streaming, await the create call once and then iterate. The await returns the asynchronous iterator; it does not return the final response.

stream = await aclient.chat.completions.create(
    model="plugsky-pro",
    messages=[{"role": "user", "content": "Write a short changelog."}],
    stream=True,
)

async for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")

Call tools with the standard schema

Tool calling uses the OpenAI request shape. The model returns a tool call with a name and a JSON-encoded argument string; your code executes the function and sends the result back as a tool message.

tools = [{
    "type": "function",
    "function": {
        "name": "get_order_status",
        "description": "Look up an order by its ID.",
        "parameters": {
            "type": "object",
            "properties": {"order_id": {"type": "string"}},
            "required": ["order_id"],
            "additionalProperties": False,
        },
    },
}]

completion = client.chat.completions.create(
    model="plugsky-pro",
    messages=[{"role": "user", "content": "Where is order A-1042?"}],
    tools=tools,
    tool_choice="auto",
)

message = completion.choices[0].message
if message.tool_calls:
    call = message.tool_calls[0]
    print(call.function.name, call.function.arguments)

Not every model advertises function calling. Check the model's feature list before you depend on it, and return a clear error to the user if the selected model cannot call tools. Schema errors come back as invalid_tool_schema; simplify unsupported JSON Schema keywords rather than retrying the same request.

Create embeddings

embedding = client.embeddings.create(
    model="plugsky-embed",
    input=["first document", "second document"],
)

print(len(embedding.data[0].embedding))  # 2048

plugsky-embed returns 2,048-dimension vectors and accepts up to 2,048 inputs per request. The optional dimensions parameter truncates the output; if you use it, query with the same dimension count and rebuild any collection that was indexed at the full size.

Embeddings are billed from the same plan as chat on self-serve plans, with no separate per-token meter. The practical limit is the plan's fair-use rate and the batch ceiling, not a separate embedding quota.

Representative Plugsky model IDs for SDK work
Model IDContextMax outputFeaturesUse it for
plugsky-pro262,14416,384Chat, streaming, JSON mode, tools, codeGeneral production chat and agents.
plugsky-frontier262,1448,192Chat, streaming, JSON mode, tools, long contextHarder reasoning and long documents.
plugsky-vision-fast131,0724,096Chat, streaming, vision, JSON modeDocuments, screenshots and image questions.
plugsky-embed8,192n/aEmbeddings, RAG, semantic searchVectors at 2,048 dimensions.

A model ID is a routing label, not a guarantee about the engine behind it. Plugsky exposes the actual serving model in the x-plugsky-served-model response header and in the model catalogue, which is the authoritative source when you need to record what produced an output.

Handle errors like a production client

The SDK raises typed exceptions. Catch the specific class you can act on, then fall back to APIStatusError for the rest.

import openai

try:
    response = client.chat.completions.create(
        model="plugsky-pro",
        messages=[{"role": "user", "content": "Hello"}],
    )
except openai.AuthenticationError:
    raise
except openai.RateLimitError as exc:
    retry_after = exc.response.headers.get("retry-after")
    print("rate limited", retry_after)
except openai.APIStatusError as exc:
    print(exc.status_code, exc.request_id, exc.body)

Plugsky adds error_code, retry_after, request_id and a limit object to the OpenAI-shaped error body. Read them: plan_rpm_limit and plan_concurrency_limit call for pacing or a plan change, while upstream_unavailable is a transient routing failure.

SDK exception, HTTP status and the action to take
ExceptionHTTPTypical causeAction
BadRequestError400Malformed body, context too large, invalid tool schema.Fix the request; do not retry unchanged.
AuthenticationError401Missing or revoked key.Create a new key; do not retry.
PermissionDeniedError403Plan does not include the feature, or the account is restricted.Check the plan and account status.
NotFoundError404Model ID is not in the catalogue.Read /v1/models and use a current ID.
RateLimitError429RPM, concurrency or daily cap reached.Honour Retry-After; back off with jitter.
InternalServerError5xxUpstream or gateway failure.Retry with a cap; log the request_id.
APITimeoutErrorn/aClient timed out before the response completed.Retry, shorten the request or raise the timeout.

The SDK retries connection errors, timeouts, 408, 409, 429 and 5xx responses twice by default. That is a good baseline, not a complete policy: add jitter, cap total attempts, and make writes idempotent so a retry cannot duplicate a side effect.

Migration checklist

  1. Set base_url and a Plugsky key in the environment.
  2. Map each OpenAI model name to a Plugsky ID and record the mapping in config, not in code.
  3. Run your evaluation set for accuracy, tool calling, JSON validity and long-context behaviour.
  4. Check timeouts and retries against your own SLO; the SDK defaults may be too patient for interactive use.
  5. Log usage, request_id and x-plugsky-served-model for every request.
  6. Load-test at your plan's concurrency and RPM before cutover.

The step-by-step version, including the exact code diff and rollback plan, is in the OpenAI migration guide.

What we did not verify

  • We did not benchmark latency or answer quality for any model. The model table is a capability summary, not a ranking.
  • We did not test every SDK release. Package behaviour and defaults were checked against the current README and source on 20 November 2026.
  • We did not verify OpenAI product parity beyond chat completions and embeddings; assume other products are out of scope until documented.
  • We did not review a security report for your deployment. Request the current SOC 2 report under NDA and confirm its scope and period; do not treat readiness as certification.

Frequently asked questions

Can I use the OpenAI Python SDK with Plugsky?

Yes, for the endpoints Plugsky implements: chat completions and embeddings. Install the openai package, set base_url to https://api.plugsky.com/v1, use a Plugsky model ID and keep the rest of your Chat Completions code unchanged.

Which client parameter changes for Plugsky?

The base URL. Python uses base_url, while the Node SDK uses baseURL. The API key is a normal bearer key, and the model names must be Plugsky IDs such as plugsky-pro or plugsky-embed.

Does streaming work with the Python SDK?

Yes. Pass stream=True and iterate over the returned stream. Read chunk.choices[0].delta.content, which can be None for the first and last chunks, rather than the non-streaming message content field.

How do I call an async endpoint?

Use AsyncOpenAI instead of OpenAI and await the create call. For a stream, await the create call once to get the async iterator, then consume it with async for.

Which errors should I retry?

Retry rate limits, timeouts, connection failures and most 5xx responses with exponential backoff and jitter. Do not retry authentication, permission, not-found or malformed-request errors until the request or account is fixed.

Does the SDK support embeddings and tool calling?

Yes. Embeddings use client.embeddings.create with plugsky-embed, which returns 2,048-dimension vectors. Tool calling uses the standard tools and tool_choice parameters on models that advertise function calling.

Related pages

Keep the SDK, change the endpoint

Start free, run your evaluation set, then move to the plan that matches your concurrency and output ceiling.

Start Free → See pricing

Sources

SDK behaviour was checked against the official repository and API reference on 20 November 2026. Plugsky limits were checked against its docs on the same date.

Official pages used for this integration guide
SourcePage checkedChecked
OpenAIopenai-python repository and README20 Nov 2026
OpenAIChat Completions API reference20 Nov 2026
OpenAIPython SDK API reference20 Nov 2026
PlugskyQuickstart and API docs20 Nov 2026

Last checked 20 November 2026. Plan terms live at /pricing; the live model list is at /models.