0Pricing
AI Agents · 강의

LangSmith와 Langfuse를 활용한 추적 분석

추적 기록을 읽고 느린 도구, 잘못된 결정, 오류 패턴을 식별합니다.

LangSmith와 Langfuse를 활용한 추적 분석은(는) CoddyKit의 무료 AI Agents 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.

에이전트를 추적해야 하는 이유

에이전트는 실행할 때마다 여러 번 LLM을 호출하고 도구를 호출합니다. 추적이 없으면 디버깅은 추측에 의존할 수밖에 없습니다. 추적은 입력, 출력, 토큰 사용량, 지연 시간, 오류 등 모든 단계를 기록하여 각 실행을 완전히 파악할 수 있게 합니다.

LangSmith 설정

LangSmith는 LangChain을 위한 Anthropic의 추적 플랫폼입니다. 두 개의 환경 변수를 설정하여 활성화하십시오. 모든 LangChain 호출이 자동으로 추적되어 LangSmith 사용자 인터페이스에 표시됩니다.

import os
from dotenv import load_dotenv

load_dotenv()

# LangSmith tracing configuration
os.environ['LANGCHAIN_TRACING_V2'] = 'true'
os.environ['LANGCHAIN_API_KEY'] = os.environ.get('LANGSMITH_API_KEY', 'ls__...')
os.environ['LANGCHAIN_PROJECT'] = 'my-agent-project'

# Now any LangChain code is automatically traced
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage

llm = ChatOpenAI(model='gpt-4o-mini', api_key=os.environ.get('OPENAI_API_KEY', 'sk-...'))

# This call is traced automatically
response = llm.invoke([HumanMessage(content='What is 2+2?')])
print(response.content)
# Check trace at: https://smith.langchain.com

실행 메타데이터 추가

추적 기록에 태그와 메타데이터를 추가하면 LangSmith 사용자 인터페이스에서 필터링하고 검색할 수 있습니다. 다양한 에이전트 버전, 사용자 ID 또는 실험 레이블을 추적할 때 유용합니다.

import os
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
from langsmith import traceable

os.environ['LANGCHAIN_TRACING_V2'] = 'true'
os.environ['LANGCHAIN_API_KEY'] = 'ls__your-key'
os.environ['LANGCHAIN_PROJECT'] = 'my-agent-project'

llm = ChatOpenAI(model='gpt-4o-mini', api_key='sk-...')

@traceable(name='my-agent-run', tags=['production', 'v2'], metadata={'user_id': '42'})
def run_agent(question: str) -> str:
    response = llm.invoke(
        [HumanMessage(content=question)],
        config={
            'run_name': f'agent-{question[:20]}',
            'tags': ['production'],
            'metadata': {'user_id': '42', 'version': 'v2.1'}
        }
    )
    return response.content

result = run_agent('Explain LangChain tracing')
print(result)

LangSmith 사용자 인터페이스에서 추적 기록 보기

LangSmith 대시보드에서는 전체 추적 트리와 함께 모든 실행을 볼 수 있습니다. 각 노드에는 입력, 출력, 토큰 수, 지연 시간 및 모든 오류가 표시됩니다. 실행을 비교하고 태그나 프로젝트로 필터링할 수 있습니다.

  • 오류 상태로 필터링하여 실패한 실행 찾기
  • 지연 시간순으로 정렬하여 느린 단계 식별
  • 두 실행을 나란히 비교하여 성능 저하 디버깅
# Programmatically query LangSmith for run data
from langsmith import Client

client = Client(api_key='ls__your-key')

# List recent runs for a project
runs = list(client.list_runs(
    project_name='my-agent-project',
    execution_order=1,      # Top-level runs only
    error=True,             # Only failed runs
    limit=10
))

for run in runs:
    print(f'Run: {run.name}')
    print(f'  Status: {run.status}')
    print(f'  Latency: {run.end_time - run.start_time if run.end_time else "running"}')
    print(f'  Error: {run.error}')
    print()

사용자 지정 추적을 위한 Langfuse

Langfuse는 LangSmith의 오픈 소스 대안입니다. 모든 LLM 프레임워크 또는 사용자 지정 코드와 함께 사용할 수 있습니다. Langfuse SDK를 사용하여 추적 기록과 스팬을 수동으로 생성하십시오.

from langfuse import Langfuse

lf = Langfuse(
    public_key='pk-lf-...',
    secret_key='sk-lf-...',
    host='https://cloud.langfuse.com'  # Or your self-hosted URL
)

# Create a trace
trace = lf.trace(
    name='email-agent-run',
    user_id='user-42',
    metadata={'environment': 'production'}
)

# Create a span for entity extraction
span = trace.span(
    name='entity-extraction',
    input={'text': 'Meeting with Alice from Google tomorrow'}
)

# Simulate work
extracted = ['Alice', 'Google']

# End the span with output
span.end(output={'entities': extracted})

print('Trace created in Langfuse')
print(f'View at: https://cloud.langfuse.com/trace/{trace.id}')

Langfuse에서 LLM 호출 추적

각 LLM 호출마다 generation 스팬을 생성하십시오. 이 스팬에는 사용한 모델, 프롬프트, 완성 결과 및 토큰 수가 기록되며, 이는 비용 분석에 가장 중요한 데이터입니다.

from langfuse import Langfuse
import openai

lf = Langfuse(public_key='pk-lf-...', secret_key='sk-lf-...')
client = openai.OpenAI(api_key='sk-...')

def traced_llm_call(trace, prompt: str, model: str = 'gpt-4o-mini') -> str:
    generation = trace.generation(
        name='llm-call',
        model=model,
        input=[{'role': 'user', 'content': prompt}]
    )
    
    response = client.chat.completions.create(
        model=model,
        messages=[{'role': 'user', 'content': prompt}]
    )
    content = response.choices[0].message.content
    
    generation.end(
        output=content,
        usage={
            'prompt_tokens': response.usage.prompt_tokens,
            'completion_tokens': response.usage.completion_tokens,
            'total_tokens': response.usage.total_tokens
        }
    )
    return content

trace = lf.trace(name='test-trace')
result = traced_llm_call(trace, 'What is the capital of France?')
print('Result:', result)

오류 및 지연 시간별 실행 필터링

LangSmith 클라이언트를 사용하면 문제가 있는 실행을 프로그래밍 방식으로 찾을 수 있습니다. 오류 상태, 지연 시간 임계값 또는 특정 태그로 필터링하여 디버깅 작업에 집중하십시오.

from langsmith import Client
from datetime import datetime, timedelta

client = Client(api_key='ls__your-key')

def find_slow_runs(project: str, latency_threshold_ms: int = 10000):
    runs = list(client.list_runs(
        project_name=project,
        execution_order=1,
        start_time=datetime.utcnow() - timedelta(hours=24)
    ))
    
    slow_runs = []
    for run in runs:
        if run.end_time and run.start_time:
            duration_ms = (run.end_time - run.start_time).total_seconds() * 1000
            if duration_ms > latency_threshold_ms:
                slow_runs.append({
                    'id': str(run.id),
                    'name': run.name,
                    'duration_ms': round(duration_ms),
                    'tags': run.tags
                })
    
    slow_runs.sort(key=lambda x: x['duration_ms'], reverse=True)
    return slow_runs

print('Find slow runs function defined')
print('Usage: find_slow_runs("my-agent-project", latency_threshold_ms=5000)')

실행 비교

LangSmith를 사용하면 사용자 인터페이스에서 두 실행을 비교하여 무엇이 변경되었는지 확인할 수 있습니다. 프로그래밍 방식으로 실행 출력, 토큰 사용량 및 지연 시간을 비교하여 모델이나 프롬프트를 변경한 후 성능 저하를 감지할 수 있습니다.

from langsmith import Client

client = Client(api_key='ls__your-key')

def compare_runs(run_id_1: str, run_id_2: str) -> dict:
    run1 = client.read_run(run_id_1)
    run2 = client.read_run(run_id_2)
    
    def get_tokens(run):
        if run.total_tokens:
            return run.total_tokens
        return 0
    
    def get_latency_ms(run):
        if run.end_time and run.start_time:
            return (run.end_time - run.start_time).total_seconds() * 1000
        return 0
    
    return {
        'run1': {'id': run_id_1, 'tokens': get_tokens(run1), 'latency_ms': get_latency_ms(run1), 'status': run1.status},
        'run2': {'id': run_id_2, 'tokens': get_tokens(run2), 'latency_ms': get_latency_ms(run2), 'status': run2.status},
        'token_delta': get_tokens(run2) - get_tokens(run1),
        'latency_delta_ms': get_latency_ms(run2) - get_latency_ms(run1)
    }

print('Run comparison function defined')

점수 및 피드백 추가

에이전트 실행을 수동 또는 자동으로 평가한 후 추적 기록에 점수나 피드백을 추가하십시오. 이를 통해 미세 조정이나 프롬프트 변경 평가에 사용할 데이터 세트를 만들 수 있습니다.

from langsmith import Client

client = Client(api_key='ls__your-key')

def score_run(run_id: str, score: float, reasoning: str = ''):
    # score: 0.0 (bad) to 1.0 (perfect)
    client.create_feedback(
        run_id=run_id,
        key='quality',
        score=score,
        comment=reasoning
    )

def auto_evaluate_run(run_id: str, expected_output: str, actual_output: str) -> float:
    # Simple heuristic: check if key terms from expected output are present
    expected_terms = set(expected_output.lower().split())
    actual_terms = set(actual_output.lower().split())
    overlap = len(expected_terms & actual_terms) / max(len(expected_terms), 1)
    score = min(1.0, overlap * 1.5)  # Normalize
    score_run(run_id, score, f'Term overlap: {overlap:.2f}')
    return score

print('Scoring functions defined')
print('Example: score_run("run-id-abc", 0.85, "Good answer but missing one detail")')

구조화된 추적 컨텍스트

세션 ID, 사용자 ID, 에이전트 버전 및 기능 플래그와 같은 의미 있는 컨텍스트를 추적 기록에 연결하십시오. 그러면 추적 기록을 쉽게 세분화하고 다양한 구성에서 성능을 비교할 수 있습니다.

import os
from langsmith import traceable
from langchain_core.runnables import RunnableConfig

def build_trace_config(user_id: str, session_id: str, version: str) -> dict:
    return {
        'metadata': {
            'user_id': user_id,
            'session_id': session_id,
            'agent_version': version,
            'environment': os.environ.get('ENV', 'development')
        },
        'tags': [version, os.environ.get('ENV', 'development')],
        'run_name': f'agent-{user_id[:8]}'
    }

@traceable
def run_agent_with_context(question: str, user_id: str, session_id: str):
    config = build_trace_config(user_id, session_id, 'v2.3')
    # Pass config to any LangChain component
    # llm.invoke([HumanMessage(content=question)], config=config)
    print(f'Running agent for user {user_id}, session {session_id}')
    return 'Answer here'

result = run_agent_with_context('Question', 'user-001', 'sess-xyz')
print(result)

경보 설정

LangSmith 또는 Langfuse에서 경보를 설정하여 에이전트 상태를 모니터링하십시오. 오류율이 임계값을 초과하거나 P99 지연 시간이 급증하거나 특정 단계가 지속적으로 실패할 때 경보를 보내십시오.

from langsmith import Client
from datetime import datetime, timedelta

client = Client(api_key='ls__your-key')

def check_error_rate(project: str, window_minutes: int = 60, threshold: float = 0.05) -> dict:
    runs = list(client.list_runs(
        project_name=project,
        execution_order=1,
        start_time=datetime.utcnow() - timedelta(minutes=window_minutes)
    ))
    
    if not runs:
        return {'error_rate': 0.0, 'alert': False}
    
    error_count = sum(1 for r in runs if r.status == 'error')
    error_rate = error_count / len(runs)
    
    if error_rate > threshold:
        print(f'ALERT: Error rate {error_rate:.1%} exceeds threshold {threshold:.1%}')
        # Send to Slack/PagerDuty here
    
    return {
        'total_runs': len(runs),
        'error_count': error_count,
        'error_rate': round(error_rate, 4),
        'alert': error_rate > threshold
    }

print('Error rate monitor defined')

이해도 확인: 추적

LangSmith와 Langfuse를 사용한 에이전트 추적에 대한 이해도를 확인합니다.

추적 요약

LangSmith와 Langfuse는 서로 보완적인 도구입니다. LangSmith는 LangChain과 긴밀하게 통합되고 설정이 거의 필요하지 않은 반면, Langfuse는 어떤 프레임워크와도 사용할 수 있으며 더 많은 제어 권한을 제공합니다. 두 도구 모두 모든 에이전트 단계의 입력, 출력, 토큰 사용량, 지연 시간 및 오류를 기록합니다. 운영 환경에서 에이전트 품질을 유지하려면 필터링, 점수 부여 및 경보를 사용하십시오.

자주 묻는 질문

“LangSmith와 Langfuse를 활용한 추적 분석” 강의는 무료인가요?

네 — “LangSmith와 Langfuse를 활용한 추적 분석” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents 강의 전체를 잠금 해제할 수 있습니다. AI Agents 강의에는 총 4개의 강의가 포함되어 있습니다.

“LangSmith와 Langfuse를 활용한 추적 분석”에서 뭘 배우나요?

추적 기록을 읽고 느린 도구, 잘못된 결정, 오류 패턴을 식별합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Agents을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“LangSmith와 Langfuse를 활용한 추적 분석” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Agents 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Agents 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. LangSmith와 Langfuse를 활용한 추적 분석
  2. 단계별 토큰 및 비용 프로파일링
  3. 느리고 비용이 많이 드는 단계 식별
  4. 에이전트 실패의 근본 원인 분석
← AI Agents(으)로 돌아가기