dspy.ReActV2
dspy.ReActV2
ReActV2는 현재 dspy.ReAct 구현을 대체할 실험적인 네이티브 도구 인식(native-tool-aware) 버전입니다. DSPy 3.5에서 dspy.ReAct가 됩니다. dspy.ReActV2라는 이름은 3.5 릴리스 라인 전반에 걸쳐 deprecated 호환 별칭으로 남아 있다가 DSPy 3.6에서 제거될 예정입니다. ReActV2는 호출과 결과를 구조화된 dspy.History에 저장하고, 한 턴에 여러 도구 호출을 지원하며, 시그니처의 타입이 지정된 출력 필드를 내부 도구를 통해 제출(submit)합니다.
출처: 문서
본문
ReActV2의 이점, 설정, ReAct와의 차이점, 구현을 표준 dspy.ReAct API로 병합할 계획에 대해서는 ReAct and ReActV2 문서를 참고하세요.
dspy.ReActV2(signature: type[Signature], tools: list[Callable | Tool], max_iters: int = 20)
- Bases:
Module(callbacks=None)
시그니처를 완수하기 위해 추론과 도구 호출을 번갈아 수행하는 에이전트입니다. 모델은 도구를 선택하고 그 결과를 관찰한 뒤, 최종 출력으로 submit을 호출합니다. 네이티브 함수 호출(function calling)과 텍스트 기반 도구 호출을 모두 지원합니다. 예측(Prediction)에는 선언된 출력, 대화 기록, 종료 이유(termination reason)가 포함됩니다.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signature |
type[Signature] |
에이전트의 입력과 출력을 정의하는 시그니처. | required |
tools |
list[Callable | Tool] |
에이전트가 사용할 수 있는 함수, 호출 가능한 객체, 또는 dspy.Tool 인스턴스. |
required |
max_iters |
int |
최종 submit 시도 전 최대 도구 호출 턴 수. | 20 |
소스 코드는 dspy/predict/react_v2.py에 있습니다.
def __init__(self, signature: type[Signature], tools: list[Callable | Tool], max_iters: int = 20):
super().__init__()
self.signature = ensure_signature(signature)
self.max_iters = max_iters
reserved_outputs = _RESERVED_PREDICTION_KEYS.intersection(self.signature.output_fields)
if reserved_outputs:
names = ", ".join(f"`{name}`" for name in sorted(reserved_outputs))
raise ValueError(
f"Output field name(s) {names} are reserved by ReActV2 and attached to every "
"returned Prediction. Rename these output fields on your signature."
)
user_tools = [tool if isinstance(tool, Tool) else Tool(tool) for tool in tools]
self.tools = {tool.name: tool for tool in user_tools}
if "submit" in self.tools:
raise ValueError("`submit` is reserved by ReActV2 as the final-output tool.")
self.tools["submit"] = self._make_submit_tool()
self.react = dspy.Predict(self._make_react_signature())
Methods
def forward(self, **input_args):
max_iters = input_args.pop("max_iters", self.max_iters)
history = _coerce_history(input_args.pop("history", None))
pending_inputs = {name: input_args[name] for name in self.signature.input_fields if name in input_args}
break_reason = "max_iters"
for turn_index in range(max_iters):
try:
pred = self.react(
history=history,
tools=list(self.tools.values()),
**pending_inputs,
)
tool_calls = _coerce_tool_calls(getattr(pred, "tool_calls", None))
except (AdapterParseError, ValueError) as err:
logger.warning("Ending ReActV2 loop after parse failure: %s", format_error_for_lm(err, traceback_frames=5))
break_reason = "parse_error"
break
...
forward는 input_args에서 max_iters와 history를 꺼낸 뒤, 남은 입력 필드들을 pending_inputs로 모아 시그니처의 입력으로 사용합니다. 루프를 돌면서 self.react(내부 dspy.Predict)를 호출해 도구 호출을 얻고, 이를 구조화된 history와 tools에 맞춰 처리합니다. 파싱 실패(AdapterParseError·ValueError)가 나면 break_reason을 기록하고 루프를 종료합니다.
그 외 상속받은 메서드
ReActV2는 Module/BaseModule/Parameter에서 공통 메서드를 상속받습니다. 자세한 설명은 Predict 페이지를 참고하세요.
__call__(*args, **kwargs) -> Prediction— 모듈 호출.acall(*args, **kwargs) -> Prediction(async) — 비동기 호출.batch(...)—dspy.Example리스트를Parallel로 병렬 처리.deepcopy()/dump_state(json_mode=True)— 복사·상태 내보내기.get_lm()/set_lm(lm)— 언어 모델 조회·설정.inspect_history(n=1, file=None)— LM 호출 기록 표시.load(...)/load_state(...)— 상태 불러오기.map_named_predictors(func)— named predictor에 함수 적용.named_parameters()/named_predictors()/named_sub_modules()/parameters()/predictors()— 구조 탐색.reset_copy()— 복사 후 초기화.save(...)— 모듈 저장.