dspy.ReAct

dspy.ReAct

dspy.ReAct는 "Reasoning and Acting(추론과 행동)"을 뜻하는, 도구를 사용하는 에이전트를 만드는 인기 패러다임입니다. 이 방식에서 언어 모델은 도구 목록을 반복적으로 제공받으며 현재 상황에 대해 추론합니다. 모델은 추론 과정에 기반해 정보를 더 모으기 위해 도구를 호출할지, 아니면 작업을 마칠지를 결정합니다. DSPy 버전의 ReAct는 시그니처 폴리모피즘(signature polymorphism) 덕분에 어떤 시그니처에서든 동작하도록 일반화되어 있습니다.

출처: 문서

본문

dspy.ReAct(signature: type[Signature], tools: list[Callable], max_iters: int = 20)
  • Bases: Module(callbacks=None)

ReAct는 "Reasoning and Acting"을 뜻하며, 도구를 사용하는 에이전트를 만드는 인기 패러다임입니다. 이 방식에서 언어 모델은 도구 목록을 반복적으로 제공받으며 현재 상황에 대해 추론합니다. 모델은 추론 과정에 기반해 정보를 더 모으기 위해 도구를 호출할지, 아니면 작업을 마칠지를 결정합니다. DSPy 버전의 ReAct는 시그니처 폴리모피즘 덕분에 어떤 시그니처에서든 동작하도록 일반화되어 있습니다.

Parameters:

Name Type Description Default
signature type[Signature] 모듈의 시그니처. react 모듈의 입력과 출력을 정의합니다. required
tools list[Callable] 함수, 호출 가능한 객체, 또는 dspy.Tool 인스턴스의 리스트. required
max_iters Optional[int] 실행할 최대 반복 횟수. 기본값은 20. 20

Examples

def get_weather(city: str) -> str:
    return f"The weather in {city} is sunny."

react = dspy.ReAct(signature="question->answer", tools=[get_weather])
pred = react(question="What is the weather in Tokyo?")

소스 코드는 dspy/predict/react.py에 있습니다.

def __init__(self, signature: type["Signature"], tools: list[Callable], max_iters: int = 20):
    """
    ReAct stands for "Reasoning and Acting," a popular paradigm for building tool-using agents.
    In this approach, the language model is iteratively provided with a list of tools and has
    to reason about the current situation. The model decides whether to call a tool to gather more
    information or to finish the task based on its reasoning process. The DSPy version of ReAct is
    generalized to work over any signature, thanks to signature polymorphism.

    Args:
        signature: The signature of the module, which defines the input and output of the react module.
        tools (list[Callable]): A list of functions, callable objects, or `dspy.Tool` instances.
        max_iters (Optional[int]): The maximum number of iterations to run. Defaults to 20.

    Examples:

    ```python
    def get_weather(city: str) -> str:
        return f"The weather in {city} is sunny."

    react = dspy.ReAct(signature="question->answer", tools=[get_weather])
    pred = react(question="What is the weather in Tokyo?")
    ```
    """
    super().__init__()
    self.signature = signature = ensure_signature(signature)
    self.max_iters = max_iters

    tools = [t if isinstance(t, Tool) else Tool(t) for t in tools]
    tools = {tool.name: tool for tool in tools}
    ...

Methods

def forward(self, **input_args):
    trajectory = {}
    max_iters = input_args.pop("max_iters", self.max_iters)
    for idx in range(max_iters):
        try:
            pred = self._call_with_potential_trajectory_truncation(self.react, trajectory, **input_args)
        except ContextWindowExceededError as err:
            logger.warning(f"Ending the trajectory: {format_error_for_lm(err, traceback_frames=5)}")
            break
        except ValueError as err:
            logger.warning(f"Ending the trajectory: Agent failed to select a valid tool: {format_error_for_lm(err, traceback_frames=5)}")
            break

        trajectory[f"thought_{idx}"] = pred.next_thought
        trajectory[f"tool_name_{idx}"] = pred.next_tool_name
        trajectory[f"tool_args_{idx}"] = pred.next_tool_args
        ...
def truncate_trajectory(self, trajectory):
    """Truncates the trajectory so that it fits in the context window.

    Users can override this method to implement their own truncation logic.
    """
    keys = list(trajectory.keys())
    if len(keys) <= 4:
        # Every tool call has 4 keys: thought, tool_name, tool_args, and observation.
        raise ContextWindowExceededError(
            message="The trajectory is too long so your prompt exceeded the context window, but the trajectory "
            "cannot be truncated because it only has one tool call."
        )

    for key in keys[:4]:
        trajectory.pop(key)

    return trajectory

aforward(**input_args)는 forward의 비동기(async) 버전으로, _async_call_with_potential_trajectory_truncation을 사용해 동일한 trajectory 루프를 수행합니다.

truncate_trajectory(trajectory)

trajectory가 컨텍스트 창에 맞도록 잘라냅니다. 사용자는 이 메서드를 override해 자신만의 truncation 로직을 구현할 수 있습니다. 각 도구 호출은 4개의 키(thought, tool_name, tool_args, observation)를 가지므로, 키가 4개 이하(즉 도구 호출이 1개뿐)인 경우에는 잘라낼 수 없어 ContextWindowExceededError를 발생시킵니다.

그 외 상속받은 메서드

ReAct는 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(...) — 모듈 저장.

더 알아보기 (Learn more)