DSPy Domain Model
LinkML schema for DSPy -- the framework for programming, not prompting, language models.
Covers the core abstractions of DSPy: signatures, modules, predictors, adapters, custom types (Image, Audio, Code, Tool, History), the typed LM request/response contract (LMRequest, LMResponse, LMMessage, LMConfig, LM*Part), LM clients & providers, the cache, teleprompters (optimizers), evaluation, retrievers, datasets, code interpreters, settings, streaming, and the public exception hierarchy.
URI: https://w3id.org/lmodel/dspy
Name: dspy
Classes
| Class | Description |
|---|---|
| Any | Arbitrary JSON-serializable value (object, array, or scalar) |
| EvaluationRow | Single (example, prediction, score) row from an evaluation run |
| ExampleField | A single (key, value) entry stored inside an Example |
| FinalOutput | Sentinel produced by CodeInterpreter to indicate program termination |
| LMCacheConfig | DSPy memoization cache controls |
| LMConfig | Common generation controls for an LM request (``dspy |
| LMHistoryEntry | A single LM call recorded in the per-LM / per-module history |
| LMMessage | Role-attributed sequence of LM parts (``dspy |
| LMOutput | One generated candidate inside an LMResponse |
| LMPart | Abstract base for a single content item carried by an LM message or output |
| LMCitationPart | Citation returned by a model |
| LMDocumentPart | Semantic source/document content, optionally citation-enabled |
| LMRefusalPart | Model refusal part |
| LMSourcePart | LM part whose content comes from exactly one of data, url, file_id, or path |
| LMAudioPart | Audio content part |
| LMBinaryPart | Opaque binary content part |
| LMImagePart | Image content part |
| LMVideoPart | Video content part |
| LMTextPart | Plain text part of an LM message or output |
| LMThinkingPart | Reasoning / thinking trace returned by a model |
| LMToolCallPart | Model-issued request to call a tool (LMToolCallPart) |
| LMToolResultPart | Tool execution result returned to a model (LMToolResultPart) |
| LMPromptCacheConfig | Provider-side prompt/token cache controls (call still happens; backend may re... |
| LMReasoningConfig | Reasoning controls for models with native reasoning support |
| LMRequest | Normalized request handed to a BaseLM (``dspy |
| LMResponse | Normalized result of one LM request (``dspy |
| LMToolChoice | Tool-choice controls for native tool-capable models |
| LMToolSpec | Provider-independent tool schema attached to an LMRequest |
| LMUsage | Token and timing usage for one LM request (``dspy |
| NamedThing | Abstract base for any identifiable DSPy artefact |
| Adapter | Base class for prompt-format adapters (``dspy |
| BAMLAdapter | BAML schema-language adapter (``dspy |
| ChatAdapter | Markdown-formatted chat adapter (``dspy |
| JSONAdapter | Structured-JSON adapter (``dspy |
| TwoStepAdapter | Two-step plan + finalize adapter (``dspy |
| XMLAdapter | XML output adapter (``dspy |
| BaseLM | Abstract base class for DSPy language models (``dspy |
| LM | Concrete LiteLLM-backed language model (``dspy |
| Cache | DSPy cache configuration (``dspy |
| Completions | Container of candidate completions associated with a Prediction (``dspy |
| DataLoader | Pluggable loader that materializes HuggingFace / pandas data into Examples (`... |
| Dataset | Base dataset container (``dspy |
| AlfWorld | AlfWorld text-game agent dataset (``dspy |
| Colors | Synthetic color-name dataset (``dspy |
| GSM8K | GSM8K grade-school math word problems (``dspy |
| HotPotQA | HotPotQA multi-hop QA dataset (``dspy |
| MATH | Competition mathematics dataset (``dspy |
| DSPyError | Root of the public DSPy exception hierarchy (``dspy |
| AdapterParseError | Raised when an Adapter fails to parse an LM response (``dspy |
| LMError | Abstract base for LM-related errors (``dspy |
| LMConfigurationError | Misconfigured LM |
| LMNotConfiguredError | Raised when no LM is configured |
| LMProviderError | Provider-side LM error |
| LMAuthError | LM authentication error |
| LMBillingError | LM billing / quota error |
| LMInvalidRequestError | LM rejected the request |
| ContextWindowExceededError | Context window exceeded |
| LMUnsupportedModelError | Model is not supported |
| LMRateLimitError | LM rate-limit error |
| LMServerError | Server-side LM error |
| LMTimeoutError | Request timed out |
| LMTransportError | Transport-level LM error |
| LMUnexpectedError | Unexpected / unclassified LM error |
| LMUnsupportedFeatureError | Feature not supported by the underlying LM |
| Embedder | Text embedding model (``dspy |
| Evaluate | Parallel program evaluator (``dspy |
| Example | Flexible data container for DSPy examples (trainset rows) |
| Prediction | Output of a DSPy module |
| EvaluationResult | Aggregate evaluation result (``dspy |
| Interpreter | Abstract code interpreter used by ProgramOfThought and CodeAct |
| CodeInterpreter | Sandboxed code interpreter (``dspy |
| PythonInterpreter | Local in-process Python REPL (``dspy |
| Metric | A scoring function used by Evaluate or teleprompters |
| Module | Base class for DSPy programs (``dspy |
| Aggregator | Aggregation helper (``dspy |
| BestOfN | Sample N candidates and select the highest-rewarded (``dspy |
| KNN | K-nearest-neighbor demo selector (``dspy |
| Parallel | Run modules in parallel across batched inputs (``dspy |
| Predictor | Module that wraps a Signature + LM and produces a Prediction |
| CodeAct | Code-acting agent (``dspy |
| MultiChainComparison | Generates N chains and selects the best (``dspy |
| Predict | Basic input-to-output predictor (``dspy |
| ChainOfThought | Predictor that injects a free-form rationale field (``dspy |
| ProgramOfThought | Tool-using predictor that emits and executes Python code (``dspy |
| ReAct | Reasoning + Acting agent with tool use (``dspy |
| ReActV2 | Next-generation ReAct agent (``dspy |
| Refine | Iterative refinement loop (``dspy |
| Retriever | Abstract retrieval module |
| ColBERTv2 | Remote ColBERTv2 retrieval server (``dspy |
| Embeddings | Embedding-based nearest-neighbour retriever (``dspy |
| EmbeddingsWithScores | Embeddings retriever that also returns similarity scores (``dspy |
| Retrieve | Generic retrieve module that calls ``dspy |
| RLM | Reinforcement-learning model wrapper (``dspy |
| Provider | Backend provider abstraction (``dspy |
| DatabricksProvider | Databricks Foundation Models provider (``dspy |
| LocalProvider | Local-server provider used for ``dspy |
| OpenAIProvider | OpenAI fine-tuning provider (``dspy |
| ReinforceJob | Reinforcement-learning fine-tuning job (``dspy |
| Settings | Global DSPy configuration singleton (``dspy |
| Signature | Declarative input/output contract for a DSPy predictor (``dspy |
| StreamListener | Per-field listener that turns provider chunks into StreamResponse events ... |
| Teleprompter | Base class for DSPy optimizers (``dspy |
| AvatarOptimizer | Optimizer specialized for Avatar agents (``dspy |
| BetterTogether | Compose prompt + weight optimization (``dspy |
| BootstrapFewShot | Bootstraps demos by running the teacher program (``dspy |
| BootstrapFewShotWithOptuna | BootstrapFewShot driven by an Optuna hyperparameter search (``dspy |
| BootstrapFewShotWithRandomSearch | BootstrapFewShot + random search over program variants (``dspy |
| InferRules | Optimizer that infers natural-language rules from training data (``dspy |
| KNNFewShot | KNN-selected few-shot optimizer (``dspy |
| BootstrapFinetune | Bootstrap demos then fine-tune the underlying LM (``dspy |
| COPRO | Coordinate-prompt optimizer (``dspy |
| Ensemble | Ensembles multiple compiled programs (``dspy |
| GEPA | Genetic-evolutionary Prompt Adaptation optimizer (``dspy |
| LabeledFewShot | Trivial optimizer that injects labelled few-shot demos (``dspy |
| MIPROv2 | Multi-prompt instruction-program optimizer v2 (``dspy |
| SIMBA | Stochastic Introspective Mini-Batch Ascent optimizer (``dspy |
| Tool | A function-call tool usable by an LM (``dspy |
| ToolCall | A model request to invoke a tool (``dspy |
| ToolCallResults | Container for tool-call execution results (``dspy |
| ToolCalls | Container for the set of tool calls returned by the model (``dspy |
| ToolResult | A tool execution result returned to the model (``dspy |
| TrainingJob | Asynchronous fine-tuning job (``dspy |
| Type | Abstract DSPy custom type (``dspy |
| Audio | Audio content (``dspy |
| Citation | A single citation entry (``dspy |
| Code | Code content typed by programming language (``dspy |
| Document | Citation-enabled document content (``dspy |
| File | Arbitrary file payload (``dspy |
| History | Conversation history (``dspy |
| Image | Image content usable as an input/output field type (``dspy |
| Reasoning | Native model reasoning content surfaced to the user (``dspy |
| SignatureField | A single typed field belonging to a ``dspy |
| StreamEvent | Abstract event produced by ``dspy |
| StatusMessage | Status update emitted while a module runs (``dspy |
| StreamResponse | Streaming text chunk for a specific predictor field (``dspy |
Slots
| Slot | Description |
|---|---|
| adapter | Prompt-format adapter bound to this predictor / settings |
| adapter_kind | Concrete adapter implementation (matches an AdapterKind value) |
| aggregator_name | Aggregator function name (e |
| allow_tool_async_sync_conversion | |
| allowed | Tool names a model is allowed to call |
| arg_desc | Dict from arg name to argument description |
| arg_types | Dict from arg name to Python type name |
| args | JSON-schema dict describing tool argument shapes |
| async_max_workers | |
| auto | MIPROv2 auto mode (light / medium / heavy) |
| batch_size | |
| breadth | |
| bsize | |
| cache | Whether responses for this LM should be cached |
| cache_config | |
| cache_hit | Whether this response was served from DSPy's cache |
| cache_key | Prompt cache key |
| cache_read_tokens | |
| cache_write_tokens | |
| caching | |
| call_id | Provider-issued tool-call id |
| callbacks | Dotted import paths of callbacks registered on the module |
| candidates | Per-candidate field assignments |
| checkpoints | Map from checkpoint name to artifact location |
| chunk | Partial output text emitted by streaming |
| citation_index | |
| citations | Citations returned by the model |
| code | Source code payload |
| code_value | Provider error code |
| compiled | Whether the module has been compiled by a teleprompter |
| completion_tokens | |
| completions | Optional list of alternate completion candidates |
| config | Default keyword arguments forwarded to the underlying LM |
| constraints | Pydantic constraints translated to human-readable text |
| content_parts | Heterogeneous content parts attached to the tool result |
| context | Additional context attached to a document |
| corpus | In-memory document corpus |
| cost | Estimated USD cost for the request (when computable) |
| current_model | |
| data | Base64-encoded inline payload |
| default | Default value expressed as JSON |
| default_kwargs | |
| demos | Few-shot demonstrations attached to a predictor |
| depth | |
| desc | Field description as passed to ``InputField(desc= |
| description | Free-form description |
| detail | Image detail level (low / high / auto) |
| devset | Dev / evaluation split |
| disable_history | |
| disk_cache_dir | |
| disk_size_limit_bytes | |
| display_progress | |
| display_table | 0 to hide, N>0 to show the first N rows |
| effort | |
| embedder | |
| embedding_model | Embedding model identifier (LiteLLM name or callable path) |
| enable_disk_cache | |
| enable_env_vars | |
| enable_memory_cache | |
| enable_network_access | |
| enable_read_paths | |
| enable_write_paths | |
| enabled | |
| example | |
| extensions | Provider-specific extra request kwargs |
| extraction_model | |
| failure_score | |
| field_kind | Whether this Signature field is an input or output |
| field_name | Field name |
| fields | Named scalar fields carried by an Example / Prediction |
| file_id | Provider-side file identifier for an uploaded asset |
| filename | |
| finetunable | |
| finetuning_model | |
| finish_reason | Why the model stopped generating this candidate |
| fn_path | Dotted import path of the metric callable |
| forward_contract | |
| func | Dotted import path of the Python callable wrapped by a Tool |
| has_kwargs | Whether the tool accepts arbitrary **kwargs |
| higher_is_better | |
| history | Per-module call history of LM requests / responses |
| history_messages | Untyped chat-history messages used by ``dspy |
| http_status | |
| id | Stable opaque identifier for an instance |
| index_path | |
| init_temperature | |
| input_audio_tokens | |
| input_fields | Ordered list of input fields on a Signature |
| input_keys | Subset of fields flagged as inputs via ``with_inputs( |
| input_tokens | |
| instructions | Free-form instructions string carried on a Signature (its __doc__) |
| interpreter_kind | Concrete code interpreter implementation (matches an InterpreterKind valu... |
| is_error | Whether a tool result represents an error |
| is_input | Whether this field is part of the example's input subset |
| is_last_chunk | |
| job_id | |
| k | Top-k retrieval depth |
| k_nearest | |
| keep_details | |
| key | Field name |
| language | Language tag (programming language or BCP-47) |
| last_checkpoint | |
| launch_kwargs | |
| lm | Language model bound to this predictor / program |
| lm_response | Raw LM response text associated with a parse error |
| lm_usage | Token usage attributed to the prediction |
| log_dir | |
| logprobs | Token log-probability payload as returned by the provider |
| logprobs_flag | Whether to return token log-probabilities |
| max_bootstrapped_demos | |
| max_errors | |
| max_history_size | |
| max_iters | Maximum number of reasoning / tool-call iterations (ReAct family) |
| max_labeled_demos | |
| max_retries | Maximum retry attempts (Refine, retry decorator) |
| max_rounds | |
| max_tokens | |
| max_trace_size | |
| memory_max_entries | |
| message | Human-readable error message |
| messages | Ordered list of LM messages |
| metadata | Opaque key/value metadata passed alongside an object |
| metric | Dotted import path of the metric callable (or its name) |
| metric_threshold | |
| mimetype | IANA media type for the payload |
| mode | |
| model | LiteLLM-style provider/model identifier |
| model_type | Which LiteLLM API contract to use (chat / text / responses) |
| module_under_test | Wrapped module |
| n | Number of candidate generations (BestOfN, MultiChainComparison |
| n_outputs | Number of LM completions to request (n field on LMConfig) |
| name | Short human-readable name |
| native_response_types | Output field types handled by native LM features rather than adapter parsing |
| num_candidate_programs | |
| num_candidates | Number of candidate prompts / programs to evaluate per trial |
| num_iters | |
| num_retries | |
| num_rules | |
| num_threads | |
| num_trials | |
| only_hard_examples | |
| output_audio_tokens | |
| output_fields | Ordered list of output fields on a Signature |
| output_tokens | |
| outputs | One or more generated candidates returned by the LM |
| parallel | Whether parallel tool calls are permitted |
| parallel_tool_calls | |
| parameters | JSON-schema parameter spec for a tool |
| part_type | Discriminator for the LMPart subclass |
| parts | Ordered content parts of an LM message or output |
| passages | |
| path | Local filesystem path to a payload |
| pending_batch_ids | |
| predict_name | Name of the originating predictor |
| prediction | |
| predictors | Predictor children of a composite Module (named_predictors()) |
| prompt_cache_config | |
| prompt_model | |
| prompt_tokens | |
| provide_traceback | |
| provider | |
| provider_data | Provider-specific raw payload preserved with a normalized object |
| provider_name | Short name of the provider (openai, anthropic, databricks |
| python_type | Python type annotation as a string (e |
| rationale_type | Custom rationale type name used by ChainOfThought |
| reasoning_config | |
| reasoning_tokens | |
| redacted | Whether the content has been redacted |
| reduce_fn | Dotted import path of the reduction function |
| reinforceable | |
| request | |
| response | |
| response_format | |
| response_id | Provider-issued response id (when available) |
| restrict_pickle | |
| result_name | Name of the tool whose result is reported |
| results | Per-example evaluation rows aggregated into an EvaluationResult |
| retryable | |
| reward_fn | Dotted import path of a reward function (Refine, BestOfN) |
| rm | Globally configured retrieval module |
| role | Conversational role of a message |
| rollout_id | Rollout id used to differentiate cache entries |
| safe_types | Dotted import paths of additional safe pickle types |
| save_as_csv | |
| save_as_json | |
| score | Numeric score attached to a Prediction (used for arithmetic / comparison) |
| scores | |
| server_url | |
| signature | Signature attached to a predictor |
| signature_field_name | |
| signature_name | |
| size | Number of programs to ensemble |
| source | Document source payload |
| spec_type | Schema kind |
| splits | Dataset split sizes / metadata |
| stage | Random per-predictor stage id used to bucket traces |
| status | |
| stop | Stop sequences |
| strategy | Strategy string (e |
| stream_event_kind | Kind of stream event (matches a StreamEventKind value) |
| sub_modules | Nested Module children of a composite Module |
| subset | MATH subset name (algebra, geometry, |
| summary | |
| sync_files | |
| task_model | |
| teacher_settings | |
| temperature | |
| testset | Held-out test split |
| text | Plain-text payload |
| timestamp | |
| title | Human-readable title or display name |
| tool_call_results | Results returned for previously issued tool calls |
| tool_calls | Tool calls produced by the model |
| tool_choice | |
| tool_specs | Provider-independent tool schemas attached to an LMRequest |
| tools | Tools available to an agent |
| top_p | |
| total_tokens | |
| traces | Bootstrapped traces gathered by teleprompters |
| track_stats | |
| track_usage | |
| train | Training examples attached to a predictor (used by some optimizers) |
| train_data | Training examples in provider-acceptable shape |
| train_data_format | |
| train_kwargs | |
| training_status | |
| trainset | Training split used by an optimizer |
| truncated | Whether the model output was truncated |
| unofficial_dev | |
| url | URL pointing at a remote payload |
| usage | Token and timing usage for the request |
| use_developer_role | |
| use_native_function_calling | |
| valset | Validation split used by an optimizer |
| value | JSON-serialized value |
| warn_on_type_mismatch |
Enumerations
| Enumeration | Description |
|---|---|
| AdapterKind | Adapter implementation used to format prompts / parse responses |
| FieldKind | Whether a Signature field is consumed as input or produced as output |
| FinishReason | Reason the model stopped generating (mirrors provider conventions) |
| ForwardContract | Which forward contract a BaseLM subclass implements |
| InterpreterKind | Concrete code interpreter implementation |
| LMPartType | Discriminator value used by LMPart subclasses |
| LMRole | Role of an LM message (used by both legacy chat dicts and LMMessage) |
| ModelType | LiteLLM model contract selector understood by ``dspy |
| ReasoningEffort | Reasoning effort hint for models with native reasoning support |
| StreamEventKind | Kinds of payloads yielded by ``dspy |
| ToolChoiceMode | Provider tool-choice mode used by LMToolChoice |
| TrainDataFormat | Mirrors ``dspy |
| TrainingStatus | Mirrors ``dspy |
Types
| Type | Description |
|---|---|
| Boolean | A binary (true or false) value |
| Curie | a compact URI |
| Date | a date (year, month and day) in an idealized calendar |
| DateOrDatetime | Either a date or a datetime |
| Datetime | The combination of a date and time |
| Decimal | A real number with arbitrary precision that conforms to the xsd:decimal speci... |
| Double | A real number that conforms to the xsd:double specification |
| Float | A real number that conforms to the xsd:float specification |
| Identifier | Opaque string identifier used by DSPy primitives (tool call ids, response ids... |
| Integer | An integer |
| Jsonpath | A string encoding a JSON Path |
| Jsonpointer | A string encoding a JSON Pointer |
| MimeType | IANA media type for a part (e |
| ModelName | LiteLLM-style provider/model string (e |
| Ncname | Prefix part of CURIE |
| Nodeidentifier | A URI, CURIE or BNODE that represents a node in a model |
| Objectidentifier | A URI or CURIE that represents an object in the model |
| Sparqlpath | A string encoding a SPARQL Property Path |
| String | A character string |
| Time | A time object represents a (local) time of day, independent of any particular... |
| Uri | a complete URI |
| Uriorcurie | a URI or a CURIE |
Subsets
| Subset | Description |
|---|---|
| Adapters | Prompt-format adapters (chat, json, xml, baml, two-step) |
| Clients | Language model clients, providers, embedders, and caches |
| Core | Foundational DSPy primitives (Example, Signature, Module) |
| CustomTypes | Rich content types usable in signatures (Image, Audio, Code, Tool |
| Datasets | Built-in datasets and data loaders |
| Errors | Public exception hierarchy |
| Evaluation | Evaluation, metrics, and result containers |
| Finetune | Fine-tuning job and data-format abstractions |
| LmContract | Typed LM request/response contract (LMRequest, LMMessage, LM parts) |
| Modules | Composable program modules and predictors |
| Retrievers | Retrieval modules and similarity backends |
| Settings | Global runtime configuration |
| Streaming | Streaming primitives and status messages |
| Teleprompt | Optimizers (a |
| Tooling | Tool / function-call abstractions for agents |