lucidity.sh platform
← All posts

Synth 2.5 with LangChain, LiteLLM and the Vercel AI SDK: Setup and Pitfalls

Most teams don't call a model API by hand. They call it through a framework. Here is the working configuration for the three most common ones, and the defaults in each that break against a non-OpenAI endpoint.

Short answer: every framework that speaks OpenAI Chat Completions works with the LuciditySH Platform. Set the base URL to https://platform.lucidity.sh/v1, use an sh-live- key and a model id like synth-2.5-pro. Three things go wrong often enough to plan for. LangChain may pick the Responses API, so set use_responses_api=False. Structured-output helpers rely on JSON schema support the platform doesn't document, so validate JSON yourself. And parallel batch helpers run into Synth 2.5 Pro's shared limit of 5 requests per minute, so send batch work to synth-2.5-flash.

What the API supports

Before wiring a framework in, check which parts of the OpenAI API it will call. The LuciditySH Platform implements a deliberately small surface:

FeatureStatusWhat it means for you
Chat Completions (POST /v1/chat/completions)SupportedAll three frameworks work through it.
Streaming (stream: true, stream_options.include_usage)SupportedFallback only happens before the first byte.
GET /v1/models and /v1/models/{id}SupportedLists hosted models only, so clients that probe the list first work.
models: [...] fallback chainSupported (platform field)Pass through extra_body or providerOptions.
Responses API (/v1/responses)Not offeredTurn it off in LangChain with use_responses_api=False.
Embeddings (/v1/embeddings)Not offeredUse a separate embedding provider for RAG.
tools, response_formatNot documentedForwarded to the model server as sent; not a guaranteed feature.

The gateway rewrites only model and stream. Everything else in the request body, including temperature, top_p, max_tokens and stop, reaches the model server unchanged. So framework sampling settings work as written. It also means an undocumented field gets no error from the gateway; it just isn't guaranteed to do anything.

Two models are available today: synth-2.5-pro ($0.10 per million input tokens, $0.20 output) and synth-2.5-flash ($0.03 and $0.10). Both are creative-writing models with a 32,000-token context window on the platform. Our Synth 2.5 production guide covers sampling values, fallback and retries in detail. This post is about getting a framework to use them correctly.

LangChain (Python)

Use ChatOpenAI from langchain-openai, not a community wrapper. The one setting people miss is use_responses_api. LangChain partly infers whether to call Chat Completions or OpenAI's newer Responses API from the model name, and its reference recommends setting it to False explicitly for OpenAI-compatible providers. The platform has no Responses endpoint, so set it.

import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="synth-2.5-pro",
    base_url="https://platform.lucidity.sh/v1",
    api_key=os.environ["LUCIDITY_API_KEY"],  # sh-live-...
    use_responses_api=False,  # the platform serves Chat Completions only
    temperature=0.9,
    max_tokens=400,
    top_p=0.95,
)

msg = llm.invoke([("system", SYSTEM_PROMPT), ("human", "Open the scene.")])
print(msg.response_metadata["model_name"])  # synth-2.5-pro, or synth-2.5-flash after a fallback
print(msg.usage_metadata)                    # input_tokens, output_tokens, total_tokens

response_metadata["model_name"] is the field to log. When Synth 2.5 Pro is over capacity, the platform answers with Synth 2.5 Flash and reports that in the response's model field. LangChain drops non-standard response fields, so the platform's lucidity_fallback object never reaches your code. The model name still tells you a fallback happened.

For platform-specific request fields, LangChain's reference says to use extra_body, not model_kwargs. That is how you send an explicit fallback chain:

# Pin the chain yourself: never fall back from Pro.
pro_only = ChatOpenAI(
    model="synth-2.5-pro",
    base_url="https://platform.lucidity.sh/v1",
    api_key=os.environ["LUCIDITY_API_KEY"],
    use_responses_api=False,
    extra_body={"models": ["synth-2.5-pro"]},
)

# Batch work: go straight to Flash and cap concurrency.
flash = ChatOpenAI(model="synth-2.5-flash", base_url="https://platform.lucidity.sh/v1",
                   api_key=os.environ["LUCIDITY_API_KEY"], use_responses_api=False)
results = flash.batch(prompts, config={"max_concurrency": 4})

With models: ["synth-2.5-pro"], a busy Pro comes back as a 429 with a Retry-After header instead of a Flash answer. Use it when a Flash reply would break a promise you made, for example in a paid tier sold as "Pro".

LiteLLM SDK and proxy

LiteLLM routes any OpenAI-compatible endpoint through the openai/ model prefix. Keep /v1 on the base URL. LiteLLM's docs name a missing /v1 as the usual cause of a Not Found error, and they say to give no deeper path, since LiteLLM appends the endpoint itself.

import os, litellm

resp = litellm.completion(
    model="openai/synth-2.5-pro",               # "openai/" = OpenAI-compatible route
    api_base="https://platform.lucidity.sh/v1",  # keep the /v1
    api_key=os.environ["LUCIDITY_API_KEY"],
    messages=[{"role": "user", "content": "Write a two-line hook for a heist story."}],
    temperature=0.9,
    max_tokens=200,
)
print(resp.model, resp.usage)

The LiteLLM proxy is the better fit for a company with several services. You register the platform once, give each entry a name your services request, and keep the sh-live- key on the proxy host only:

model_list:
  - model_name: story-writer            # what your services ask for
    litellm_params:
      model: openai/synth-2.5-pro
      api_base: https://platform.lucidity.sh/v1
      api_key: os.environ/LUCIDITY_API_KEY
  - model_name: story-writer-bulk
    litellm_params:
      model: openai/synth-2.5-flash
      api_base: https://platform.lucidity.sh/v1
      api_key: os.environ/LUCIDITY_API_KEY

Two cautions. First, LiteLLM has its own fallback and retry settings. If you turn those on as well, a Pro request can be retried by LiteLLM after the platform has already fallen back to Flash, which doubles attempts and muddies your logs. Pick one layer to own fallback; the platform's is already on by default for synth-2.5-pro. Second, if you use LiteLLM's spend tracking, check its numbers against the platform's Usage page, which is what your balance is charged from.

Security update, November 23, 2026: several LiteLLM proxy vulnerabilities are being exploited. Run the current release and keep the admin routes off the internet. Details and what to rotate.

Vercel AI SDK

Use @ai-sdk/openai-compatible, which exists for exactly this case, rather than the OpenAI provider, which targets OpenAI's own API. Run it on the server (a route handler or server action) so the key never reaches the browser.

import { createOpenAICompatible } from '@ai-sdk/openai-compatible'
import { generateText } from 'ai'

const lucidity = createOpenAICompatible({
  name: 'lucidity',
  baseURL: 'https://platform.lucidity.sh/v1',
  apiKey: process.env.LUCIDITY_API_KEY,
  includeUsage: true, // usage in streaming responses
})

const { text } = await generateText({
  model: lucidity('synth-2.5-pro'),
  system: SYSTEM_PROMPT,
  prompt: 'Open the scene.',
  temperature: 0.9,
  maxOutputTokens: 400,
  // Extra body fields go under the provider name. This one pins Pro with no fallback.
  providerOptions: { lucidity: { models: ['synth-2.5-pro'] } },
})

The name you give the provider is the key for providerOptions; the AI SDK docs say the key is camelCase, so lucidity stays lucidity. Fields placed there go into the request body. Set includeUsage: true if you stream. It is off by default, and without usage on streamed responses you lose per-request cost data, which you need for tracking cost per customer.

Structured output without JSON schema mode

This is the pitfall that costs teams the most time. Since langchain-openai 0.3.0, with_structured_output defaults to method="json_schema", which uses OpenAI's Structured Outputs. Its other methods use tool calling or JSON mode. The LuciditySH Platform documents none of these. The fields reach the model server, but nothing guarantees they are enforced. You may get valid JSON in testing and prose in production.

For Synth 2.5, treat structure as a prompt instruction you verify in code:

import json
from pydantic import BaseModel, ValidationError

class Blurb(BaseModel):
    title: str
    body: str

PROMPT = """Write a product blurb for: {item}
Answer with only a JSON object: {{"title": "...", "body": "..."}}"""

def blurb(item: str, tries: int = 3) -> Blurb:
    for _ in range(tries):
        text = llm.invoke(PROMPT.format(item=item)).content
        start, end = text.find("{"), text.rfind("}")
        try:
            return Blurb.model_validate(json.loads(text[start:end + 1]))
        except (ValueError, ValidationError):
            continue
    raise RuntimeError("no valid JSON after retries")
  • Use Pro for anything structured. The Synth 2.5 Flash card says it cannot follow deep prompts that need heavy, specific formatting.
  • Keep the schema small. Two to five flat fields parse reliably. Nested objects and enums fail more often; generate them in code from simpler fields.
  • Slice from the first { to the last } before parsing. Creative models often add a line of preamble.
  • Count retries. Each failed parse is a paid request. If retries pass a few percent, simplify the schema before raising the retry count.

Synth 2.5 is a writing model. If a step needs a strict schema, such as extracting fields from an invoice, a model built for structured extraction is the better tool for that step. Synth then writes the text a person reads.

Batch helpers and the Pro rate limit

Framework batch helpers run requests in parallel by default: LangChain's batch and abatch, map-reduce summarization chains, and Promise.all over AI SDK calls. Synth 2.5 Pro has a capacity limit of 5 requests per minute shared across all callers. A 50-item batch on Pro will see most items rejected by that limit and answered by Flash through fallback, after a wasted Pro attempt each time.

The fix is a routing rule, not a bigger retry budget. Send batch and background work to synth-2.5-flash, cap concurrency with max_concurrency in LangChain's run config (or a small promise pool in JavaScript), and keep synth-2.5-pro for interactive traffic where a person waits on each reply.

RAG and agents: what to plan around

  • RAG works with a separate embedding model. The platform has no /v1/embeddings. Index and retrieve with any embedding provider, then put the retrieved passages in the Synth prompt. Budget the 32,000-token window: system prompt, passages, history and the reply all share it.
  • Agents that depend on tool calling are a poor fit today. Tool calls are not part of the documented API. A ReAct-style agent that asks for actions in plain text and parses them can work, with the same validate-and-retry loop as above.
  • Moderation is your job. Both Synth 2.5 model cards say the models can produce harmful or NSFW content and recommend a moderation layer in production. LangChain and the AI SDK don't add one for you. See how to write moderation policies a guard model can enforce.

Framework integration FAQ

Can I use Synth 2.5 with LangChain?

Yes. Use ChatOpenAI from langchain-openai with base_url set to https://platform.lucidity.sh/v1, an sh-live- API key, model synth-2.5-pro or synth-2.5-flash, and use_responses_api=False. The served model name is in response_metadata["model_name"] and token counts are in usage_metadata.

How do I add LuciditySH Platform to LiteLLM?

Prefix the model with openai/ and set api_base to https://platform.lucidity.sh/v1, for example model="openai/synth-2.5-pro". In the LiteLLM proxy, put the same three values under litellm_params in model_list and give the entry any model_name your services should call.

Does the LuciditySH Platform API support tool calling or JSON schema output?

Neither is part of the documented API. The gateway forwards fields like tools and response_format to the model server unchanged, but the platform does not guarantee them. For structured data, ask for JSON in the prompt, validate it in your code and retry on failure, preferably on Synth 2.5 Pro.

Why does with_structured_output fail or return bad JSON with Synth?

Since langchain-openai 0.3.0, with_structured_output defaults to method="json_schema", which relies on OpenAI's Structured Outputs feature. The LuciditySH Platform does not document that feature, so parse and validate JSON yourself instead of relying on it.

Can I use Synth 2.5 for embeddings or RAG?

Synth 2.5 can be the generator in a RAG pipeline, but the platform has no embeddings endpoint. Use a separate embedding model for indexing and retrieval, then send the retrieved passages to Synth 2.5 in the prompt.

Sources

Create a key, paste it into any snippet above, and your existing framework code runs on Synth 2.5. No monthly fee; you pay per token.

Create an account