이것은 대화형 노트북입니다. 로컬에서 실행하거나 아래 링크를 사용할 수 있습니다:

오디오 데이터와 함께 Weave 사용하기: OpenAI 예제

이 데모는 GPT 4o Audio Preview를 사용한 OpenAI 채팅 완성 API를 사용하여 텍스트 프롬프트에 대한 오디오 응답을 생성하고 이를 Weave에서 추적합니다. 고급 사용 사례에서는 OpenAI Realtime API를 활용하여 실시간으로 오디오를 스트리밍합니다. 비디오 시연을 보려면 다음 썸네일을 클릭하거나 여기. Everything Is AWESOME

설정

OpenAI (openai) 및 Weave (weave) 종속성과 API 키 관리 종속성 set-env.
%%capture
!pip install openai
!pip install weave
!pip install set-env-colab-kaggle-dotenv -q # for env var
python
%%capture
# Temporary workaround to fix bug in openai:
# TypeError: Client.__init__() got an unexpected keyword argument 'proxies'
# See https://community.openai.com/t/error-with-openai-1-56-0-client-init-got-an-unexpected-keyword-argument-proxies/1040332/15
!pip install "httpx<0.28"
다음으로 OpenAI 및 Weave에 필요한 API 키를 로드합니다. 여기서는 Google Colab의 비밀 키 관리자와 호환되는 set_env를 사용하며, Colab의 특정 google.colab.userdata의 대안입니다. 참조: 여기 사용 지침.
# Set environment variables.
from set_env import set_env

_ = set_env("OPENAI_API_KEY")
_ = set_env("WANDB_API_KEY")
마지막으로 필요한 라이브러리를 가져옵니다.
import base64
import os
import time
import wave

import numpy as np
from IPython.display import display
from openai import OpenAI

import weave

오디오 스트리밍 및 저장 예제

이제 오디오 모달리티가 활성화된 OpenAI의 완성 엔드포인트에 대한 호출을 설정하겠습니다. 먼저 OpenAI 클라이언트를 생성하고 Weave 프로젝트를 시작합니다.
client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
weave.init("openai-audio-chat")
이제 OpenAI 완성 요청을 정의하고 Weave 데코레이터(op)를 추가하겠습니다. 여기서 함수 prompt_endpont_and_log_trace를 정의합니다. 이 함수에는 세 가지 주요 단계가 있습니다:
  1. 텍스트 및 오디오 입력과 출력을 지원하는 GPT 4o Audio Preview 모델을 사용하여 완성 객체를 만듭니다.
    • 모델에게 다양한 억양으로 천천히 13까지 세도록 프롬프트합니다.
    • 완성을 “stream”으로 설정합니다.
  2. 스트리밍된 데이터가 청크별로 기록되는 새 출력 파일을 엽니다.
  3. Weave가 트레이스에 오디오 데이터를 기록할 수 있도록 오디오 파일에 대한 열린 파일 핸들러를 반환합니다.
SAMPLE_RATE = 22050

@weave.op()
def prompt_endpoint_and_log_trace(system_prompt=None, user_prompt=None):
    if not system_prompt:
        system_prompt = "You're the fastest counter in the world"
    if not user_prompt:
        user_prompt = "Count to 13 super super slow, enunciate each number with a dramatic flair, changing up accents as you go along. British, French, German, Spanish, etc."
    # Request from the OpenAI API with audio modality
    completion = client.chat.completions.create(
        model="gpt-4o-audio-preview",
        modalities=["text", "audio"],
        audio={"voice": "fable", "format": "pcm16"},
        stream=True,
        messages=[
            {"role": "system", "content": system_prompt},
            {"role": "user", "content": user_prompt},
        ],
    )

    # Open a wave file for writing
    with wave.open("./output.wav", "wb") as wav_file:
        wav_file.setnchannels(1)  # Mono
        wav_file.setsampwidth(2)  # 16-bit
        wav_file.setframerate(SAMPLE_RATE)  # Sample rate (adjust if needed)

        # Write chunks as they are streamed in from the API
        for chunk in completion:
            if (
                hasattr(chunk, "choices")
                and chunk.choices is not None
                and len(chunk.choices) > 0
                and hasattr(chunk.choices[0].delta, "audio")
                and chunk.choices[0].delta.audio.get("data") is not None
            ):
                # Decode the base64 audio data
                audio_data = base64.b64decode(chunk.choices[0].delta.audio.get("data"))

                # Write the current chunk to the wave file
                wav_file.writeframes(audio_data)

    # Return the file to Weave op
    return wave.open("output.wav", "rb")

테스트

다음 셀을 실행하세요. 시스템 및 사용자 프롬프트는 출력 오디오와 함께 Weave 트레이스에 저장됩니다. 셀을 실행한 후 ”🍩” 이모티콘 옆의 링크를 클릭하여 트레이스를 확인하세요.
from IPython.display import Audio

# Call the function to write the audio stream
prompt_endpoint_and_log_trace(
    system_prompt="You're the fastest counter in the world",
    user_prompt="Count to 13 super super slow, enunciate each number with a dramatic flair, changing up accents as you go along. British, French, German, Spanish, etc.",
)

# Display the updated audio stream
display(Audio("output.wav", rate=SAMPLE_RATE, autoplay=True))

고급 사용법: Weave를 사용한 실시간 오디오 API