평가 빠른 시작

평가 빠른 시작 (Evaluation quickstart)

평가는 LLM 애플리케이션의 성능을 측정하는 정량적인 방법이에요. LLM은 예측할 수 없게 동작할 수 있으며, 프롬프트, 모델, 입력의 작은 변화도 결과에 크게 영향을 줄 수 있어요. 평가는 실패를 식별하고, 버전을 비교하며, 더 신뢰할 수 있는 AI 애플리케이션을 구축하는 구조화된 방법을 제공해요.

LangSmith에서 평가를 실행하려면 세 가지 핵심 구성 요소가 필요해요:

  • 데이터셋: 테스트 입력 집합(선택적으로 기대 출력 포함).
  • 대상 함수: 테스트하려는 애플리케이션의 부분 — 새 프롬프트가 있는 단일 LLM 호출, 하나의 모듈, 또는 전체 워크플로일 수 있어요.
  • 평가기: 대상 함수의 출력을 점수 매기는 함수.

이 빠른 시작은 LangSmith SDK 또는 UI를 사용해 LLM 응답의 정확성을 검사하는 스타터 평가를 실행하는 방법을 안내해요.

출처: 문서

본문

사전 요구사항

시작하기 전에 다음을 갖추고 있는지 확인해요:

UI 또는 SDK 필터를 선택해 지침을 확인하세요:

## 1. 워크스페이스 시크릿 설정
[LangSmith UI](https://smith.langchain.com)에서 API 키가 [워크스페이스 시크릿](/langsmith/set-up-hierarchy#configure-workspace-settings)으로 설정되어 있는지 확인해요.

1. <Icon icon="settings" /> **Settings**로 이동한 다음 **Secrets** 탭으로 이동해요.
2. **Add secret**을 선택하고 키 환경 변수(예: `OPENAI_API_KEY` 또는 `ANTHROPIC_API_KEY`)와 API 키를 **Value**로 입력해요.
3. **Save secret**을 선택해요.

> **참고:** LangSmith UI에서 워크스페이스 시크릿을 추가할 때, 시크릿 키가 모델 프로바이더가 기대하는 환경 변수 이름과 일치하는지 확인하세요.

> **참고:** 프로바이더가 OAuth2 `client_credentials`로 인증한다면, 대신 모델 구성에 자격 증명을 구성해요. 그 경우 워크스페이스 시크릿은 필요하지 않아요. [OAuth client credentials](/langsmith/model-configurations#oauth-client-credentials) 참조.

## 2. 프롬프트 생성

[Playground](/langsmith/prompt-engineering-concepts#playground)를 사용하면 서로 다른 프롬프트, 새 모델, 또는 다른 모델 구성을 대상으로 평가를 실행할 수 있어요.

1. [LangSmith UI](https://smith.langchain.com)에서 사이드바의 **Playground**를 클릭해요.
2. **Prompts** 패널 아래에서 **system** 프롬프트를 다음과 같이 수정해요:

   ```
   Answer the following question accurately:
   ```

   **Human** 메시지는 `{question}` 그대로 둬요.

## 3. 데이터셋 생성

1. **Set up Evaluation**을 클릭하면 페이지 하단에 **New Experiment** 테이블이 열려요.

2. **Select or create a new dataset** 드롭다운에서 **+ New** 버튼을 클릭해 새 데이터셋을 만들어요.

       <div style={{ textAlign: 'center' }}>
         <img className="block dark:hidden" src="https://mintcdn.com/langchain-5e9cc07a/hVPHwyb3hetqtQnG/langsmith/images/playground-system-prompt-light.png?fit=max&auto=format&n=hVPHwyb3hetqtQnG&q=85&s=b068f4407a83e31403da9a5473960fee" alt="Playground with the edited system prompt and new experiment with the dropdown for creating a new dataset." width="1422" height="743" data-path="langsmith/images/playground-system-prompt-light.png" />

         <img className="hidden dark:block" src="https://mintcdn.com/langchain-5e9cc07a/hVPHwyb3hetqtQnG/langsmith/images/playground-system-prompt-dark.png?fit=max&auto=format&n=hVPHwyb3hetqtQnG&q=85&s=a114b1a83bf8d0a074b4ce2759207e4d" alt="Playground with the edited system prompt and new experiment with the dropdown for creating a new dataset." width="1421" height="736" data-path="langsmith/images/playground-system-prompt-dark.png" />
       </div>

3. 데이터셋에 다음 예제를 추가해요:

   | 입력                                                    | 참조 출력                                          |
   | -------------------------------------------------------- | -------------------------------------------------- |
   | question: Which country is Mount Kilimanjaro located in? | output: Mount Kilimanjaro is located in Tanzania. |
   | question: What is Earth's lowest point?                  | output: Earth's lowest point is The Dead Sea.      |

4. **Save**를 클릭하고 이름을 입력해 새로 만든 데이터셋을 저장해요.

## 4. 평가기 추가

1. **+ Evaluator**를 클릭하고 **Prebuilt Evaluator** 옵션에서 **Correctness**를 선택해요.
2. **Correctness** 패널에서 **Save**를 클릭해요.

## 5. 평가 실행

1. 오른쪽 상단의 <Icon icon="player-play" /> **Start**를 선택해 평가를 실행해요. 그러면 **New Experiment** 테이블에 미리보기가 있는 [*실험*](/langsmith/evaluation-concepts#experiment)이 만들어져요. 실험 이름을 클릭하면 전체를 볼 수 있어요.

       <div style={{ textAlign: 'center' }}>
         <img className="block dark:hidden" src="https://mintcdn.com/langchain-5e9cc07a/3SZlGm2zGXjJWzA5/langsmith/images/full-experiment-view-light.png?fit=max&auto=format&n=3SZlGm2zGXjJWzA5&q=85&s=efa004b4032d0e439a58d08567b75478" alt="Full experiment view of the results that used the example dataset." width="1241" height="671" data-path="langsmith/images/full-experiment-view-light.png" />

         <img className="hidden dark:block" src="https://mintcdn.com/langchain-5e9cc07a/3SZlGm2zGXjJWzA5/langsmith/images/full-experiment-view-dark.png?fit=max&auto=format&n=3SZlGm2zGXjJWzA5&q=85&s=34c2921eeadd1b7782ac64b579bcef6a" alt="Full experiment view of the results that used the example dataset." width="1241" height="665" data-path="langsmith/images/full-experiment-view-dark.png" />
       </div>

## 다음 단계

> **팁:** LangSmith에서 실험 실행에 대해 더 알아보려면 [평가 개념 가이드](/langsmith/evaluation-concepts)를 읽어보세요.

* 평가에 대한 자세한 내용은 [평가 문서](/langsmith/evaluation)를 참조해요.
## 1. 프로젝트 및 패키지 설치
- Python
- TypeScript

프로젝트 디렉토리를 만들고 SDK에 필요한 패키지를 설치해요:

<CodeGroup>
  ```bash Python
  mkdir eval-quickstart && cd eval-quickstart
  python -m pip install langsmith openevals openai
  ```

  ```bash TypeScript
  mkdir eval-quickstart && cd eval-quickstart
  npm init -y
  npm install langsmith openevals openai
  npx tsc --init
  ```
</CodeGroup>

> **참고:** `yarn`을 패키지 매니저로 사용한다면 `@langchain/core`를 `openevals`의 peer dependency로 수동 설치해야 해요. 이것은 일반적인 LangSmith 평가에는 필요하지 않으며, [임의의 커스텀 코드](/langsmith/code-evaluator-ui)로 평가기를 정의할 수 있어요.

## 2. 환경 변수 설정

다음 환경 변수를 설정해요:

* `LANGSMITH_TRACING`
* `LANGSMITH_API_KEY`
* `OPENAI_API_KEY` (또는 LLM 프로바이더의 API 키)
* (선택) `LANGSMITH_WORKSPACE_ID`: LangSmith API 키가 여러 [워크스페이스](/langsmith/administration-overview#workspaces)에 연결되어 있다면, 사용할 워크스페이스를 지정하려면 이 변수를 설정해요.

```bash
export LANGSMITH_TRACING=true
export LANGSMITH_API_KEY="<your-langsmith-api-key>"
export OPENAI_API_KEY="<your-openai-api-key>"
export LANGSMITH_WORKSPACE_ID="<your-workspace-id>"
```

> **참고:** Anthropic을 사용한다면 [Anthropic 래퍼](/langsmith/trace-anthropic)로 호출을 트레이싱해요. 다른 프로바이더는 [traceable 래퍼](/langsmith/annotate-code#use-%40traceable-%2F-traceable)를 사용해요.

## 3. 데이터셋 생성

1. 파일을 만들고 다음 코드를 추가해요. 이 코드는 다음을 수행해요:

   * LangSmith에 연결할 `Client`를 import.
   * 데이터셋 생성.
   * 예제 [*입력*과 *출력*](/langsmith/evaluation-concepts#examples) 정의.
   * 해당 입력·출력 쌍을 LangSmith의 데이터셋과 연결해 평가에 사용할 수 있게 함.

       <CodeGroup>
         ```python Python
         # dataset.py
         from langsmith import Client

         def main():
             client = Client()

             # Programmatically create a dataset in LangSmith
             dataset = client.create_dataset(
                 dataset_name="Sample dataset",
                 description="A sample dataset in LangSmith."
             )

             # Create examples
             examples = [
                 {
                     "inputs": {"question": "Which country is Mount Kilimanjaro located in?"},
                     "outputs": {"answer": "Mount Kilimanjaro is located in Tanzania."},
                 },
                 {
                     "inputs": {"question": "What is Earth's lowest point?"},
                     "outputs": {"answer": "Earth's lowest point is The Dead Sea."},
                 },
             ]

             # Add examples to the dataset
             client.create_examples(dataset_id=dataset.id, examples=examples)
             print("Created dataset:", dataset.name)

         if __name__ == "__main__":
             main()

         ```

         ```typescript TypeScript
         // dataset.ts
         import { Client } from "langsmith";

         async function main() {
         const client = new Client();

         const dataset = await client.createDataset(
             "Sample dataset",
             { description: "A sample dataset in LangSmith." }
         );

         // Define examples
         const inputs = [
             { question: "Which country is Mount Kilimanjaro located in?" },
             { question: "What is Earth's lowest point?" },
         ];
         const outputs = [
             { answer: "Mount Kilimanjaro is located in Tanzania." },
             { answer: "Earth's lowest point is The Dead Sea." },
         ];

         await client.createExamples({
             datasetId: dataset.id,
             inputs,
             outputs,
         });

         console.log("Created dataset:", dataset.name);
         }

         if (require.main === module) {
         main().catch((e) => {
             console.error(e);
             process.exit(1);
         });
         }
         ```
       </CodeGroup>

2. 터미널에서 `dataset` 파일을 실행해 앱을 평가할 데이터셋을 만들어요:

       <CodeGroup>
         ```bash Python
         python dataset.py
         ```

         ```bash TypeScript
         npx ts-node dataset.ts
         ```
       </CodeGroup>

   다음과 같은 출력이 표시돼요:

   ```bash
   Created dataset: Sample dataset
   ```

## 4. 대상 함수 생성

평가할 내용을 담은 [대상 함수](/langsmith/define-target-function)를 정의해요. 이 가이드에서는 질문에 답하는 단일 LLM 호출을 담은 대상 함수를 정의할 거예요.

`eval` 파일에 다음을 추가해요:

<CodeGroup>
  ```python Python
  # eval.py
  from langsmith import Client, wrappers
  from openai import OpenAI

  # Wrap the OpenAI client for LangSmith tracing
  openai_client = wrappers.wrap_openai(OpenAI())

  # Define the application logic you want to evaluate inside a target function
  # The SDK will automatically send the inputs from the dataset to your target function
  def target(inputs: dict) -> dict:
      response = openai_client.chat.completions.create(
          model="gpt-5-mini",
          messages=[
              {"role": "system", "content": "Answer the following question accurately"},
              {"role": "user", "content": inputs["question"]},
          ],
      )
      return {"answer": response.choices[0].message.content.strip()}
  ```

  ```typescript TypeScript
  // eval.ts
  import { evaluate } from "langsmith/evaluation";
  import { wrapOpenAI } from "langsmith/wrappers/openai";
  import OpenAI from "openai";

  const openaiClient = wrapOpenAI(new OpenAI());

  async function target(inputs: Record<string, any>): Promise<Record<string, any>> {
    const question = String(inputs.question ?? "");
    const resp = await openaiClient.chat.completions.create({
      model: "gpt-5-mini",
      messages: [
        { role: "system", content: "Answer the following question accurately" },
        { role: "user", content: question },
      ],
    });
    return { answer: resp.choices[0].message.content?.trim() ?? "" };
  }
  ```
</CodeGroup>

## 5. 평가기 정의

이 단계에서는 앱이 생성하는 답변을 어떻게 채점할지 LangSmith에 알려줘요.

[`openevals`](https://github.com/langchain-ai/openevals)에서 사전 구축된 평가 프롬프트(`CORRECTNESS_PROMPT`)와 그 프롬프트를 [*LLM-as-judge 평가기*](/langsmith/evaluation-concepts#llm-as-judge)로 감싸는 헬퍼를 import해요. 이 평가기가 애플리케이션의 출력을 점수 매겨요.

> **참고:** `CORRECTNESS_PROMPT`는 `"inputs"`, `"outputs"`, `"reference_outputs"` 변수가 있는 단순한 f-string이에요. 자세한 내용은 [OpenEvals 프롬프트 커스터마이징](https://github.com/langchain-ai/openevals#customizing-prompts)을 참조해요.

평가기는 다음을 비교해요:

* `inputs`: 대상 함수에 전달된 것(예: 질문 텍스트).
* `outputs`: 대상 함수가 반환한 것(예: 모델의 답변).
* `reference_outputs`: [3단계](#3-데이터셋-생성)에서 각 데이터셋 예제에 첨부한 정답.

`eval` 파일에 다음 강조된 코드를 추가해요:

<CodeGroup>
  ```python Python
  from langsmith import Client, wrappers
  from openai import OpenAI
  from openevals.llm import create_llm_as_judge
  from openevals.prompts import CORRECTNESS_PROMPT

  # Wrap the OpenAI client for LangSmith tracing
  openai_client = wrappers.wrap_openai(OpenAI())

  # Define the application logic you want to evaluate inside a target function
  # The SDK will automatically send the inputs from the dataset to your target function
  def target(inputs: dict) -> dict:
      response = openai_client.chat.completions.create(
          model="gpt-5-mini",
          messages=[
              {"role": "system", "content": "Answer the following question accurately"},
              {"role": "user", "content": inputs["question"]},
          ],
      )
      return {"answer": response.choices[0].message.content.strip()}

  def correctness_evaluator(inputs: dict, outputs: dict, reference_outputs: dict):
      evaluator = create_llm_as_judge(
          prompt=CORRECTNESS_PROMPT,
          model="openai:o3-mini",
          feedback_key="correctness",
      )
      return evaluator(
          inputs=inputs,
          outputs=outputs,
          reference_outputs=reference_outputs
      )
  ```

  ```typescript TypeScript
  import { evaluate } from "langsmith/evaluation";
  import { wrapOpenAI } from "langsmith/wrappers/openai";
  import OpenAI from "openai";
  import { createLLMAsJudge, CORRECTNESS_PROMPT } from "openevals";

  const openaiClient = wrapOpenAI(new OpenAI());

  async function target(inputs: Record<string, any>): Promise<Record<string, any>> {
    const question = String(inputs.question ?? "");
    const resp = await openaiClient.chat.completions.create({
      model: "gpt-5-mini",
      messages: [
        { role: "system", content: "Answer the following question accurately" },
        { role: "user", content: question },
      ],
    });
    return { answer: resp.choices[0].message.content?.trim() ?? "" };
  }

  const judge = createLLMAsJudge({
    prompt: CORRECTNESS_PROMPT,
    model: "openai:o3-mini",
    feedbackKey: "correctness",
  });

  async function correctnessEvaluator(run: {
    inputs: Record<string, any>;
    outputs: Record<string, any>;
    referenceOutputs?: Record<string, any>;
  }) {
    return judge({
      inputs: run.inputs,
      outputs: run.outputs,
      // OpenEvals expects snake_case here:
      reference_outputs: run.referenceOutputs,
    });
  }
  ```
</CodeGroup>

## 6. 실행 및 결과 보기

평가 실험을 실행하려면 `evaluate(...)`를 호출해요. 이 함수는:

* [3단계](#3-데이터셋-생성)에서 만든 데이터셋에서 예제를 가져와요.
* 각 예제의 입력을 [4단계](#4-대상-함수-생성)의 대상 함수로 보내요.
* 출력(모델의 답변)을 수집해요.
* 출력과 함께 `reference_outputs`를 [5단계](#5-평가기-정의)의 평가기로 전달해요.
* 모든 결과를 LangSmith에 실험으로 기록해 UI에서 볼 수 있게 해요.

1. `eval` 파일에 강조된 코드를 추가해요:

       <CodeGroup>
         ```python Python
         from langsmith import Client, wrappers
         from openai import OpenAI
         from openevals.llm import create_llm_as_judge
         from openevals.prompts import CORRECTNESS_PROMPT

         # Wrap the OpenAI client for LangSmith tracing
         openai_client = wrappers.wrap_openai(OpenAI())

         # Define the application logic you want to evaluate inside a target function
         # The SDK will automatically send the inputs from the dataset to your target function
         def target(inputs: dict) -> dict:
             response = openai_client.chat.completions.create(
                 model="gpt-5-mini",
                 messages=[
                     {"role": "system", "content": "Answer the following question accurately"},
                     {"role": "user", "content": inputs["question"]},
                 ],
             )
             return {"answer": response.choices[0].message.content.strip()}

         def correctness_evaluator(inputs: dict, outputs: dict, reference_outputs: dict):
             evaluator = create_llm_as_judge(
                 prompt=CORRECTNESS_PROMPT,
                 model="openai:o3-mini",
                 feedback_key="correctness",
             )
             return evaluator(
                 inputs=inputs,
                 outputs=outputs,
                 reference_outputs=reference_outputs
             )

         # After running the evaluation, a link will be provided to view the results in langsmith
         def main():
             client = Client()
             experiment_results = client.evaluate(
                 target,
                 data="Sample dataset",
                 evaluators=[
                     correctness_evaluator,
                     # can add multiple evaluators here
                 ],
                 experiment_prefix="first-eval-in-langsmith",
                 max_concurrency=2,
             )
             print(experiment_results)

         if __name__ == "__main__":
             main()
         ```

         ```typescript TypeScript
         import { evaluate } from "langsmith/evaluation";
         import { wrapOpenAI } from "langsmith/wrappers/openai";   // helper to wrap OpenAI client
         import OpenAI from "openai";                              // model provider
         import { createLLMAsJudge, CORRECTNESS_PROMPT } from "openevals"; // evaluator tools

         const openaiClient = wrapOpenAI(new OpenAI());

         async function target(inputs: Record<string, any>): Promise<Record<string, any>> {
         const question = String(inputs.question ?? "");
         const resp = await openaiClient.chat.completions.create({
             model: "gpt-5-mini",
             messages: [
             { role: "system", content: "Answer the following question accurately" },
             { role: "user", content: question },
             ],
         });
         return { answer: resp.choices[0].message.content?.trim() ?? "" };
         }

         const judge = createLLMAsJudge({
         prompt: CORRECTNESS_PROMPT,
         model: "openai:o3-mini",
         feedbackKey: "correctness",
         });

         async function correctnessEvaluator(run: {
         inputs: Record<string, any>;
         outputs: Record<string, any>;
         referenceOutputs?: Record<string, any>;
         }) {
         return judge({
             inputs: run.inputs,
             outputs: run.outputs,
             // OpenEvals expects snake_case here:
             reference_outputs: run.referenceOutputs,
         });
         }

         async function main() {
         const datasetName = process.env.DATASET_NAME ?? "Sample dataset";

         const results = await evaluate(target, {
             data: datasetName,
             evaluators: [correctnessEvaluator],
             experimentPrefix: "first-eval-in-langsmith",
             maxConcurrency: 2,
         });

         console.log(results);
         }

         if (require.main === module) {
         main().catch((e) => {
             console.error(e);
             process.exit(1);
         });
         }
         ```
       </CodeGroup>

2. 평가기를 실행해요:

       <CodeGroup>
         ```bash Python
         python eval.py
         ```

         ```bash TypeScript
         npx ts-node eval.ts
         ```
       </CodeGroup>

3. 실험 결과에 대한 평가 결과와 메타데이터를 볼 수 있는 링크를 받게 돼요:

   ```
   View the evaluation results for experiment: 'first-eval-in-langsmith-00000000' at: https://smith.langchain.com/o/6551f9c4-2685-4a08-86b9-1b29643deb3d/datasets/e5fde557-c274-4e49-b39d-000000000000/compare?selectedSessions=70b11778-6a28-4cdb-be81-000000000000

   <ExperimentResults first-eval-in-langsmith-00000000>
   ```

4. 평가 실행 출력의 링크를 따라 [LangSmith UI](https://smith.langchain.com)의 **Datasets & Experiments** 페이지에 접근해 실험 결과를 살펴봐요. 그러면 **Inputs**, **Reference Output**, **Outputs**를 보여주는 테이블이 있는 생성된 실험으로 이동해요. 데이터셋을 선택해 결과의 확장 보기를 열 수 있어요.

       <div style={{ textAlign: 'center' }}>
         <img className="block dark:hidden" src="https://mintcdn.com/langchain-5e9cc07a/DDMvkseOvrCjx9sx/langsmith/images/experiment-results-link-light.png?fit=max&auto=format&n=DDMvkseOvrCjx9sx&q=85&s=94341c15219e46866589140d87efb8f6" alt="Experiment results in the UI after following the link." width="1816" height="464" data-path="langsmith/images/experiment-results-link-light.png" />

         <img className="hidden dark:block" src="https://mintcdn.com/langchain-5e9cc07a/DDMvkseOvrCjx9sx/langsmith/images/experiment-results-link-dark.png?fit=max&auto=format&n=DDMvkseOvrCjx9sx&q=85&s=d741b33219f7d130e80e1dfb7e743ac6" alt="Experiment results in the UI after following the link." width="1567" height="455" data-path="langsmith/images/experiment-results-link-dark.png" />
       </div>

## 다음 단계

다음으로 살펴볼 만한 주제들:

* [평가 개념](/langsmith/evaluation-concepts) — LangSmith 평가의 핵심 용어 설명.
* [OpenEvals README](https://github.com/langchain-ai/openevals) — 사용 가능한 모든 사전 구축 평가기와 커스터마이징 방법.
* [커스텀 평가기 정의](/langsmith/code-evaluator-ui).
* 모든 클래스와 함수에 대한 포괄적인 설명은 [Python](https://docs.smith.langchain.com/reference/python/reference) 또는 [TypeScript](https://docs.smith.langchain.com/reference/js) SDK 참조.

더 알아보기 (Learn more)