Marvin 구조화 결과 — Task 결과 타입 지정
Marvin 구조화 결과
marvin.run()은 결과 타입을 지정하지 않으면 그냥 문자열을 돌려줘요. result_type 파라미터로 정확히 원하는 형태를 요구하면, Marvin이 그 타입으로 결과를 강제해 줍니다. 어떤 타입이 지원되는지 볼게요.
스칼라 타입
가장 단순한 형태는 Python 내장 스칼라 타입이에요.
import marvin
text = marvin.run("Write a haiku", result_type=str)
temperature = marvin.run("Convert 72°F to Celsius", result_type=float)
is_spam = marvin.run("Is this email spam?", result_type=bool, context={"email": "..."})
context 파라미터로 작업에 필요한 추가 데이터를 넣을 수 있어요.
리스트·집합·튜플
# Get a list of strings
keywords = marvin.run("Extract keywords from this text", result_type=list[str], context={"text": "..."})
# Get a list of numbers
prices = marvin.run("Extract all prices from this text", result_type=list[float], context={"text": "The shirt costs $19.99 and the pants are $49.99"})
집합(set)은 중복을 없애고, 튜플은 대부분의 LLM 프로바이더가 직접 지원하지 않으므로 Marvin이 결과를 튜플로 강제 변환하려 시도해요.
coordinates = marvin.run("Convert '40.7128° N, 74.0060° W' to decimal coordinates", result_type=tuple[float, float])
person_info = marvin.run("Extract name and age from: John is 25 years old", result_type=tuple[str, int])
구조화 타입
복잡한 구조는 각각 장단점이 있는 여러 방법이 있어요.
TypedDict — 고정 키를 가진 딕셔너리 타입:
import marvin
from typing import TypedDict
class MovieDict(TypedDict):
title: str
year: int
rating: float
movie = marvin.run("Describe the movie 'Inception'", result_type=MovieDict)
print(movie["title"]) # "Inception"
Dataclass, Pydantic 모델도 지원돼요. 분류 작업은 result_type로 list[str], bool, Enum, Literal 타입을 주어 구조화된 라벨을 받을 수 있어요. 여러 LLM 프로바이더에서 모두 잘 동작해요.