첫 실험 실행하기(Run your first experiment)

첫 실험 실행하기(Run your first experiment)

이 튜토리얼은 @experiment 데코레이터와 로컬 CSV 백엔드로 Ragas의 첫 실험을 실행하는 과정을 안내해요. 가상의 애플리케이션 엔드포인트를 만들고, 커스텀 지표로 응답을 평가하며, 결과가 CSV 파일로 저장되는 흐름을 그대로 따라 해볼 수 있어요.

출처: 문서

본문

튜토리얼은 @experiment 데코레이터와 로컬 CSV 백엔드를 사용해 Ragas로 첫 실험을 실행하는 과정을 안내해요.

사전 요구사항(Prerequisites)

  • Python 3.9+
  • Ragas 설치됨 (설치 참고)

Hello World 👋

1. 설치(Install) (아직 안 했다면)

pip install ragas

2. hello_world.py 만들기

이 내용을 복사해 새 파일로 저장하고 hello_world.py로 저장하세요:

import numpy as np
from ragas import Dataset, experiment
from ragas.metrics import MetricResult, discrete_metric

# Define a custom metric for accuracy
@discrete_metric(name="accuracy_score", allowed_values=["pass", "fail"])
def accuracy_score(response: str, expected: str):
    result = "pass" if expected.lower().strip() == response.lower().strip() else "fail"
    return MetricResult(value=result, reason=f"Match: {result == 'pass'}")

# Mock application endpoint that simulates an AI application response
def mock_app_endpoint(**kwargs) -> str:
    return np.random.choice(["Paris", "4", "Blue Whale", "Einstein", "Python"])

# Create an experiment that uses the mock application endpoint and the accuracy metric
@experiment()
async def run_experiment(row):
    response = mock_app_endpoint(query=row.get("query"))
    accuracy = accuracy_score.score(response=response, expected=row.get("expected_output"))
    return {**row, "response": response, "accuracy": accuracy.value}

if __name__ == "__main__":
    import asyncio

    # Create dataset inline
    dataset = Dataset(name="test_dataset", backend="local/csv", root_dir=".")
    test_data = [
        {"query": "What is the capital of France?", "expected_output": "Paris"},
        {"query": "What is 2 + 2?", "expected_output": "4"},
        {"query": "What is the largest animal?", "expected_output": "Blue Whale"},
        {"query": "Who developed the theory of relativity?", "expected_output": "Einstein"},
        {"query": "What programming language is named after a snake?", "expected_output": "Python"},
    ]

    for sample in test_data:
        dataset.append(sample)
    dataset.save()

    # Run experiment
    _ = asyncio.run(run_experiment.arun(dataset, name="first_experiment"))

3. 생성된 파일 확인하기

tree .

다음과 같은 구조가 보여야 해요:

├── datasets
│   └── test_dataset.csv
└── experiments
    └── first_experiment.csv

4. 첫 실험 결과 보기

open experiments/first_experiment.csv

출력 미리보기:

다음 단계(Next steps)

더 알아보기 (Learn more)