import json
import os
import sys
import anthropic

key = os.environ.get('ANTHROPIC_API_KEY')
if not key:
    raise SystemExit('请先设置关联 Console 组织的 workspace 范围 API key。')

# Requires the tutorial's clean environment and a current official SDK.
# Retries are off for this single diagnostic request.
client = anthropic.Anthropic(
    api_key=key,
    base_url='https://api.anthropic.com',
    timeout=30.0,
    max_retries=0,
)

try:
    raw = client.messages.with_raw_response.create(
        model='claude-haiku-5-5',
        max_tokens=128,
        thinking={'type': 'disabled'},
        output_config={'effort': 'low'},
        messages=[{'role': 'user', 'content': '只回复：API连接成功'}],
    )
    message = raw.parse()  # Parse the response already received, not a second request.
    for name in ('request-id', 'anthropic-organization-id', 'anthropic-workspace-id'):
        print(name+':', raw.headers.get(name, '(not returned)'))
    print('model:', message.model)
    print('stop_reason:', message.stop_reason)
    print('text:', '\n'.join(block.text for block in message.content if block.type == 'text'))
    print('usage:', json.dumps(message.usage.model_dump(), ensure_ascii=False))
except anthropic.APIStatusError as exc:
    print(f'HTTP {exc.status_code}; request-id={exc.request_id}', file=sys.stderr)
    raise SystemExit(1)
except anthropic.APIConnectionError:
    print('连接或超时未完成；先核对记录和网络，再决定是否重试。', file=sys.stderr)
    raise SystemExit(1)
finally:
    client.close()
