Python调用AnthropicAPI的两种方式

Written by

in

文章目录
  • Anthropic API 本质是标准 HTTP 接口,Python 中通常有两种主流调用方式: 使用 requests:轻量、灵活、适合工程封装 使用官方 SDK:封装完善、自动处理部分配置 下文对两种方式进行对比与示例说明。
  • 目录
    • Python 调用 Anthropic API 的两种方式
      • 一、使用 requests 调用(适合生产环境工程封装)
        • 1. 基本非流式调用
        • 2. 流式响应(SSE Stream)
        • 3. 使用毫秒超时(API_TIMEOUT_MS)
      • 二、使用官方 SDK 调用(简单、封装完善)
        • 1. 基本调用
        • 2. 流式调用(逐 token 输出)
      • 三、两种方式对比

       本文介绍了Python调用Anthropic API的两种主要方式,包括

      • requests 调用
      • 官方 SDK 调用
      https://api-docs.deepseek.com/zh-cn/guides/anthropic_api
      

      Anthropic API 本质是标准 HTTP 接口,Python 中通常有两种主流调用方式:

      1. 使用 requests:轻量、灵活、适合工程封装
      2. 使用官方 SDK:封装完善、自动处理部分配置

      下文对两种方式进行对比与示例说明。

      requests 是 Python 最通用的 HTTP 客户端,适合你在框架(Django / FastAPI / 微服务)中封装统一的 AI 调用模块。

      import requests
      
      API_KEY = "YOUR_API_KEY"
      BASE_URL = "https://api.deepseek.com/anthropic/v1/messages"
      
      headers = {
          "Content-Type": "application/json",
          "x-api-key": API_KEY,
          "anthropic-version": "2023-06-01",
      }
      
      payload = {
          "model": "deepseek-chat",
          "max_tokens": 2048,
          "messages": [{"role": "user", "content": "你好"}],
      }
      
      resp = requests.post(BASE_URL, json=payload, headers=headers, timeout=600)
      print(resp.json())
      

      import requests
      import json
      
      API_KEY = "YOUR_API_KEY"
      BASE_URL = "https://api.deepseek.com/anthropic/v1/messages"
      
      headers = {
          "Content-Type": "application/json",
          "x-api-key": API_KEY,
          "anthropic-version": "2023-06-01",
      }
      
      payload = {
          "model": "deepseek-chat",
          "max_tokens": 2000,
          "messages": [{"role": "user", "content": "介绍一下你自己"}],
          "stream": True,
      }
      
      with requests.post(BASE_URL, json=payload, headers=headers, stream=True, timeout=600) as r:
          for line in r.iter_lines():
              if not line:
                  continue
              data = line.decode("utf-8")
              if data.startswith("data: "):
                  content = data[6:]
                  if content == "[DONE]":
                      break
                  event = json.loads(content)
                  delta = event.get("delta", {}).get("text")
                  if delta:
                      print(delta, end="", flush=True)
      

      Anthropic 配置通常使用毫秒,需要转成秒:

      API_TIMEOUT_MS = 600000
      requests.post(url, json=payload, headers=headers, timeout=API_TIMEOUT_MS / 1000)
      

      Anthropic 提供官方 Python SDK,支持自动处理 headers、base_url、超时管理等。

      安装:

      pip install anthropic
      

      from anthropic import Anthropic
      
      client = Anthropic(
          api_key="YOUR_API_KEY",
          base_url="https://api.deepseek.com/anthropic",
          timeout=600,
      )
      
      resp = client.messages.create(
          model="deepseek-chat",
          max_tokens=2048,
          messages=[{"role": "user", "content": "你好"}],
      )
      
      print(resp)
      

      from anthropic import Anthropic
      
      client = Anthropic(
          api_key="YOUR_API_KEY",
          base_url="https://api.deepseek.com/anthropic",
      )
      
      with client.messages.stream(
          model="deepseek-chat",
          max_tokens=2048,
          messages=[{"role": "user", "content": "写一段话"}],
      ) as stream:
          for event in stream:
              if event.type == "message_delta" and event.delta.text:
                  print(event.delta.text, end="", flush=True)
      

      对比项 requests 官方 SDK
      轻量性
      灵活度 高(可自由封装)
      上手难度 需要写 headers、处理 SSE 简单直接
      流式支持 需要手动解析 SSE 官方封装
      配置管理(base_url、timeout) 手动控制 构造参数即可
      适合场景 生产级 API 服务、统一调用层 技术验证、快速开发

      两种方式都稳定可靠,你可以针对团队习惯选择合适的方式。

      到此这篇关于Python 调用Anthropic API 的两种方式的文章就介绍到这了,更多相关Python调用 Anthropic API 内容请搜索风君子博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持风君子博客!

      您可能感兴趣的文章:

      • python 调用API接口 获取和解析 Json数据
      • python调用新浪微博API项目实践
      • Python调用ChatGPT API接口的用法详解
      • python调用api实例讲解
      • python 调用有道api接口的方法
      • python爬虫之百度API调用方法
      • python调用windows api锁定计算机示例
      • python如何实现API的调用详解
      • Python使用Flask调用API接口的方法

      站内搜索