Anthropic

Anthropic

AgentOps로 Anthropic API 호출을 추적하고 분석하는 방법을 소개해요. 설치부터 API 키 설정, 기본 사용법과 스트리밍·도구 사용 예제까지 알아볼게요.

출처: 문서

본문

AgentOps는 Anthropic의 Python SDK와 원활하게 통합되어, 모든 Claude 모델 상호작용을 자동으로 추적하고 분석할 수 있게 해줍니다.

설치 (Installation)

```bash pip theme={null} pip install agentops anthropic ```
poetry add agentops anthropic
uv pip install agentops anthropic

API 키 설정 (Setting Up API Keys)

Anthropic을 AgentOps와 함께 사용하기 전에 API 키를 설정해야 해요. 다음을 얻을 수 있습니다.

그런 다음 환경 변수로 내보내거나 .env 파일에 설정할 수 있어요.

```bash Export to CLI theme={null} export ANTHROPIC_API_KEY="your_anthropic_api_key_here" export AGENTOPS_API_KEY="your_agentops_api_key_here" ```
ANTHROPIC_API_KEY="your_anthropic_api_key_here"
AGENTOPS_API_KEY="your_agentops_api_key_here"

그리고 Python 코드에서 환경 변수를 로드합니다.

from dotenv import load_dotenv
import os

# Load environment variables from .env file
load_dotenv()

# Set up environment variables with fallback values
os.environ["ANTHROPIC_API_KEY"] = os.getenv("ANTHROPIC_API_KEY")
os.environ["AGENTOPS_API_KEY"] = os.getenv("AGENTOPS_API_KEY")

사용법 (Usage)

애플리케이션 시작 시 AgentOps를 초기화하면 모든 Anthropic API 호출이 자동으로 추적됩니다.

import agentops
import anthropic

# Initialize AgentOps
agentops.init()

# Create Anthropic client
client = anthropic.Anthropic()

# Make a completion request - AgentOps will track it automatically
message = client.messages.create(
    model="claude-sonnet-4-20250514",
    messages=[
        {"role": "user", "content": "What is artificial intelligence?"}
    ]
)

# Print the response received
print(message.content[0].text)

예제 (Examples)

```python Streaming theme={null} import agentops import anthropic

Initialize AgentOps

agentops.init()

Create Anthropic client

client = anthropic.Anthropic()

Make a streaming request

with client.messages.stream( model="claude-sonnet-4-20250514", messages=[ {"role": "user", "content": "Write a short poem about artificial intelligence."} ] ) as stream: for text in stream.text_stream: print(text, end="", flush=True) print()


```python Tool Use theme={null}
import agentops
import anthropic
import json
from datetime import datetime

# Initialize AgentOps
agentops.init()

# Create Anthropic client
client = anthropic.Anthropic()

# Define tools
tools = [
    {
        "type": "custom",
        "name": "get_current_time",
        "description": "Get the current date and time",
        "input_schema": {
            "type": "object",
            "properties": {},
            "required": []
        }
    }
]

def get_current_time():
    return {"current_time": datetime.now().isoformat()}

# Make a request with tools
  message = client.messages.create(
    model="claude-opus-4-20250514",
    tools=tools,
    messages=[
        {"role": "user", "content": "What time is it now?"}
    ]
  )

# Handle tool use
if message.content[0].type == "tool_calls":
    tool_call = message.content[0].tool_calls[0]
    tool_name = tool_call.name
    
    if tool_name == "get_current_time":
        tool_response = get_current_time()
        
        # Continue the conversation with the tool response
        second_message = client.messages.create(
          model="claude-opus-4-20250514",
            messages=[
                {"role": "user", "content": "What time is it now?"},
                {
                    "role": "assistant",
                    "content": [
                        {
                            "type": "tool_calls",
                            "tool_calls": [
                                {
                                    "type": "custom",
                                    "name": "get_current_time",
                                    "input": {}
                                }
                            ]
                        }
                    ]
                },
                {
                    "role": "tool",
                    "content": json.dumps(tool_response),
                    "tool_call_id": tool_call.id
                }
            ]
      )

        print(second_message.content[0].text)
else:
    print(message.content[0].text)

더 많은 예제 (More Examples)

도구 사용과 고급 기능을 지원하는 Claude 통합 Anthropic SDK와 동기 호출을 보여줍니다. Anthropic SDK와 비동기 호출을 보여줍니다.

더 알아보기 (Learn more)