> ## Documentation Index
> Fetch the complete documentation index at: https://docs.coreweave.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 제너레이터 함수 트레이스

> W&B Weave 트레이싱으로 동기 및 비동기 제너레이터 함수를 추적하세요

W\&B Weave는 깊게 중첩된 패턴을 포함해 동기 및 비동기 제너레이터 함수의 트레이싱을 모두 지원합니다. 이 페이지에서는 제너레이터 함수에 `@weave.op` 데코레이터를 적용하여 Weave가 함수의 입력, yield된 출력, 중첩된 Call의 전체 계층 구조를 캡처하도록 하는 방법을 설명합니다. 스트리밍 방식이거나 지연 평가되는 코드 경로의 출력을 Weights & Biases UI에서 다른 트레이스와 함께 살펴보려는 경우에 활용하세요.

<Warning>
  제너레이터는 값을 지연 방식으로 yield하므로, Weave는 제너레이터가 완전히 소비된 경우에만(예: 목록으로 변환한 경우) 출력을 로깅합니다.
  트레이스에 출력이 캡처되도록 하려면 제너레이터를 완전히 소비하세요(예: `list()` 사용).
</Warning>

<Tabs>
  <Tab title="Python">
    ```python theme={"system"}
    from typing import Generator
    import weave

    weave.init("my-project")

    # 이 함수는 동기 제너레이터를 사용합니다.
    # Weave는 Call과 입력(`x`)을 트레이스하지만,
    # 출력 값은 제너레이터가 소비된 후에만 캡처됩니다(예: `list()` 사용).
    @weave.op
    def basic_gen(x: int) -> Generator[int, None, None]:
        yield from range(x)

    # 제너레이터 파이프라인 안에서 사용되는 일반 동기 함수입니다.
    # 이 함수의 Call도 Weave가 별도로 트레이스합니다.
    @weave.op
    def inner(x: int) -> int:
        return x + 1

    # 트레이스되는 다른 함수(`inner`)를 호출하는 동기 제너레이터입니다.
    # yield되는 각 값은 `inner`에 대한 개별 트레이스 Call에서 생성됩니다.
    @weave.op
    def nested_generator(x: int) -> Generator[int, None, None]:
        for i in range(x):
            yield inner(i)

    # 위의 제너레이터를 조합한 제너레이터입니다.
    # 이를 트레이싱하면 다음과 같은 계층적 Call 트리가 생성됩니다.
    # - `deeply_nested_generator` (부모)
    #   - `nested_generator` (자식)
    #     - `inner` (손자)
    @weave.op
    def deeply_nested_generator(x: int) -> Generator[int, None, None]:
        for i in range(x):
            for j in nested_generator(i):
                yield j

    # Weave가 출력을 캡처하려면 제너레이터를 *소비*해야 합니다.
    # 이는 동기 및 비동기 제너레이터 모두에 적용됩니다.
    res = deeply_nested_generator(4)
    list(res)  # 중첩된 모든 Call과 yield의 트레이싱을 트리거합니다
    ```
  </Tab>

  <Tab title="TypeScript">
    ```plaintext theme={"system"}
    This feature is not available in the TypeScript SDK yet.
    ```
  </Tab>
</Tabs>

다음 스크린샷은 위 코드로 생성된 트레이스를 선택한 **Traces** 페이지입니다. 가운데 패널에 선택한 트레이스의 트레이스 트리가 표시되며, 트리 계층 구조에서 `deeply_nested_generator`, `nested_generator`, `inner` Op을 확인할 수 있습니다.

<img src="https://mintcdn.com/coreweave-dbfa0e8d/3Dv_sw2eg8feUJlx/products/wandb/weave/_media/generators.png?fit=max&auto=format&n=3Dv_sw2eg8feUJlx&q=85&s=58e76a5d5bdd84e1efa37433e780180f" alt="깊게 중첩된 Op을 보여주는 트레이스 트리가 선택된 Weave Traces 페이지" width="1966" height="1134" data-path="products/wandb/weave/_media/generators.png" />

<h2 id="consume-generators">
  제너레이터 소비
</h2>

다음 섹션에서는 Weave가 제너레이터의 출력을 기록하려면 제너레이터를 소비해야 하는 이유와 사용 가능한 소비 패턴을 설명합니다.

Weave는 제너레이터를 완전히 소비한 후에만 제너레이터의 출력을 캡처합니다. 제너레이터를 순회하여 소비하세요(예를 들어 `list()`, `for` 루프 또는 값이 소진될 때까지 `next()`를 사용하세요). 비동기 제너레이터에도 `async for` 또는 이에 상응하는 소비 방식을 사용할 때 동일하게 적용됩니다.

`@weave.op`으로 함수와 메서드를 데코레이팅하는 방법에 대한 자세한 내용은 [Call 생성](/ko/products/wandb/weave/guides/tracking/create-call)을 참조하세요.

<h2 id="accumulate-yielded-values-into-a-single-trace">
  yield된 값을 단일 트레이스로 누적하기
</h2>

Weave가 yield된 값의 원시 시퀀스 대신 결합된 결과(예: 이어 붙인 문자열이나 목록)를 기록하도록 하려면 accumulator를 사용하세요.

`weave.op`의 `accumulator` 매개변수를 사용하면 제너레이터 함수에서 yield된 값을 결합하는 방식을 사용자 지정할 수 있습니다. 예를 들어, 스트리밍되는 텍스트 토큰을 하나의 문자열로 이어 붙일 수 있습니다. accumulator는 인수 두 개를 받는 함수로, Weave가 yield된 값마다 한 번씩 호출하여 결과를 점진적으로 구성합니다.

<Note>
  TypeScript에서는 `accumulator` 매개변수를 사용할 수 없습니다.
</Note>

다음 예시는 yield된 각 값을 목록에 추가하는 맞춤형 accumulator를 보여줍니다. 제너레이터를 끝까지 소비하면 Weave가 해당 목록을 Call 출력으로 기록합니다.

```python theme={"system"}
from typing import Generator
import weave

weave.init("your-team-name/your-project-name")

# Weave는 각 yield 이후에 이 함수를 호출합니다. 첫 호출에서 acc는 None입니다.
# 마지막으로 반환한 값이 트레이스에 기록되는 Op 출력이 됩니다.
def list_accumulator(acc, value):
    if acc is None:
        acc = []
    acc.append(value)
    return acc

# accumulator 매개변수를 설정합니다
@weave.op(accumulator=list_accumulator)
def basic_gen_with_accumulator(x: int) -> Generator[int, None, None]:
    yield from range(x)

# 모든 yield가 실행되고 accumulator가 트레이스에 기록할 최종 출력을 생성할 수 있도록 완료될 때까지 반복합니다.
result = list(basic_gen_with_accumulator(3))
print(result)
```


## Related topics

- [중첩 함수 트레이스하기](/ko/products/wandb/weave/tutorial-tracing_2.md)
