Skip to content

Support more ast types in Signature typed parsing #1899

@thomasahle

Description

@thomasahle

On the website, you see this example:

import dspy
dspy.configure(lm=dspy.LM('gpt-4o-mini-2024-07-18'))

# Define the DSPy module for classification. It will use the hint at training time, if available.
signature = dspy.Signature("text -> label").with_updated_fields('label', type_=Literal[tuple(CLASSES)])
classify = dspy.ChainOfThoughtWithHint(signature)

# Optimize via BootstrapFinetune.
optimizer = dspy.BootstrapFinetune(metric=(lambda x, y, trace=None: x.label == y.label), num_threads=24)
optimized = optimizer.compile(classify, trainset=trainset)

optimized_classifier(text="What does a pending cash withdrawal mean?")

This would have been a lot cleaner as

signature = dspy.Signature(f"text -> label:Literal{CLASSES}")

We already has support for most of this.
If you see

def _parse_type_node(node, names=None) -> Any:
you just have to add a case for ast.Constant, like this:

    if isinstance(node, ast.Constant):
        return node.value

Then you get

In[1]: dspy.Signature(f"text -> label:Literal[1,2]")
Out[1]:
StringSignature(text -> label
    instructions='Given the fields `text`, produce the fields `label`.'
    text = Field(annotation=str required=True json_schema_extra={'__dspy_field_type': 'input', 'prefix': 'Text:', 'desc': '${text}'})
    label = Field(annotation=Literal[1, 2] required=True json_schema_extra={'__dspy_field_type': 'output', 'prefix': 'Label:', 'desc': '${label}'})
)

and

In[1]: CLASSES = ["good", "bad"]
In[2]: dspy.Signature(f"text -> label:Literal{CLASSES}")
Out[2]:
StringSignature(text -> label
    instructions='Given the fields `text`, produce the fields `label`.'
    text = Field(annotation=str required=True json_schema_extra={'__dspy_field_type': 'input', 'prefix': 'Text:', 'desc': '${text}'})
    label = Field(annotation=Literal['good', 'bad'] required=True json_schema_extra={'__dspy_field_type': 'output', 'prefix': 'Label:', 'desc': '${label}'})
)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions