dspy.Code¶
dspy.Code
¶
Bases: Type
Code type in DSPy.
This type is useful for code generation and code analysis.
Example 1: dspy.Code as output type in code generation:
import dspy
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
class CodeGeneration(dspy.Signature):
'''Generate python code to answer the question.'''
question: str = dspy.InputField(description="The question to answer")
code: dspy.Code["java"] = dspy.OutputField(description="The code to execute")
predict = dspy.Predict(CodeGeneration)
result = predict(question="Given an array, find if any of the two numbers sum up to 10")
print(result.code)
Example 2: dspy.Code as input type in code analysis:
import dspy
import inspect
dspy.configure(lm=dspy.LM("openai/gpt-4o-mini"))
class CodeAnalysis(dspy.Signature):
'''Analyze the time complexity of the function.'''
code: dspy.Code["python"] = dspy.InputField(description="The function to analyze")
result: str = dspy.OutputField(description="The time complexity of the function")
predict = dspy.Predict(CodeAnalysis)
def sleepsort(x):
import time
for i in x:
time.sleep(i)
print(i)
result = predict(code=inspect.getsource(sleepsort))
print(result.result)
Functions¶
description() -> str
classmethod
¶
Source code in dspy/adapters/types/code.py
extract_custom_type_from_annotation(annotation)
classmethod
¶
Extract all custom types from the annotation.
This is used to extract all custom types from the annotation of a field, while the annotation can
have arbitrary level of nesting. For example, we detect Tool
is in list[dict[str, Tool]]
.
Source code in dspy/adapters/types/base_type.py
serialize_model()
¶
validate_input(data: Any)
classmethod
¶
Source code in dspy/adapters/types/code.py
:::