dspy.Example

dspy.Example

dspy.Example는 명명된 필드를 가진 유연한 데이터 컨테이너로, DSPy example과 학습 데이터에 사용됩니다.

출처: 문서

본문

dspy.Example(base=None, **kwargs)

명명된 필드를 가진 유연한 데이터 컨테이너로, DSPy example과 학습 데이터에 사용됩니다.

Example은 대략 HuggingFace 데이터셋이나 pandas DataFrame의 한 행(row)에 해당합니다. 딕셔너리나 점 접근 레코드(dot-access record)처럼 동작합니다. example["question"] 또는 example.question으로 필드를 읽을 수 있습니다.

DSPy에서 Example 객체의 리스트가 바로 trainset, devset, testset입니다. 대부분의 example은 키워드 인자나 기존 레코드로 만들어진 뒤 with_inputs(...)로 태그를 붙여 어떤 필드를 모듈에 입력으로 넣을지 표시합니다. 나머지 필드는 라벨 또는 메타데이터입니다.

평가 코드, 커스텀 옵티마이저, 학습 루프를 작성할 때는 모듈에 전달할 필드는 example.inputs(), 모듈 출력과 비교할 필드는 example.labels()를 사용하세요.

Examples

키워드 인자로 만들기:

>>> import dspy
>>> example = dspy.Example(
...     question="What is the capital of France?",
...     answer="Paris",
... ).with_inputs("question")
>>> example.question
'What is the capital of France?'
>>> example.answer
'Paris'
>>> example.inputs().toDict()
{'question': 'What is the capital of France?'}

기존 레코드에서 만들기:

>>> record = {"question": "What is 2+2?", "answer": "4"}
>>> example = dspy.Example(**record).with_inputs("question")
>>> example["question"]
'What is 2+2?'
>>> example.labels().answer
'4'

어느 필드가 입력인지 표시하기:

>>> example = dspy.Example(
...     question="What is the weather?",
...     answer="It's sunny",
... ).with_inputs("question")
>>> example.inputs().question
'What is the weather?'
>>> example.labels().answer
"It's sunny"

trainset에서 사용:

>>> trainset = [
...     dspy.Example(question="What is 2+2?", answer="4").with_inputs("question"),
...     dspy.Example(question="What is 3+3?", answer="6").with_inputs("question"),
... ]
>>> trainset[0].inputs().toDict()
{'question': 'What is 2+2?'}

metric에서 사용:

>>> def exact_match_metric(example, pred, trace=None):
...     return example.answer.lower() == pred.answer.lower()

Methods

copy(**kwargs)

얕은 복사를 반환하며, 선택적으로 필드를 재정의합니다. type(self)(base=self, **kwargs)를 반환합니다.

with_inputs(*keys)

어느 필드가 입력인지 태그로 표시합니다. keys는 입력으로 취급할 필드 이름입니다.

inputs()

입력으로 표시된 필드만 담은 Example을 반환합니다.

labels()

입력이 아닌(라벨/메타데이터) 필드만 담은 Example을 반환합니다.

toDict()

딕셔너리로 변환합니다.

get(key, default=None)

주어진 키의 값을 반환합니다. 없으면 기본값.

items(include_dspy=False) / keys(include_dspy=False) / values(include_dspy=False)

딕셔너리처럼 항목/키/값을 순회합니다. include_dspy=True면 내부 DSPy 메타데이터 키도 포함합니다.

without(*keys)

주어진 키를 뺀 복사본을 반환합니다.

더 알아보기 (Learn more)