2027 integration guide · Evidence checked 20 November 2026

LangChain with Plugsky: OpenAI-Compatible Setup

LangChain does not need a Plugsky-specific package. Its official OpenAI adapter, ChatOpenAI, accepts a custom base URL, so the integration is a package install, a key and one URL change. This guide covers the exact settings, working Python and TypeScript examples, the features that pass through cleanly, and the errors that catch teams during migration.

Short answer. Plugsky exposes an OpenAI-compatible Chat Completions endpoint, so LangChain connects through the langchain-openai package. Install it, set base_url to https://api.plugsky.com/v1 and your Plugsky key, then use a plugsky-* model ID. Chat, streaming, tool calling, structured output and embeddings work; provider-specific fields and some Responses features need testing.

What the LangChain integration actually connects

LangChain is the orchestration layer: it builds prompts, chains, tools, retrievers and agents. It does not serve a model. ChatOpenAI is the adapter that turns a LangChain message list into an HTTP request and turns the response back into an AIMessage. Plugsky supplies the model behind an OpenAI-compatible endpoint at https://api.plugsky.com/v1.

That means there is no plugin to install on the Plugsky side and no gateway to run. The adapter package is langchain-openai, maintained by the LangChain team, and it uses the official OpenAI Python or JavaScript SDK underneath. If a LangChain feature depends on a non-standard OpenAI response field, it may not survive the adapter; the limitations section below lists the cases that matter.

Three-line setup

  1. Install the adapter: pip install -U langchain-openai.
  2. Export your key: on macOS or Linux, export OPENAI_API_KEY="YOUR_PLUGSKY_API_KEY". ChatOpenAI reads OPENAI_API_KEY by default.
  3. Point at Plugsky: ChatOpenAI(model="plugsky-pro", base_url="https://api.plugsky.com/v1").

Those three lines are enough for a first call. The environment-variable route is convenient for a shell test, but it shares one key name with every OpenAI client in that shell. In application code, pass api_key explicitly from your secret manager so the Plugsky key is not picked up by an unrelated OpenAI call.

Python
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="plugsky-pro",
    base_url="https://api.plugsky.com/v1",
    api_key="YOUR_PLUGSKY_API_KEY",
    temperature=0.2,
    max_tokens=1024,
)

messages = [
    ("system", "You are a concise support engineer."),
    ("human", "Explain the difference between RAG and fine-tuning."),
]
response = llm.invoke(messages)
print(response.content)

Chat, streaming and tool calls in Python

invoke returns an AIMessage. The visible text is in content; token usage, when the endpoint returns it, is in usage_metadata. Keep the message objects rather than flattening them to strings if you plan to add tools or continue the conversation, because role boundaries and tool call IDs are part of the request.

Token streaming uses the same object. The adapter reads server-sent events and yields chunks as they arrive. Print chunk.content as it comes; do not assume every chunk contains text, because the final chunk may carry usage or finish metadata instead. LangChain's guidance notes that stream usage defaults change when a custom base URL is configured through OPENAI_BASE_URL, so test the final chunk before relying on usage metadata.

Python
for chunk in llm.stream(messages):
    if chunk.content:
        print(chunk.content, end="", flush=True)

Tool calling uses the standard OpenAI function schema. Decorate a Python function with @tool, bind it to the model, then inspect tool_calls on the response and return a ToolMessage with the result. The model proposes the call; your code decides whether to execute it. That separation is the security boundary.

Python
from langchain.tools import tool

@tool
def get_order_status(order_id: str) -> str:
    """Return the fulfilment status for an order ID."""
    return "shipped"

llm_with_tools = llm.bind_tools([get_order_status])
result = llm_with_tools.invoke("Where is order A-1042?")
print(result.tool_calls)

Structured output is available through with_structured_output. Use a Pydantic model or a JSON schema, and validate the parsed object again in your application. A schema-constrained generation reduces malformed output but does not prove that the values are correct or authorised.

TypeScript and JavaScript setup

The JavaScript adapter uses the same OpenAI SDK conventions, but the custom URL lives under configuration.baseURL, not a top-level base_url. The camel-case spelling matters. Install @langchain/openai, then instantiate ChatOpenAI with the model, key and configuration object.

TypeScript
import { ChatOpenAI } from "@langchain/openai";

const llm = new ChatOpenAI({
  model: "plugsky-pro",
  apiKey: process.env.PLUGSKY_API_KEY,
  configuration: { baseURL: "https://api.plugsky.com/v1" },
});

const reply = await llm.invoke("Draft a two-line changelog entry.");
console.log(reply.text);

Streaming in JavaScript uses await llm.stream(...) and an async iterator. Tool calling uses bindTools with the same JSON schema shape. The adapter is maintained separately from the Python package, so pin a version and run the same smoke test in both languages if you ship both.

Embeddings and RAG

Plugsky publishes three embedding IDs: plugsky-embed, plugsky-embed-nim and plugsky-embed-multilingual. They return 2,048-dimension vectors and share an 8,192-token input window. Configure your vector store for 2,048 dimensions before you ingest documents; changing dimension later means reindexing.

There is one adapter-specific setting to know. OpenAIEmbeddings normally tokenises text with tiktoken and sends integer token arrays. Many non-OpenAI endpoints expect raw strings and reject arrays. LangChain's own reference recommends check_embedding_ctx_length=False for non-OpenAI providers, which sends text instead of tokens, and suggests encoding_format="float" (passed through model_kwargs) when the endpoint does not accept base64. Set both deliberately and test one document before a bulk load.

Python
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings(
    model="plugsky-embed",
    base_url="https://api.plugsky.com/v1",
    api_key="YOUR_PLUGSKY_API_KEY",
    check_embedding_ctx_length=False,
    model_kwargs={"encoding_format": "float"},
)

vector = embeddings.embed_query("What is an OpenAI-compatible API?")
print(len(vector))  # 2048

For retrieval, keep chunk sizes well below the embedding window and store the source URL and section heading with each vector. The agents and RAG architecture guide covers the retrieval loop, evaluation and observability in more depth.

Supported features and what to expect

The table separates features that pass through the OpenAI adapter from features that depend on a specific endpoint or response field. “Documented” means Plugsky's API reference lists the endpoint; it does not mean every LangChain wrapper has been tested with it.

LangChain features against the Plugsky OpenAI-compatible API
FeatureStatusWhat to check
Chat CompletionsSupportedChatOpenAI.invoke sends POST /v1/chat/completions; use an exact plugsky-* ID.
Token streamingSupported.stream() reads server-sent events; empty text chunks are normal.
Tool callingSupportedStandard OpenAI tool schema through bind_tools; validate arguments before execution.
Structured outputSupportedwith_structured_output with a Pydantic model or JSON schema; revalidate the result.
JSON modeSupportedSet an OpenAI-style response_format and still parse defensively.
EmbeddingsSupported2,048 dimensions, 8,192-token input; set check_embedding_ctx_length=False.
Responses APITest firstPlugsky's documentation lists /v1/responses, but ChatOpenAI defaults to Chat Completions unless you opt in with use_responses_api=True.
Provider-specific fieldsNot preservedLangChain states that non-standard fields such as reasoning_content are not extracted by ChatOpenAI.
Image, audio and video generationUse HTTPThese are separate endpoints, not part of the chat adapter; call them with the OpenAI SDK or raw HTTP.
Prompt cachingNot publishedWe found no documented cache-control contract, so do not plan savings from cached input.

Limits that change application design

Plugsky serves 39 public model IDs. Main text models have a 262,144-token context window; plugsky-mistral-medium and the vision models use 131,072, plugsky-translate uses 32,768, and the embedding models use 8,192 input tokens. The plan can impose a lower input ceiling than the model. Builder allows 256K input and 32K output per request; Scale allows a 512K plan input ceiling and 32K output, while the model's own window still applies.

Context is shared between input and output. A 250,000-token prompt on a 262,144-token model leaves almost no room for an answer, and the API may reject the request even though the prompt alone “fits”. Reserve output tokens explicitly and trim history before you hit the ceiling. The context window calculator does that arithmetic, including the plan ceiling and output reserve.

Concurrency is per account, not per chain. A LangChain pipeline that fans out to eight parallel branches consumes eight concurrent requests. Builder includes 10 concurrent requests and 600 RPM; Scale includes 16 and 1,200 RPM; Hobby is limited to 4 and 120 RPM. If your graph runs tools in parallel, the concurrency limit will bind before the monthly token allowance.

Token counting inside LangChain is an estimate based on OpenAI encodings. Plugsky's public docs do not publish a tokenizer, so treat get_num_tokens_from_messages as a planning number, and use the usage_metadata returned by the API as the authoritative count for a completed request.

Error table and fixes

Most integration failures are configuration, not model behaviour. The status code tells you which layer to inspect: the key, the URL path, the model ID, the request size or the plan limit.

Common LangChain and Plugsky errors, causes and fixes
StatusTypical causeFix
401Missing, revoked or wrong-host API keyRe-enter the Plugsky key; confirm the request goes to api.plugsky.com, not an OpenAI host.
403The key lacks the required scope or roleCheck the key role in the dashboard; create a key with the scope the workload needs.
404Wrong base URL path or unknown model IDUse https://api.plugsky.com/v1 and an ID from GET /v1/models.
400 (context)Input plus reserved output exceeds the model or plan windowTrim history, reduce max_tokens, or move to a larger plan ceiling; the error reports token counts.
413Request body is too largeSend fewer messages or a smaller document; chunk long inputs before the call.
429RPM, concurrency or daily quota exhaustedHonour Retry-After, add exponential backoff, and reduce parallel branches.
500, 502, 503Server or upstream failure, possibly after failoverRetry with jittered backoff; check the status page before changing code.

Production checklist

  • Pin the adapter version and the model ID; do not let a floating latest tag change behaviour under a release.
  • Set an explicit request timeout and a max_retries value. The OpenAI SDK retries transient failures by default, but the default may not match your latency budget.
  • Cap max_tokens at the plan output ceiling: 8K on Hobby, 16K on Starter, 32K on Builder and Scale.
  • Log request IDs, model ID, token usage and latency; keep prompts and completions out of logs unless the data policy allows them.
  • Read the x-plugsky-served-model response header at the HTTP layer when you need the actual serving engine behind a legacy ID.
  • Test a 429 path and a context-overflow path before launch; both are routine in production and both are recoverable.

When LangChain is the right layer — and when it is not

LangChain is a good fit when you need a provider-neutral message abstraction, tool binding, retrievers, callbacks and a large ecosystem of integrations. It is a poor fit when you need a thin, dependency-free client for one endpoint, or when your team already has an orchestration layer and does not want another abstraction. The OpenAI SDK alone is smaller; a direct HTTP call is smaller still.

Plugsky also exposes a gateway-style surface for teams that want routing and observability in front of multiple providers. If the requirement is central governance rather than chain composition, read the AI gateway overview and compare it with running LangChain in-process.

What we did not verify

  • We did not run latency, throughput or uptime benchmarks against Plugsky or any other provider. No performance number on this page is a measurement.
  • We did not test every LangChain integration, callback handler, vector store or LangGraph backend. This page covers only the ChatOpenAI and OpenAIEmbeddings adapters described above.
  • We did not confirm that ChatOpenAI(use_responses_api=True) preserves every stateful Responses feature through the Plugsky route. Treat it as a test item.
  • We did not verify streaming usage metadata on a custom base URL; LangChain's own documentation says the default changes when a custom URL is set.
  • We did not compare Plugsky token counts with tiktoken. Plugsky's public docs do not publish a tokenizer, so all client-side counts are estimates.
  • We used the API host https://api.plugsky.com/v1 throughout. Confirm the host in your account documentation before launch.

Frequently asked questions

Is LangChain compatible with Plugsky?

Yes for the OpenAI adapter. LangChain's ChatOpenAI class and OpenAIEmbeddings class talk to the Chat Completions and embeddings endpoints, and Plugsky implements both behind an OpenAI-compatible API. Install langchain-openai, set the base URL to https://api.plugsky.com/v1, and use a Plugsky model ID.

Which base URL should LangChain use for Plugsky?

Use https://api.plugsky.com/v1, including the /v1 suffix and without a trailing slash. ChatOpenAI appends /chat/completions to that root. A base URL without /v1 usually produces a 404 because the SDK calls the wrong path.

Which model name should I pass to ChatOpenAI?

Use an exact public ID such as plugsky-pro or plugsky-micro. Plugsky's catalogue contains 39 public plugsky-* IDs, and gpt-4o is not one of them. List the current IDs from GET https://api.plugsky.com/v1/models before you pin one in production.

Does streaming work through LangChain with Plugsky?

Token streaming works through ChatOpenAI.stream, which reads server-sent events from the Chat Completions endpoint. Usage metadata during a stream is a separate setting. LangChain's documentation says the default changes when OPENAI_BASE_URL is set, because many non-OpenAI endpoints do not support streaming usage, so request it explicitly only after testing that your route returns usage in the final chunk.

Do LangChain tool calls and structured output work?

Standard OpenAI tool schemas work through bind_tools, and with_structured_output can use function calling or JSON schema. Validate the returned arguments in your own code, limit the tool set per request, and test parallel tool calls. Non-standard response fields are not preserved by ChatOpenAI.

How do I fix a 401 or 404 error in LangChain?

A 401 means the key is missing, revoked or sent to the wrong host. A 404 usually means the base URL is wrong or the model ID does not exist on Plugsky. Check that the key starts with your Plugsky prefix, confirm https://api.plugsky.com/v1, and call the models endpoint to verify the exact ID.

Can I use LangGraph with Plugsky?

Yes in principle, because LangGraph builds on LangChain model objects. The same ChatOpenAI instance can be passed into a graph, and tool calling uses the same OpenAI schema. This page tests the ChatOpenAI adapter, not every LangGraph checkpoint, store or deployment backend.

Related pages

Run your first LangChain chain on Plugsky

Start on the free plan with two keys, then move to Builder or Scale when concurrency and context ceilings matter.

Start Free → Read the docs

Sources

Every claim about LangChain behaviour was checked on the linked official page on 20 November 2026. Plugsky plan and model facts come from the canonical pricing page and the live model catalogue. Prices and limits change; recheck before quoting.

Official pages used for this guide
SourcePage checkedChecked
LangChaindocs.langchain.com — ChatOpenAI integration (Python)20 Nov 2026
LangChaindocs.langchain.com — ChatOpenAI integration (JavaScript)20 Nov 2026
LangChainreference.langchain.com — OpenAIEmbeddings20 Nov 2026
Plugskyplugsky.com/pricing and plugsky.com/models20 Nov 2026
Plugskyplugsky.com/docs20 Nov 2026

Last checked 20 November 2026. Plugsky's canonical plan numbers live at /pricing; this page explains the integration and does not replace the plan terms.