Skip to main content

TypeScript용 Weave 퀵스타트 가이드

W&B Weave를 TypeScript와 함께 사용해 다음을 수행할 수 있습니다:
  • 언어 모델의 입력, 출력, 트레이스를 로깅하고 디버깅
  • 언어 모델 사용 사례에 대해 동일한 조건으로 비교할 수 있는 엄격한 평가 구축
  • 실험부터 평가, 프로덕션에 이르기까지 LLM 워크플로 전반에서 생성되는 모든 정보 정리
자세한 내용은 Weave 문서를 참조하세요.

함수 추적

TypeScript 코드에서 Weave를 사용하려면 새 Weave 프로젝트를 초기화하고 추적하려는 함수에 weave.op 래퍼를 추가하세요. weave.op를 추가하고 함수를 호출한 뒤, W&B 대시보드로 이동해 프로젝트에서 해당 함수가 추적되는 것을 확인하세요. 코드는 자동으로 추적되므로 UI의 코드 탭을 확인하세요!
async function initializeWeaveProject() {
    const PROJECT = 'weave-examples';
    await weave.init(PROJECT);
}
const stripUserInput = weave.op(function stripUserInput(userInput: string): string {
    return userInput.trim();
});
다음 예시는 기본 함수 추적이 어떻게 작동하는지 보여줍니다.
async function demonstrateBasicTracking() {
    const result = await stripUserInput("    hello    ");
    console.log('기본 추적 결과:', result);
}

OpenAI 인테그레이션

Weave는 다음을 포함한 모든 OpenAI 호출을 자동으로 추적합니다.
  • 토큰 사용량
  • API 비용
  • 요청/응답 쌍
  • 모델 설정
OpenAI 외에도 Weave는 Anthropic 및 Mistral과 같은 다른 LLM 제공업체의 자동 로깅도 지원합니다. 전체 목록은 인테그레이션 문서의 LLM Providers를 참조하세요.
function initializeOpenAIClient() {
    return weave.wrapOpenAI(new OpenAI({
        apiKey: process.env.OPENAI_API_KEY
    }));
}
async function demonstrateOpenAITracking() {
    const client = initializeOpenAIClient();
    const result = await client.chat.completions.create({
        model: "gpt-4-turbo",
        messages: [{ role: "user", content: "Hello, how are you?" }],
    });
    console.log('OpenAI tracking result:', result);
}

중첩 함수 추적

Weave를 사용하면 여러 추적된 함수와 LLM 호출을 조합해 복잡한 워크플로를 추적하면서도 전체 실행 트레이스를 유지할 수 있습니다. 장점은 다음과 같습니다:
  • 애플리케이션 로직 흐름 전체를 파악 가능
  • 복잡한 오퍼레이션 체인을 쉽게 디버깅 가능
  • 성능 최적화 기회 제공
async function demonstrateNestedTracking() {
    const client = initializeOpenAIClient();
    
    const correctGrammar = weave.op(async function correctGrammar(userInput: string): Promise<string> {
        const stripped = await stripUserInput(userInput);
        const response = await client.chat.completions.create({
            model: "gpt-4-turbo",
            messages: [
                {
                    role: "system",
                    content: "You are a grammar checker, correct the following user input."
                },
                { role: "user", content: stripped }
            ],
            temperature: 0,
        });
        return response.choices[0].message.content ?? '';
    });

    const grammarResult = await correctGrammar("That was so easy, it was a piece of pie!");
    console.log('Nested tracking result:', grammarResult);
}

데이터셋 관리

weave.Dataset 클래스를 사용하면 Weave로 데이터셋을 생성하고 관리할 수 있습니다. Weave Models와 마찬가지로 weave.Dataset는 다음과 같은 작업에 도움이 됩니다:
  • 데이터를 추적하고 버전을 관리
  • 테스트 케이스를 구성
  • 팀 구성원 간에 데이터셋을 공유
  • 체계적인 평가 수행 지원
interface GrammarExample {
    userInput: string;
    expected: string;
}
function createGrammarDataset(): weave.Dataset<GrammarExample> {
    return new weave.Dataset<GrammarExample>({
        id: 'grammar-correction',
        rows: [
            {
                userInput: "That was so easy, it was a piece of pie!",
                expected: "That was so easy, it was a piece of cake!"
            },
            {
                userInput: "I write good",
                expected: "I write well"
            },
            {
                userInput: "LLM's are best",
                expected: "LLM's are the best"
            }
        ]
    });
}

평가 프레임워크

Weave는 Evaluation 클래스를 통해 평가 주도 개발을 지원합니다. 평가를 사용하면 GenAI 애플리케이션을 더 안정적으로 반복 개선할 수 있습니다. Evaluation 클래스는 다음을 수행합니다:
  • Dataset에서 Model의 성능을 평가합니다
  • 맞춤형 채점 함수를 적용합니다
  • 상세한 성능 보고서를 생성합니다
  • 모델 버전 간 비교를 지원합니다
전체 평가 튜토리얼은 http://wandb.me/weave_eval_tut에서 확인할 수 있습니다
class OpenAIGrammarCorrector {
    private oaiClient: ReturnType<typeof weave.wrapOpenAI>;
    
    constructor() {
        this.oaiClient = weave.wrapOpenAI(new OpenAI({
            apiKey: process.env.OPENAI_API_KEY
        }));
        this.predict = weave.op(this, this.predict);
    }

    async predict(userInput: string): Promise<string> {
        const response = await this.oaiClient.chat.completions.create({
            model: 'gpt-4-turbo',
            messages: [
                { 
                    role: "system", 
                    content: "You are a grammar checker, correct the following user input." 
                },
                { role: "user", content: userInput }
            ],
            temperature: 0
        });
        return response.choices[0].message.content ?? '';
    }
}
async function runEvaluation() {
    const corrector = new OpenAIGrammarCorrector();
    const dataset = createGrammarDataset();
    
    const exactMatch = weave.op(
        function exactMatch({ modelOutput, datasetRow }: { 
            modelOutput: string; 
            datasetRow: GrammarExample 
        }): { match: boolean } {
            return { match: datasetRow.expected === modelOutput };
        },
        { name: 'exactMatch' }
    );

    const evaluation = new weave.Evaluation({
        dataset,
        scorers: [exactMatch],
    });

    const summary = await evaluation.evaluate({
        model: weave.op((args: { datasetRow: GrammarExample }) => 
            corrector.predict(args.datasetRow.userInput)
        )
    });
    console.log('평가 요약:', summary);
}
다음 main 함수는 모든 데모를 실행합니다:
async function main() {
    try {
        await initializeWeaveProject();
        await demonstrateBasicTracking();
        await demonstrateOpenAITracking();
        await demonstrateNestedTracking();
        await runEvaluation();
    } catch (error) {
        console.error('데모 실행 중 오류 발생:', error);
    }
}