cmpnd
The cmpnd package traces, deploys and optimizes DSPy programs on the cmpnd
platform. You give a program a name, and a client records its traces,
deployments and optimization runs under that name.
Installation
uv add cmpnd # or: pip install cmpnd
The interactive cmpnd shell uses IPython when you install the shell extra:
uv add 'cmpnd[shell]' or pip install 'cmpnd[shell]'. The plain install
leaves IPython out, and the shell then runs on the standard Python prompt.
Two independent ways to use the SDK
The SDK has two ways to use it, and they are independent:
cmpnd.Client is for a program you keep. A client holds its own account,
tags and providers. It runs, deploys and optimizes programs, and it looks
up your organization's providers.
cmpnd.configure() with cmpnd.auto_instrument() is for sketching. It
traces every DSPy call in the process.
The two do not share settings, and neither changes the other. A client never
reads cmpnd.configure(), and cmpnd.configure() never changes a client. Both
can run in one process. Pick the way that fits the job, and do not expect a
setting from one to apply to the other.
Authentication
The cmpnd library works with the cmpnd service at
platform.cmpnd.ai. Create an API key on the
platform under Settings → API keys. A client takes the key as
cmpnd.Client(api_key=). The sketching path takes it as
cmpnd.configure(api_key=). Each way reads only its own argument, and both
use CMPND_API_KEY when the argument is missing. For a self-hosted cmpnd
install, also pass the install's URL as endpoint= to the same call, or set
CMPND_ENDPOINT.
With no api_key= and no CMPND_API_KEY, the library uses the key that
cmpnd login stored for the endpoint, as the command line does. That is the
active organization's key (cmpnd org switch). A script on a machine where
you ran cmpnd login needs no key of its own.
Quick start
A program name is the name your organization gives a program, such as
question-answerer. Traces, deployments and optimization runs under one
program name go to one program. The platform makes the program the first time
your organization uses the program name.
@cmpnd.program(name) above a dspy.Module class gives the class a program
name. Building the class takes its own arguments and a required lm=. The
lm= argument is the dspy.LM that the program runs on:
import cmpnd
import dspy
class Answer(dspy.Signature):
"""Answer the question in one short sentence."""
question: str = dspy.InputField()
answer: str = dspy.OutputField()
@cmpnd.program("question-answerer")
class QA(dspy.Predict):
def __init__(self):
super().__init__(Answer)
qa1 = QA(lm=dspy.LM("openai/gpt-6-luna"))
A cmpnd.Client runs the program and records its trace under the program
name:
gepa = dspy.GEPA(metric=metric, reflection_lm=dspy.LM("openai/gpt-6-luna"), auto="light")
with cmpnd.Client(api_key="ck_xxx", project_tags="my-project") as sdk:
# the trace goes to the program "question-answerer"
result = sdk.run_program(qa1, question="What is DSPy?")
qa2 = sdk.optimize_program(qa1, gepa, trainset=train, valset=val)
cmpnd.trace_id(result) # "a1b2c3d4-...", the trace of this run
cmpnd.trace_id() links a result to its platform trace, for example to attach
feedback later. A client records only the programs you run through it.
A client is active from construction. The with form flushes the client's
traces and closes it on exit. Without with, the client stays active until
you call close() or the process exits, and its traces go out at exit:
sdk = cmpnd.Client(api_key="ck_xxx", project_tags="my-project")
sdk.run_program(qa2, question="What is DSPy?")
# optional: flushes the traces now, so a later read sees them
sdk.close()
The cmpnd.Program constructor gives a program name to a module you already
have, such as a dspy.Predict. It makes the same kind of
program as the decorator:
qa3 = cmpnd.Program(
"question-answerer", module=dspy.Predict("question -> answer"), lm=dspy.LM("openai/gpt-6-luna")
)
- A program name starts with an ASCII letter or digit, then has letters,
digits,
., _ or -, at most 64 characters. It does not start with p_.
A bad name raises ValueError. Declaring a program makes no network call.
optimize_program runs the optimizer in your process and returns a copy of
the program that holds the optimized module. The copy keeps the program name
and the LM.
Sketching with auto_instrument()
cmpnd.auto_instrument() records a trace of every DSPy call in the process,
with no other change to your code. Use it to sketch a
DSPy program and see what it does:
cmpnd.configure(api_key="ck_xxx", project_tags="my-project")
cmpnd.auto_instrument()
dspy.configure(lm=dspy.LM("openai/gpt-6-luna"))
dspy.ChainOfThought("question -> answer")(question="What is DSPy?")
Each program shape gets a program of its own, under a name the SDK generates
from its class and signature, such as ChainOfThought-17e1f4089a24. These
programs do not count toward your plan's program limit. The first such trace in
a process logs a warning that names the generated name and shows how to give the
program a real one: @cmpnd.program(name) or cmpnd.Program(name, module=..., lm=...),
run through cmpnd.Client. Calling a cmpnd.Program directly while auto_instrument() is
on raises a TypeError that points to the client. The API reference below
lists the options of cmpnd.configure().
Deployed programs
Every deployment belongs to a program, and each program has a program name.
Give a DSPy module a program name with cmpnd.Program, then deploy it through a
client for server-side execution:
import cmpnd
import dspy
sdk = cmpnd.Client() # CMPND_API_KEY, else your cmpnd login
openai = sdk.get_provider("openai") # a provider your organization added
qa4 = cmpnd.Program(
"question-answerer", module=dspy.Predict("question -> answer"), lm=dspy.LM("openai/gpt-6-luna")
)
deployed = sdk.deploy_program(qa4, provider=openai)
result = sdk.run_deployment(deployed, question="What is DSPy?") # runs server-side
print(result.answer)
deploy_program() packages the module's source, sends it to the platform and
waits until the platform has read it. It then returns a DeployedProgram.
run_deployment() runs it server-side on the client's account, and also takes
a deployment ID. A DeployedProgram is not callable, because a run needs a
client. str(deployed) and deployed.deployment_id return the deployment ID.
deployed.artifact_metadata holds the typed artifact record when the platform
has inspected it. An unknown interface leaves input_fields and
output_fields as None. A known interface with no fields returns empty
lists.
The platform makes the program the first time your organization uses the
program name. Later deploys under the same program name go to the same
program, and so do the traces of a client that runs it.
Providers
A provider is a model provider's key that your organization sealed under a
name. A hosted program spends a provider, and the deploy names it. The program's code stays the code you run on your laptop:
# model_type="chat" keeps the LM on Chat Completions, which LunaRoute serves.
lm = dspy.LM("openai/deepseek-4.1-flash", api_base="https://gw.lunaroute.com/v1", model_type="chat") # unchanged
luna = sdk.get_provider("luna-exec")
deployed = sdk.deploy_program(program, provider=luna)
# deploy: default-lm: chat_completions openai/deepseek-4.1-flash → luna-exec (https://gw.lunaroute.com)
sdk.get_provider(name) returns a cmpnd.Provider holding the name,
the protocols its endpoint serves and its api_base. It holds no key. A name
the organization does not hold raises cmpnd.ProviderNotFound, which lists
the names it does hold and the nearest one. sdk.list_providers()
returns them all.
- Both read the client's own account, the one it deploys and optimizes on.
provider= takes a cmpnd.Provider, never a string. A string raises
and shows the client.get_provider(...) line to write.
- These older spellings still work and warn with a
DeprecationWarning:
credential= (use provider=), cmpnd.Credential and
cmpnd.CredentialNotFound (the same classes as cmpnd.Provider and
cmpnd.ProviderNotFound), and cmpnd.credentials.get(name) and
cmpnd.credentials.list(), which read the cmpnd.configure() account.
Replace each of these calls with sdk.get_provider(name) or
sdk.list_providers() on your client. Passing both provider= and
credential= raises TypeError.
- An organization may have no default provider. Then every deploy and every
optimization names its provider. The platform refuses one that names none,
and the refusal lists the names the organization holds. An owner sets a
default with
cmpnd providers default NAME, and a deploy without
provider= spends it.
- The deployment records the provider's name. Its runs spend the newest
key sealed under that name, so
run_deployment() takes no provider,
and an owner who rotates a key needs no redeploy.
- The deploy prints the protocol, model and provider of each binding, as
above. A server that prints none chose the provider from the model's
provider prefix, and the SDK warns.
- A hosted call goes to the provider's
api_base. The LM's own api_base
serves your laptop run and is not sent.
Keys never leave your laptop. The SDK sends no key on the LM, and a key reaches
the platform only when an owner adds a provider, with cmpnd providers add,
sdk.add_provider or the providers page. cmpnd deploy FILE
refuses source whose import builds an LM carrying a key, and names the module,
the model and the field.
Gateways
An OpenAI-compatible gateway, such as LunaRoute, is a provider of its own.
Add it with the gateway's provider type, or with --type openai-compatible and
the gateway's address:
cmpnd providers add luna-exec --type lunaroute < key.txt
cmpnd providers add my-gateway --type openai-compatible --base-url https://gateway.example.com/v1 < key.txt
Spell the gateway's models openai/<model>, such as
openai/deepseek-4.1-flash, and deploy with
provider=sdk.get_provider("luna-exec"). The openai/ prefix selects
the Chat Completions wire protocol, and the gateway receives the model after
the first /. The provider decides the address and the key, so one gateway
serves every model it routes.
The same source on your laptop and hosted
A program's logic runs unchanged on your laptop and hosted. On your laptop it
spends the key in your environment. Hosted, it spends a provider your
organization added. Keep the logic in one file and let a small entry point
choose where it runs.
The program file holds the logic and names its model. It holds no key:
# qa.py
import dspy
lm = dspy.LM("openai/gpt-5-mini") # no api_key: litellm reads OPENAI_API_KEY on your laptop
program = dspy.Predict("question -> answer")
def metric(gold, pred, trace=None, pred_name=None, pred_trace=None, lms=None):
verdict = dspy.Predict("answer, gold -> correct: bool")(answer=pred.answer, gold=gold.answer, lm=lms["critic"])
return dspy.Prediction(score=float(verdict.correct), feedback="correct" if verdict.correct else "wrong")
Add the key once for the organization:
printf '%s' "$OPENAI_API_KEY" | cmpnd providers add openai
sdk.add_provider("openai", api_key=os.environ["OPENAI_API_KEY"]) does the same from Python.
The entry point is the only code that knows where the run happens:
# main.py
import functools
import sys
import cmpnd
import dspy
from qa import lm, metric, program
HOSTED = "--hosted" in sys.argv
sdk = cmpnd.Client()
qa = cmpnd.Program("qa", module=program, lm=lm)
reflection = dspy.LM("openai/gpt-5", max_tokens=32000)
lms = {"critic": dspy.LM("openai/gpt-5-mini")}
train, val = load_examples() # your dspy.Example lists
if HOSTED:
openai = sdk.get_provider("openai")
deployed = sdk.deploy_program(qa, provider=openai)
print(sdk.run_deployment(deployed, question="What is DSPy?"))
best = sdk.optimize_deployment(
deployed,
trainset=train,
valset=val,
metric=metric, # the platform hands it lms
provider=openai, # every model below spends it
reflection_lm=cmpnd.HostedLM(reflection),
lms={name: cmpnd.HostedLM(model) for name, model in lms.items()},
auto="light",
)
else:
print(sdk.run_program(qa, question="What is DSPy?")) # spends $OPENAI_API_KEY
gepa = dspy.GEPA(metric=functools.partial(metric, lms=lms), reflection_lm=reflection, auto="light")
best = sdk.optimize_program(qa, gepa, trainset=train, valset=val)
python main.py runs everything on your laptop, and python main.py --hosted
runs it on the platform. cmpnd deploy qa.py qa --provider openai deploys
the same file from the terminal.
|
On your laptop |
Hosted |
| Key |
the provider's variable in your environment, such as OPENAI_API_KEY |
the credential the call names, else the organization's default, if one is set |
| Address |
the LM's api_base, else the provider's endpoint |
the credential's api_base |
| Model |
gpt-5-mini, the model after its first / |
gpt-5-mini |
The metric's lms |
the dict the entry point binds |
the run's lms=, which the platform hands it |
These rules keep the program file portable:
- Leave the key off the program's LM and let litellm read the provider's
own variable. For a key in a variable litellm does not read, write
api_key=os.environ.get("NAME"). cmpnd imports a deploy file with an empty
environment, so the key is None there and present on your laptop.
- Never write a key into the file, and never read it as
os.environ["NAME"] at module scope. The deploy refuses the first. The
second raises KeyError hosted, where the environment holds no key.
- Seal the credential at the address your laptop LM reaches. A program
that sets
api_base="https://gw.lunaroute.com/v1" needs a credential sealed
there, with --preset lunaroute or --api-base. Hosted calls go to the
credential's address and ignore the LM's api_base. The deploy prints the
address it chose, so you can compare the two.
- Wrap a model you hand the hosted optimization in
cmpnd.HostedLM. The
entry point builds reflection_lm= and each lms= entry, so those LMs may
hold a key for the laptop run. The wrapper leaves that key on your machine.
optimize_deployment refuses a key on an unwrapped LM, because there it would
look spent. cmpnd.HostedLM(model, provider=c) makes a model spend a
credential other than the run's.
A System One model, such as dspy.LM("typesafe:jev-latest") on DSPy 3.5, runs
unchanged in both places, as the program's own model or as a judge. So does a
judge built on DSPy 3.4's dspy.experimental.TypeSafe.
docs/sdk-instrumentation.md, under "System One
models", describes the hosted side.
Options
sdk.deploy_program(
program, # required: a cmpnd.Program
metric=None, # optional: a metric callable, packaged for optimization
timeout=300, # optional: seconds to wait for the deployment to be ready
metadata=None, # optional: a JSON-serializable dict, at most 64 KiB, stored with the deployment
provider=None, # a cmpnd.Provider the program's model spends, else the org's default, if one is set
)
How it works