Skip to content

dspy.ChatAdapter

dspy.ChatAdapter(callbacks=None)

Bases: Adapter

Source code in dspy/adapters/base.py
def __init__(self, callbacks=None):
    self.callbacks = callbacks or []

Functions

format(signature: Signature, demos: list[dict[str, Any]], inputs: dict[str, Any]) -> list[dict[str, Any]]

Source code in dspy/adapters/chat_adapter.py
def format(self, signature: Signature, demos: list[dict[str, Any]], inputs: dict[str, Any]) -> list[dict[str, Any]]:
    messages: list[dict[str, Any]] = []

    # Extract demos where some of the output_fields are not filled in.
    incomplete_demos = [
        demo for demo in demos if not all(k in demo and demo[k] is not None for k in signature.fields)
    ]
    complete_demos = [demo for demo in demos if demo not in incomplete_demos]
    # Filter out demos that don't have at least one input and one output field.
    incomplete_demos = [
        demo
        for demo in incomplete_demos
        if any(k in demo for k in signature.input_fields) and any(k in demo for k in signature.output_fields)
    ]

    demos = incomplete_demos + complete_demos

    prepared_instructions = prepare_instructions(signature)
    messages.append({"role": "system", "content": prepared_instructions})

    for demo in demos:
        messages.append(format_turn(signature, demo, role="user", incomplete=demo in incomplete_demos))
        messages.append(format_turn(signature, demo, role="assistant", incomplete=demo in incomplete_demos))

    messages.append(format_turn(signature, inputs, role="user"))
    return messages

format_fields(signature, values, role)

Source code in dspy/adapters/chat_adapter.py
def format_fields(self, signature, values, role):
    fields_with_values = {
        FieldInfoWithName(name=field_name, info=field_info): values.get(
            field_name, "Not supplied for this particular example."
        )
        for field_name, field_info in signature.fields.items()
        if field_name in values
    }

    return format_fields(fields_with_values)

format_finetune_data(signature, demos, inputs, outputs)

Source code in dspy/adapters/chat_adapter.py
def format_finetune_data(self, signature, demos, inputs, outputs):
    # Get system + user messages
    messages = self.format(signature, demos, inputs)

    # Add the assistant message
    role = "assistant"
    incomplete = False
    assistant_message = format_turn(signature, outputs, role, incomplete)
    messages.append(assistant_message)

    # Wrap the messages in a dictionary with a "messages" key
    return dict(messages=messages)

format_turn(signature, values, role, incomplete=False)

Source code in dspy/adapters/chat_adapter.py
def format_turn(self, signature, values, role, incomplete=False):
    return format_turn(signature, values, role, incomplete)

parse(signature, completion)

Source code in dspy/adapters/chat_adapter.py
def parse(self, signature, completion):
    sections = [(None, [])]

    for line in completion.splitlines():
        match = field_header_pattern.match(line.strip())
        if match:
            sections.append((match.group(1), []))
        else:
            sections[-1][1].append(line)

    sections = [(k, "\n".join(v).strip()) for k, v in sections]

    fields = {}
    for k, v in sections:
        if (k not in fields) and (k in signature.output_fields):
            try:
                fields[k] = parse_value(v, signature.output_fields[k].annotation)
            except Exception as e:
                raise ValueError(
                    f"Error parsing field {k}: {e}.\n\n\t\tOn attempting to parse the value\n```\n{v}\n```"
                )

    if fields.keys() != signature.output_fields.keys():
        raise ValueError(f"Expected {signature.output_fields.keys()} but got {fields.keys()}")

    return fields