Current section
Files
Jump to
Current section
Files
lib/snakebridge_generated/dspy/adapters/baml_adapter/baml_adapter.ex
# Generated by SnakeBridge v0.13.0 - DO NOT EDIT MANUALLY
# Regenerate with: mix compile
# Library: dspy 3.1.2
# Python module: dspy.adapters.baml_adapter
# Python class: BAMLAdapter
defmodule Dspy.Adapters.BAMLAdapter do
@moduledoc """
A DSPy adapter that improves the rendering of complex/nested Pydantic models to help LMs.
This adapter generates a compact, human-readable schema representation for nested Pydantic output
fields, inspired by the BAML project's JSON formatter (https://github.com/BoundaryML/baml).
The resulting rendered schema is more token-efficient and easier for smaller LMs to follow than a
raw JSON schema. It also includes Pydantic field descriptions as comments in the schema, which
provide valuable additional context for the LM to understand the expected output.
Example Usage:
```python
import dspy
from pydantic import BaseModel, Field
from typing import Literal
from baml_adapter import BAMLAdapter # Import from your module
# 1. Define your Pydantic models
class PatientAddress(BaseModel):
street: str
city: str
country: Literal["US", "CA"]
class PatientDetails(BaseModel):
name: str = Field(description="Full name of the patient.")
age: int
address: PatientAddress | None
# 2. Define a signature using the Pydantic model as an output field
class ExtractPatientInfo(dspy.Signature):
'''Extract patient information from the clinical note.'''
clinical_note: str = dspy.InputField()
patient_info: PatientDetails = dspy.OutputField()
# 3. Configure dspy to use the new adapter
llm = dspy.OpenAI(model="gpt-4.1-mini")
dspy.configure(lm=llm, adapter=BAMLAdapter())
# 4. Run your program
extractor = dspy.Predict(ExtractPatientInfo)
note = "John Doe, 45 years old, lives at 123 Main St, Anytown. Resident of the US."
result = extractor(clinical_note=note)
print(result.patient_info)
# Expected output:
# PatientDetails(name='John Doe', age=45, address=PatientAddress(street='123 Main St', city='Anytown', country='US'))
```
"""
def __snakebridge_python_name__, do: "dspy.adapters.baml_adapter"
def __snakebridge_python_class__, do: "BAMLAdapter"
def __snakebridge_library__, do: "dspy"
@opaque t :: SnakeBridge.Ref.t()
@doc """
Args:
callbacks: List of callback functions to execute during adapter methods.
use_native_function_calling: Whether to enable native function calling capabilities.
native_response_types: List of output field types handled by native LM features.
use_json_adapter_fallback: Whether to automatically fallback to JSONAdapter if the ChatAdapter fails.
If True, when an error occurs (except ContextWindowExceededError), the adapter will retry using
JSONAdapter. Defaults to True.
## Parameters
- `callbacks` (term() default: None)
- `use_native_function_calling` (boolean() default: True)
"""
@spec new(list(term()), keyword()) :: {:ok, SnakeBridge.Ref.t()} | {:error, Snakepit.Error.t()}
def new(args, opts \\ []) do
{args, opts} = SnakeBridge.Runtime.normalize_args_opts(args, opts)
SnakeBridge.Runtime.call_class(__MODULE__, :__init__, [] ++ List.wrap(args), opts)
end
@doc """
Custom adapter for improving structured outputs using the information from Pydantic models.
Based on the format used by BAML: https://github.com/BoundaryML/baml
## Parameters
- `processed_signature` (term())
- `original_signature` (term())
- `outputs` (list(term()))
- `lm` (term())
- `lm_kwargs` (%{optional(String.t()) => term()})
## Returns
- `list(%{optional(String.t()) => term()})`
"""
@spec _call_postprocess(
SnakeBridge.Ref.t(),
term(),
term(),
list(term()),
term(),
%{optional(String.t()) => term()},
keyword()
) :: {:ok, list(%{optional(String.t()) => term()})} | {:error, Snakepit.Error.t()}
def _call_postprocess(
ref,
processed_signature,
original_signature,
outputs,
lm,
lm_kwargs,
opts \\ []
) do
SnakeBridge.Runtime.call_method(
ref,
:_call_postprocess,
[processed_signature, original_signature, outputs, lm, lm_kwargs],
opts
)
end
@doc """
Custom adapter for improving structured outputs using the information from Pydantic models.
Based on the format used by BAML: https://github.com/BoundaryML/baml
## Parameters
- `lm` (term())
- `lm_kwargs` (%{optional(String.t()) => term()})
- `signature` (term())
- `inputs` (%{optional(String.t()) => term()})
## Returns
- `term()`
"""
@spec _call_preprocess(
SnakeBridge.Ref.t(),
term(),
%{optional(String.t()) => term()},
term(),
%{optional(String.t()) => term()},
keyword()
) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def _call_preprocess(ref, lm, lm_kwargs, signature, inputs, opts \\ []) do
SnakeBridge.Runtime.call_method(
ref,
:_call_preprocess,
[lm, lm_kwargs, signature, inputs],
opts
)
end
@doc """
Custom adapter for improving structured outputs using the information from Pydantic models.
Based on the format used by BAML: https://github.com/BoundaryML/baml
## Parameters
- `signature` (term())
## Returns
- `boolean()`
"""
@spec _get_history_field_name(SnakeBridge.Ref.t(), term(), keyword()) ::
{:ok, boolean()} | {:error, Snakepit.Error.t()}
def _get_history_field_name(ref, signature, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_get_history_field_name, [signature], opts)
end
@doc """
Custom adapter for improving structured outputs using the information from Pydantic models.
Based on the format used by BAML: https://github.com/BoundaryML/baml
## Parameters
- `signature` (term())
## Returns
- `boolean()`
"""
@spec _get_tool_call_input_field_name(SnakeBridge.Ref.t(), term(), keyword()) ::
{:ok, boolean()} | {:error, Snakepit.Error.t()}
def _get_tool_call_input_field_name(ref, signature, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_get_tool_call_input_field_name, [signature], opts)
end
@doc """
Custom adapter for improving structured outputs using the information from Pydantic models.
Based on the format used by BAML: https://github.com/BoundaryML/baml
## Parameters
- `signature` (term())
## Returns
- `boolean()`
"""
@spec _get_tool_call_output_field_name(SnakeBridge.Ref.t(), term(), keyword()) ::
{:ok, boolean()} | {:error, Snakepit.Error.t()}
def _get_tool_call_output_field_name(ref, signature, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :_get_tool_call_output_field_name, [signature], opts)
end
@doc """
Common call logic to be used for both sync and async calls.
## Parameters
- `lm` (term())
- `lm_kwargs` (term())
- `signature` (term())
- `demos` (term())
- `inputs` (term())
- `call_fn` (term())
## Returns
- `term()`
"""
@spec _json_adapter_call_common(
SnakeBridge.Ref.t(),
term(),
term(),
term(),
term(),
term(),
term(),
keyword()
) :: {:ok, term()} | {:error, Snakepit.Error.t()}
def _json_adapter_call_common(ref, lm, lm_kwargs, signature, demos, inputs, call_fn, opts \\ []) do
SnakeBridge.Runtime.call_method(
ref,
:_json_adapter_call_common,
[lm, lm_kwargs, signature, demos, inputs, call_fn],
opts
)
end
@doc """
Custom adapter for improving structured outputs using the information from Pydantic models.
Based on the format used by BAML: https://github.com/BoundaryML/baml
## Parameters
- `lm` (Dspy.Clients.LMClass.t())
- `lm_kwargs` (%{optional(String.t()) => term()})
- `signature` (term())
- `demos` (list(%{optional(String.t()) => term()}))
- `inputs` (%{optional(String.t()) => term()})
## Returns
- `list(%{optional(String.t()) => term()})`
"""
@spec acall(
SnakeBridge.Ref.t(),
Dspy.Clients.LMClass.t(),
%{optional(String.t()) => term()},
term(),
list(%{optional(String.t()) => term()}),
%{optional(String.t()) => term()},
keyword()
) :: {:ok, list(%{optional(String.t()) => term()})} | {:error, Snakepit.Error.t()}
def acall(ref, lm, lm_kwargs, signature, demos, inputs, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :acall, [lm, lm_kwargs, signature, demos, inputs], opts)
end
@doc """
Format the input messages for the LM call.
This method converts the DSPy structured input along with few-shot examples and conversation history into
multiturn messages as expected by the LM. For custom adapters, this method can be overridden to customize
the formatting of the input messages.
In general we recommend the messages to have the following structure:
```
[
{"role": "system", "content": system_message},
# Begin few-shot examples
{"role": "user", "content": few_shot_example_1_input},
{"role": "assistant", "content": few_shot_example_1_output},
{"role": "user", "content": few_shot_example_2_input},
{"role": "assistant", "content": few_shot_example_2_output},
...
# End few-shot examples
# Begin conversation history
{"role": "user", "content": conversation_history_1_input},
{"role": "assistant", "content": conversation_history_1_output},
{"role": "user", "content": conversation_history_2_input},
{"role": "assistant", "content": conversation_history_2_output},
...
# End conversation history
{"role": "user", "content": current_input},
]
And system message should contain the field description, field structure, and task description.
```
## Parameters
- `signature` - The DSPy signature for which to format the input messages.
- `demos` - A list of few-shot examples.
- `inputs` - The input arguments to the DSPy module.
## Returns
- `list(%{optional(String.t()) => term()})`
"""
@spec format(
SnakeBridge.Ref.t(),
term(),
list(%{optional(String.t()) => term()}),
%{optional(String.t()) => term()},
keyword()
) :: {:ok, list(%{optional(String.t()) => term()})} | {:error, Snakepit.Error.t()}
def format(ref, signature, demos, inputs, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :format, [signature, demos, inputs], opts)
end
@doc """
Format the assistant message content.
This method formats the assistant message content, which can be used in formatting few-shot examples,
conversation history.
## Parameters
- `signature` - The DSPy signature for which to format the assistant message content.
- `outputs` - The output fields to be formatted.
- `missing_field_message` - A message to be used when a field is missing.
## Returns
- `String.t()`
"""
@spec format_assistant_message_content(
SnakeBridge.Ref.t(),
term(),
%{optional(String.t()) => term()},
list(term()),
keyword()
) :: {:ok, String.t()} | {:error, Snakepit.Error.t()}
def format_assistant_message_content(ref, signature, outputs, args, opts \\ []) do
{args, opts} = SnakeBridge.Runtime.normalize_args_opts(args, opts)
SnakeBridge.Runtime.call_method(
ref,
:format_assistant_message_content,
[signature, outputs] ++ List.wrap(args),
opts
)
end
@doc """
Format the conversation history.
This method formats the conversation history and the current input as multiturn messages.
## Parameters
- `signature` - The DSPy signature for which to format the conversation history.
- `history_field_name` - The name of the history field in the signature.
- `inputs` - The input arguments to the DSPy module.
## Returns
- `list(%{optional(String.t()) => term()})`
"""
@spec format_conversation_history(
SnakeBridge.Ref.t(),
term(),
String.t(),
%{optional(String.t()) => term()},
keyword()
) :: {:ok, list(%{optional(String.t()) => term()})} | {:error, Snakepit.Error.t()}
def format_conversation_history(ref, signature, history_field_name, inputs, opts \\ []) do
SnakeBridge.Runtime.call_method(
ref,
:format_conversation_history,
[signature, history_field_name, inputs],
opts
)
end
@doc """
Format the few-shot examples.
This method formats the few-shot examples as multiturn messages.
## Parameters
- `signature` - The DSPy signature for which to format the few-shot examples.
- `demos` - A list of few-shot examples, each element is a dictionary with keys of the input and output fields of the signature.
## Returns
- `list(%{optional(String.t()) => term()})`
"""
@spec format_demos(
SnakeBridge.Ref.t(),
term(),
list(%{optional(String.t()) => term()}),
keyword()
) :: {:ok, list(%{optional(String.t()) => term()})} | {:error, Snakepit.Error.t()}
def format_demos(ref, signature, demos, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :format_demos, [signature, demos], opts)
end
@doc """
Format the field description for the system message.
This method formats the field description for the system message. It should return a string that contains
the field description for the input fields and the output fields.
## Parameters
- `signature` - The DSPy signature for which to format the field description.
## Returns
- `String.t()`
"""
@spec format_field_description(SnakeBridge.Ref.t(), term(), keyword()) ::
{:ok, String.t()} | {:error, Snakepit.Error.t()}
def format_field_description(ref, signature, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :format_field_description, [signature], opts)
end
@doc """
Overrides the base method to generate a simplified schema for Pydantic models.
## Parameters
- `signature` (term())
## Returns
- `String.t()`
"""
@spec format_field_structure(SnakeBridge.Ref.t(), term(), keyword()) ::
{:ok, String.t()} | {:error, Snakepit.Error.t()}
def format_field_structure(ref, signature, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :format_field_structure, [signature], opts)
end
@doc """
Formats the values of the specified fields according to the field's DSPy type (input or output),
annotation (e.g. str, int, etc.), and the type of the value itself. Joins the formatted values
into a single string, which is a multiline string if there are multiple fields.
## Parameters
- `fields_with_values` - A dictionary mapping information about a field to its corresponding value.
## Returns
- `String.t()`
"""
@spec format_field_with_value(
SnakeBridge.Ref.t(),
%{optional(Dspy.Adapters.ChatAdapter.FieldInfoWithName.t()) => term()},
list(term()),
keyword()
) :: {:ok, String.t()} | {:error, Snakepit.Error.t()}
def format_field_with_value(ref, fields_with_values, args, opts \\ []) do
{args, opts} = SnakeBridge.Runtime.normalize_args_opts(args, opts)
SnakeBridge.Runtime.call_method(
ref,
:format_field_with_value,
[fields_with_values] ++ List.wrap(args),
opts
)
end
@doc """
Format the call data into finetuning data according to the OpenAI API specifications.
For the chat adapter, this means formatting the data as a list of messages, where each message is a dictionary
with a "role" and "content" key. The role can be "system", "user", or "assistant". Then, the messages are
wrapped in a dictionary with a "messages" key.
## Parameters
- `signature` (term())
- `demos` (list(%{optional(String.t()) => term()}))
- `inputs` (%{optional(String.t()) => term()})
- `outputs` (%{optional(String.t()) => term()})
## Returns
- `%{optional(String.t()) => list(term())}`
"""
@spec format_finetune_data(
SnakeBridge.Ref.t(),
term(),
list(%{optional(String.t()) => term()}),
%{optional(String.t()) => term()},
%{optional(String.t()) => term()},
keyword()
) :: {:ok, %{optional(String.t()) => list(term())}} | {:error, Snakepit.Error.t()}
def format_finetune_data(ref, signature, demos, inputs, outputs, opts \\ []) do
SnakeBridge.Runtime.call_method(
ref,
:format_finetune_data,
[signature, demos, inputs, outputs],
opts
)
end
@doc """
Format the system message for the LM call.
## Parameters
- `signature` - The DSPy signature for which to format the system message.
## Returns
- `String.t()`
"""
@spec format_system_message(SnakeBridge.Ref.t(), term(), keyword()) ::
{:ok, String.t()} | {:error, Snakepit.Error.t()}
def format_system_message(ref, signature, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :format_system_message, [signature], opts)
end
@doc """
Format the task description for the system message.
This method formats the task description for the system message. In most cases this is just a thin wrapper
over `signature.instructions`.
## Parameters
- `signature` - The DSPy signature of the DSpy module.
## Returns
- `String.t()`
"""
@spec format_task_description(SnakeBridge.Ref.t(), term(), keyword()) ::
{:ok, String.t()} | {:error, Snakepit.Error.t()}
def format_task_description(ref, signature, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :format_task_description, [signature], opts)
end
@doc """
Overrides the base method to render Pydantic input instances as clean JSON.
## Parameters
- `signature` (term())
- `inputs` (%{optional(String.t()) => term()})
- `prefix` (String.t() default: '')
- `suffix` (String.t() default: '')
- `main_request` (boolean() default: False)
## Returns
- `String.t()`
"""
@spec format_user_message_content(
SnakeBridge.Ref.t(),
term(),
%{optional(String.t()) => term()},
list(term()),
keyword()
) :: {:ok, String.t()} | {:error, Snakepit.Error.t()}
def format_user_message_content(ref, signature, inputs, args, opts \\ []) do
{args, opts} = SnakeBridge.Runtime.normalize_args_opts(args, opts)
SnakeBridge.Runtime.call_method(
ref,
:format_user_message_content,
[signature, inputs] ++ List.wrap(args),
opts
)
end
@doc """
Custom adapter for improving structured outputs using the information from Pydantic models.
Based on the format used by BAML: https://github.com/BoundaryML/baml
## Parameters
- `signature` (term())
- `completion` (String.t())
## Returns
- `%{optional(String.t()) => term()}`
"""
@spec parse(SnakeBridge.Ref.t(), term(), String.t(), keyword()) ::
{:ok, %{optional(String.t()) => term()}} | {:error, Snakepit.Error.t()}
def parse(ref, signature, completion, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :parse, [signature, completion], opts)
end
@doc """
Returns a simplified format reminder for the language model.
In chat-based interactions, language models may lose track of the required output format
as the conversation context grows longer. This method generates a concise reminder of
the expected output structure that can be included in user messages.
## Parameters
- `signature` - The DSPy signature defining the expected input/output fields. (type: `Type[Signature]`)
## Returns
Returns `String.t()`. A simplified description of the required output format.
## Notes
This is a more lightweight version of `format_field_structure` specifically designed
for inline reminders within chat messages.
"""
@spec user_message_output_requirements(SnakeBridge.Ref.t(), term(), keyword()) ::
{:ok, String.t()} | {:error, Snakepit.Error.t()}
def user_message_output_requirements(ref, signature, opts \\ []) do
SnakeBridge.Runtime.call_method(ref, :user_message_output_requirements, [signature], opts)
end
end