Function Signature
Description
Create a language model instance from configuration using the factory pattern. This function handles provider resolution, API key management from environment variables, and optional schema constraint application for structured output.Parameters
Model configuration object specifying the model ID, optional provider, and provider-specific keyword arguments. See ModelConfig for details.
Optional examples for schema generation when
use_schema_constraints=True. These examples are used to infer the output structure that the model should follow.Whether to apply schema constraints from examples. When True, the model will be configured to produce structured output matching the example format.
Explicit fence output preference. If None, automatically computed based on the schema requirements. Fencing wraps output in markdown code blocks for parsing.
If True, returns a tuple of (model, fence_output_value) instead of just the model. Useful for determining whether output will be fenced.
Returns
An instantiated language model provider ready for inference. The specific type depends on the provider (e.g., GeminiModel, OpenAIModel).
When
return_fence_output=True, returns a tuple containing:- The instantiated model
- Boolean indicating whether the model requires fenced output
Exceptions
- ValueError: If neither
model_idnorprovideris specified in the config. - ValueError: If no provider is registered for the given
model_id. - InferenceConfigError: If provider instantiation fails due to invalid configuration or missing dependencies.
Usage Examples
Basic Model Creation
With Provider-Specific Arguments
With Schema Constraints
Explicit Provider Selection
With Fence Output Control
Using Environment Variables
Environment Variables
The function automatically resolves API keys and configuration from environment variables:- GEMINI_API_KEY or LANGEXTRACT_API_KEY: For Gemini models
- OPENAI_API_KEY or LANGEXTRACT_API_KEY: For GPT models
- OLLAMA_BASE_URL: For Ollama models (defaults to
http://localhost:11434)
GEMINI_API_KEY and LANGEXTRACT_API_KEY), the more specific key takes precedence and a warning is issued.
Notes
- The factory loads built-in and plugin providers automatically.
- Provider resolution is based on model ID patterns (e.g., “gemini” in the model ID routes to GeminiProvider).
- Schema constraints enable structured output extraction with type validation.
- Vertex AI authentication can be used by setting
vertexai=Trueinprovider_kwargs.