<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Messages API &#8211; 小人物看世界</title>
	<atom:link href="https://blog.che-ya.com/tag/messages-api/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.che-ya.com</link>
	<description>軟體工程師的技術筆記</description>
	<lastBuildDate>Wed, 08 Apr 2026 08:07:58 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://blog.che-ya.com/wp-content/uploads/2021/08/cropped-APP_icon-32x32.png</url>
	<title>Messages API &#8211; 小人物看世界</title>
	<link>https://blog.che-ya.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Anthropic Messages API 入門教學</title>
		<link>https://blog.che-ya.com/anthropic-messages-api-tutorial/</link>
		
		<dc:creator><![CDATA[ㄚ槌]]></dc:creator>
		<pubDate>Fri, 08 May 2026 03:39:00 +0000</pubDate>
				<category><![CDATA[Claude Code]]></category>
		<category><![CDATA[Anthropic API]]></category>
		<category><![CDATA[AI 編程工具]]></category>
		<category><![CDATA[Anthropic]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[Messages API]]></category>
		<guid isPermaLink="false">https://blog.che-ya.com/?p=892</guid>

					<description><![CDATA[Anthropic Messages API 是與 Claude 模型互動的核心介面。無論你是想在自己的應用程 ... <a title="Anthropic Messages API 入門教學" class="read-more" href="https://blog.che-ya.com/anthropic-messages-api-tutorial/" aria-label="Read more about Anthropic Messages API 入門教學">閱讀全文</a>]]></description>
										<content:encoded><![CDATA[
<p>Anthropic Messages API 是與 Claude 模型互動的核心介面。無論你是想在自己的應用程式中整合 AI 對話功能、建立智慧客服系統，還是進行大規模的文本處理，都需要透過 Messages API 來實現。本篇文章將從零開始，帶你了解 API 的基本概念、認證方式、請求格式、進階功能到費用計算，讓你能快速上手 Anthropic 的 Claude API。</p>



<h2 class="wp-block-heading">什麼是 Anthropic Messages API</h2>



<p>Anthropic Messages API（端點路徑為 <code>/v1/messages</code>）是 Anthropic 官方提供的 RESTful API，用於與 Claude 系列模型進行對話互動。它採用「訊息」的結構來組織對話，每個請求包含一組 <code>messages</code> 陣列，Claude 會根據對話脈絡生成回應。</p>



<p>與直接使用 Claude 網頁介面或 Claude Code CLI 不同，Messages API 讓開發者能以程式化的方式呼叫 Claude，適合以下場景：</p>



<ul class="wp-block-list">
<li><strong>應用程式整合</strong>：在你的 Web App、Mobile App 或後端服務中嵌入 AI 功能</li>



<li><strong>自動化工作流</strong>：搭配 CI/CD、排程任務或事件驅動架構進行批次處理</li>



<li><strong>客製化體驗</strong>：透過 System Prompt 與參數調校，打造專屬的 AI 互動行為</li>



<li><strong>多模態處理</strong>：傳送圖片、PDF 等非文字內容給 Claude 進行分析</li>
</ul>



<h2 class="wp-block-heading">API Key 取得與設定</h2>



<h3 class="wp-block-heading">取得 API Key</h3>



<p>要使用 Anthropic Messages API，首先需要在 <a href="https://console.anthropic.com/" target="_blank" rel="noopener nofollow">Anthropic Console</a> 註冊帳號並建立 API Key：</p>



<ol class="wp-block-list">
<li>前往 <a href="https://console.anthropic.com/" target="_blank" rel="noopener nofollow">console.anthropic.com</a> 並完成註冊</li>



<li>進入 <strong>Settings → API Keys</strong> 頁面</li>



<li>點擊 <strong>Create Key</strong>，輸入名稱後產生金鑰</li>



<li>立即複製並安全保存（金鑰只會顯示一次）</li>
</ol>



<h3 class="wp-block-heading">設定環境變數</h3>



<p>取得 API Key 後，建議將它設定為環境變數，避免在程式碼中明文儲存：</p>



<pre class="wp-block-code"><code lang="" class=""># Linux / macOS
export ANTHROPIC_API_KEY="sk-ant-api03-xxxxxxxxxxxxxxxx"

# Windows PowerShell
$env:ANTHROPIC_API_KEY = "sk-ant-api03-xxxxxxxxxxxxxxxx"

# 或寫入 .env 檔案（搭配 dotenv 套件使用）
ANTHROPIC_API_KEY=sk-ant-api03-xxxxxxxxxxxxxxxx</code></pre>



<p>⚠️ <strong>安全提醒</strong>：永遠不要將 API Key 提交到 Git 儲存庫。請確保 <code>.env</code> 檔案已加入 <code>.gitignore</code>。</p>



<h2 class="wp-block-heading">Messages API 基本呼叫</h2>



<h3 class="wp-block-heading">使用 curl 呼叫</h3>



<p>最基本的方式是透過 curl 直接發送 HTTP 請求：</p>



<pre class="wp-block-code"><code class="">curl https://api.anthropic.com/v1/messages \
  -H "content-type: application/json" \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -d '{
    "model": "claude-sonnet-4-6-20250514",
    "max_tokens": 1024,
    "messages": [
      {
        "role": "user",
        "content": "請用一句話解釋什麼是 API"
      }
    ]
  }'</code></pre>



<p>其中 <code>anthropic-version</code> 是必要的 Header，用於指定 API 版本。目前最新的穩定版本為 <code>2023-06-01</code>。</p>



<h3 class="wp-block-heading">使用 Python SDK</h3>



<p>Anthropic 官方提供了 Python SDK，讓呼叫更加簡潔：</p>



<pre class="wp-block-code"><code class=""># 安裝 SDK
pip install anthropic

# 基本呼叫
import anthropic

client = anthropic.Anthropic()  # 自動讀取 ANTHROPIC_API_KEY 環境變數

message = client.messages.create(
    model="claude-sonnet-4-6-20250514",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "請用一句話解釋什麼是 API"}
    ]
)

print(message.content[0].text)</code></pre>



<h3 class="wp-block-heading">使用 TypeScript SDK</h3>



<p>前端或 Node.js 開發者可以使用 TypeScript SDK：</p>



<pre class="wp-block-code"><code class="">// 安裝 SDK
npm install @anthropic-ai/sdk

// 基本呼叫
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();  // 自動讀取 ANTHROPIC_API_KEY 環境變數

const message = await client.messages.create({
  model: "claude-sonnet-4-6-20250514",
  max_tokens: 1024,
  messages: [
    { role: "user", content: "請用一句話解釋什麼是 API" }
  ],
});

console.log(message.content[0].text);</code></pre>



<h2 class="wp-block-heading">請求與回應格式</h2>



<h3 class="wp-block-heading">請求格式（Request）</h3>



<p>一個完整的 Messages API 請求包含以下欄位：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>參數</th><th>類型</th><th>必填</th><th>說明</th></tr></thead><tbody><tr><td><code>model</code></td><td>string</td><td>✅</td><td>使用的模型 ID，例如 <code>claude-sonnet-4-6-20250514</code></td></tr><tr><td><code>max_tokens</code></td><td>integer</td><td>✅</td><td>回應的最大 Token 數量</td></tr><tr><td><code>messages</code></td><td>array</td><td>✅</td><td>對話訊息陣列，包含 role 與 content</td></tr><tr><td><code>system</code></td><td>string</td><td>❌</td><td>System Prompt，定義 Claude 的行為角色</td></tr><tr><td><code>temperature</code></td><td>float</td><td>❌</td><td>隨機性控制，範圍 0.0 ~ 1.0，預設 1.0</td></tr><tr><td><code>stream</code></td><td>boolean</td><td>❌</td><td>是否啟用串流回應，預設 false</td></tr><tr><td><code>stop_sequences</code></td><td>array</td><td>❌</td><td>自訂停止序列，遇到時停止生成</td></tr><tr><td><code>metadata</code></td><td>object</td><td>❌</td><td>附加資訊，例如 <code>user_id</code> 用於追蹤</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">回應格式（Response）</h3>



<p>成功的 API 回應範例如下：</p>



<pre class="wp-block-code"><code class="">{
  "id": "msg_01XFDUDYJgAACzvnptvVoYEL",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "API（Application Programming Interface）是一組定義好的規則和協議，讓不同的軟體系統之間能夠互相溝通和交換資料。"
    }
  ],
  "model": "claude-sonnet-4-6-20250514",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 22,
    "output_tokens": 65,
    "cache_creation_input_tokens": 0,
    "cache_read_input_tokens": 0
  }
}</code></pre>



<p>回應中的 <code>usage</code> 欄位特別重要，它記錄了此次請求消耗的 Token 數量，直接關係到 API 費用。<code>stop_reason</code> 則告訴你 Claude 停止生成的原因，常見值包括 <code>end_turn</code>（正常結束）、<code>max_tokens</code>（達到上限）和 <code>stop_sequence</code>（遇到停止序列）。</p>



<h2 class="wp-block-heading">模型選擇</h2>



<p>Anthropic 目前提供三個主要的 Claude 模型系列，各有不同的定位與適用場景：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>模型</th><th>模型 ID</th><th>定位</th><th>上下文視窗</th><th>適用場景</th></tr></thead><tbody><tr><td><strong>Claude Opus 4.6</strong></td><td><code>claude-opus-4-6-20250514</code></td><td>最強大</td><td>1M tokens</td><td>複雜推理、程式開發、研究分析</td></tr><tr><td><strong>Claude Sonnet 4.6</strong></td><td><code>claude-sonnet-4-6-20250514</code></td><td>平衡型</td><td>1M tokens</td><td>日常開發、內容生成、資料處理</td></tr><tr><td><strong>Claude Haiku 4.5</strong></td><td><code>claude-haiku-4-5-20251001</code></td><td>最快速</td><td>200K tokens</td><td>即時回應、分類任務、輕量處理</td></tr></tbody></table></figure>



<p>選擇模型時，建議從 <strong>Claude Sonnet 4.6</strong> 開始，它在效能與成本之間取得了很好的平衡。如果需要處理高度複雜的任務（如大型程式碼分析、學術研究），再升級到 Opus；若追求極致速度與低成本，則可以選擇 Haiku。</p>



<h2 class="wp-block-heading">Streaming 串流回應</h2>



<p>預設情況下，Messages API 會等到 Claude 生成完整回應後才回傳結果。對於較長的回應，這可能需要等待數秒。串流（Streaming）模式可以讓回應即時逐步回傳，大幅提升使用者體驗。</p>



<h3 class="wp-block-heading">Python 串流範例</h3>



<pre class="wp-block-code"><code class="">import anthropic

client = anthropic.Anthropic()

# 使用 stream 參數
with client.messages.stream(
    model="claude-sonnet-4-6-20250514",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "請詳細解釋 RESTful API 的設計原則"}
    ]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)</code></pre>



<h3 class="wp-block-heading">TypeScript 串流範例</h3>



<pre class="wp-block-code"><code class="">import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

const stream = client.messages.stream({
  model: "claude-sonnet-4-6-20250514",
  max_tokens: 1024,
  messages: [
    { role: "user", content: "請詳細解釋 RESTful API 的設計原則" }
  ],
});

for await (const event of stream) {
  if (event.type === "content_block_delta" &amp;&amp; event.delta.type === "text_delta") {
    process.stdout.write(event.delta.text);
  }
}</code></pre>



<p>串流模式在以下場景特別有用：聊天介面需要即時顯示回應、長文本生成需要給使用者即時回饋、以及需要在回應過程中進行前端處理的應用。</p>



<h2 class="wp-block-heading">多模態輸入：圖片與 PDF</h2>



<p>Claude 不只能處理文字，還支援圖片和 PDF 等多模態輸入。你可以透過 Base64 編碼或 URL 的方式傳送圖片，讓 Claude 進行視覺理解與分析。</p>



<h3 class="wp-block-heading">傳送圖片</h3>



<pre class="wp-block-code"><code class="">import anthropic
import base64

client = anthropic.Anthropic()

# 方法一：Base64 編碼
with open("screenshot.png", "rb") as f:
    image_data = base64.standard_b64encode(f.read()).decode("utf-8")

message = client.messages.create(
    model="claude-sonnet-4-6-20250514",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": "image/png",
                        "data": image_data
                    }
                },
                {
                    "type": "text",
                    "text": "請描述這張圖片的內容"
                }
            ]
        }
    ]
)

# 方法二：URL 方式
message = client.messages.create(
    model="claude-sonnet-4-6-20250514",
    max_tokens=1024,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "url",
                        "url": "https://example.com/image.png"
                    }
                },
                {
                    "type": "text",
                    "text": "這張圖表顯示了什麼趨勢？"
                }
            ]
        }
    ]
)</code></pre>



<h3 class="wp-block-heading">傳送 PDF 文件</h3>



<p>Claude 也支援 PDF 文件的解析與理解：</p>



<pre class="wp-block-code"><code class="">import anthropic
import base64

client = anthropic.Anthropic()

with open("report.pdf", "rb") as f:
    pdf_data = base64.standard_b64encode(f.read()).decode("utf-8")

message = client.messages.create(
    model="claude-sonnet-4-6-20250514",
    max_tokens=4096,
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "document",
                    "source": {
                        "type": "base64",
                        "media_type": "application/pdf",
                        "data": pdf_data
                    }
                },
                {
                    "type": "text",
                    "text": "請摘要這份文件的重點"
                }
            ]
        }
    ]
)</code></pre>



<p>支援的圖片格式包括 JPEG、PNG、GIF、WebP，單張圖片建議不超過 5MB。PDF 文件則支援最多數百頁的內容。</p>



<h2 class="wp-block-heading">System Prompt：定義 Claude 的行為</h2>



<p>System Prompt 是控制 Claude 回應風格、角色設定與行為規範的核心機制。它會在對話開始前設定 Claude 的「角色」，影響後續所有回應的風格與內容。</p>



<pre class="wp-block-code"><code class="">import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-sonnet-4-6-20250514",
    max_tokens=1024,
    system="你是一位資深的台灣軟體工程師，專精於 Python 和 TypeScript。回答時請使用繁體中文，並提供實際的程式碼範例。遇到最佳實踐相關的問題時，請同時說明為什麼這樣做比較好。",
    messages=[
        {"role": "user", "content": "如何在 Python 中安全地處理 API 金鑰？"}
    ]
)</code></pre>



<p>善用 System Prompt 的幾個技巧：明確定義角色與專業領域、指定回應的語言和格式、設定安全邊界限制回應範圍、以及提供特定的指示來引導輸出品質。</p>



<h2 class="wp-block-heading">Temperature 與 Max Tokens</h2>



<h3 class="wp-block-heading">Temperature（溫度）</h3>



<p><code>temperature</code> 控制回應的隨機性與創造性，範圍從 0.0 到 1.0：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>溫度值</th><th>特性</th><th>適用場景</th></tr></thead><tbody><tr><td><code>0.0</code></td><td>最確定性，回應最一致</td><td>程式碼生成、資料擷取、分類任務</td></tr><tr><td><code>0.3 ~ 0.5</code></td><td>略有變化但仍穩定</td><td>技術文件撰寫、問答系統</td></tr><tr><td><code>0.7 ~ 0.8</code></td><td>較有創意與多樣性</td><td>文案撰寫、腦力激盪</td></tr><tr><td><code>1.0</code>（預設）</td><td>最大隨機性</td><td>創意寫作、故事生成</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">Max Tokens</h3>



<p><code>max_tokens</code> 是<strong>必填參數</strong>，用於限制 Claude 回應的最大長度。這一點與 OpenAI API 不同，Anthropic 要求開發者必須明確指定此值。</p>



<pre class="wp-block-code"><code class=""># 不同場景的 max_tokens 建議值
# 簡短回答（分類、是否判斷）：256 ~ 512
# 一般對話：1024 ~ 2048
# 長文生成（文章、報告）：4096 ~ 8192
# 完整程式碼生成：8192 ~ 16384

message = client.messages.create(
    model="claude-sonnet-4-6-20250514",
    max_tokens=4096,
    temperature=0.3,  # 較低溫度適合技術內容
    messages=[
        {"role": "user", "content": "請撰寫一個 FastAPI 的 CRUD 範例"}
    ]
)</code></pre>



<p>注意：如果回應被截斷（<code>stop_reason</code> 為 <code>max_tokens</code>），表示你設定的值太小。可以透過檢查 <code>stop_reason</code> 來判斷是否需要調高。</p>



<h2 class="wp-block-heading">錯誤處理</h2>



<p>在生產環境中使用 API 時，完善的錯誤處理至關重要。以下是常見的錯誤類型與處理方式：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>HTTP 狀態碼</th><th>錯誤類型</th><th>常見原因</th><th>處理建議</th></tr></thead><tbody><tr><td>400</td><td>invalid_request_error</td><td>請求格式錯誤、缺少必填欄位</td><td>檢查請求參數是否正確</td></tr><tr><td>401</td><td>authentication_error</td><td>API Key 無效或過期</td><td>確認 API Key 設定正確</td></tr><tr><td>403</td><td>permission_error</td><td>帳號權限不足</td><td>檢查帳號狀態與用量限制</td></tr><tr><td>429</td><td>rate_limit_error</td><td>超過速率限制</td><td>實作指數退避重試（Exponential Backoff）</td></tr><tr><td>500</td><td>api_error</td><td>Anthropic 伺服器錯誤</td><td>等待後重試</td></tr><tr><td>529</td><td>overloaded_error</td><td>API 服務過載</td><td>稍後重試，搭配退避策略</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">Python 錯誤處理範例</h3>



<pre class="wp-block-code"><code class="">import anthropic
import time

client = anthropic.Anthropic()

def call_claude_with_retry(messages, max_retries=3):
    """帶有重試機制的 API 呼叫"""
    for attempt in range(max_retries):
        try:
            response = client.messages.create(
                model="claude-sonnet-4-6-20250514",
                max_tokens=1024,
                messages=messages
            )
            return response
        except anthropic.RateLimitError:
            wait_time = 2 ** attempt  # 指數退避：1, 2, 4 秒
            print(f"速率限制，等待 {wait_time} 秒後重試...")
            time.sleep(wait_time)
        except anthropic.APIStatusError as e:
            print(f"API 錯誤 {e.status_code}: {e.message}")
            if e.status_code >= 500:
                time.sleep(2 ** attempt)
                continue
            raise  # 4xx 錯誤不重試
        except anthropic.APIConnectionError:
            print("連線失敗，檢查網路狀態...")
            time.sleep(2 ** attempt)
    
    raise Exception("已達最大重試次數")

# 使用範例
result = call_claude_with_retry([
    {"role": "user", "content": "Hello, Claude!"}
])</code></pre>



<h2 class="wp-block-heading">費用計算</h2>



<p>Anthropic API 採用按量付費（Pay-as-you-go）模式，依照輸入與輸出的 Token 數量分別計費。以下是截至 2026 年的最新定價：</p>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>模型</th><th>輸入（每百萬 Tokens）</th><th>輸出（每百萬 Tokens）</th><th>快取讀取</th></tr></thead><tbody><tr><td><strong>Claude Opus 4.6</strong></td><td>$15.00</td><td>$75.00</td><td>$1.50</td></tr><tr><td><strong>Claude Sonnet 4.6</strong></td><td>$3.00</td><td>$15.00</td><td>$0.30</td></tr><tr><td><strong>Claude Haiku 4.5</strong></td><td>$1.00</td><td>$5.00</td><td>$0.10</td></tr></tbody></table></figure>



<h3 class="wp-block-heading">費用估算範例</h3>



<p>假設使用 Claude Sonnet 4.6，一次對話輸入 1,000 tokens、輸出 500 tokens，則費用為：</p>



<pre class="wp-block-code"><code class=""># 費用計算公式
# 費用 = (輸入 tokens × 輸入單價) + (輸出 tokens × 輸出單價)

# 範例：Claude Sonnet 4.6
input_tokens = 1000
output_tokens = 500

input_cost = (input_tokens / 1_000_000) * 3.00   # $0.003
output_cost = (output_tokens / 1_000_000) * 15.00  # $0.0075
total_cost = input_cost + output_cost               # $0.0105

# 每次對話約 $0.01（不到新台幣 1 元）
# 每天 100 次對話 ≈ $1.05/天 ≈ 約 NT$34/天</code></pre>



<h3 class="wp-block-heading">節省成本的技巧</h3>



<ul class="wp-block-list">
<li><strong>Prompt Caching</strong>：啟用快取功能，重複使用的 System Prompt 或長文本可節省最高 90% 的輸入成本</li>



<li><strong>Batch API</strong>：使用批次 API 處理非即時任務，可享 50% 折扣</li>



<li><strong>選擇合適的模型</strong>：不需要最強能力時，使用 Haiku 可大幅降低成本</li>



<li><strong>精簡 Prompt</strong>：避免在每次請求中傳送不必要的上下文</li>



<li><strong>設定合理的 max_tokens</strong>：根據實際需求設定，避免浪費</li>
</ul>



<h2 class="wp-block-heading">多輪對話</h2>



<p>Messages API 透過 <code>messages</code> 陣列來管理對話歷史。每次請求時，你需要將完整的對話紀錄傳送給 API，Claude 才能理解上下文：</p>



<pre class="wp-block-code"><code class="">import anthropic

client = anthropic.Anthropic()

# 維護對話歷史
conversation = []

def chat(user_message):
    """多輪對話函式"""
    conversation.append({
        "role": "user",
        "content": user_message
    })
    
    response = client.messages.create(
        model="claude-sonnet-4-6-20250514",
        max_tokens=1024,
        system="你是一位友善的繁體中文 AI 助理。",
        messages=conversation
    )
    
    assistant_message = response.content[0].text
    conversation.append({
        "role": "assistant",
        "content": assistant_message
    })
    
    return assistant_message

# 多輪對話範例
print(chat("我想學 Python，該從哪裡開始？"))
print(chat("你剛才提到的第一點，可以再詳細說明嗎？"))
print(chat("有推薦的學習資源嗎？"))</code></pre>



<p>注意：每次請求都會將完整的對話歷史作為輸入 Token 計費，因此長對話的成本會逐漸增加。在生產環境中，建議實作對話長度的管理機制，例如定期摘要或截斷較舊的訊息。</p>



<h2 class="wp-block-heading">延伸閱讀</h2>



<p>本篇文章涵蓋了 Anthropic Messages API 的基礎使用方式。要更深入地掌握 API 的各項功能，以下資源值得進一步探索：</p>



<ul class="wp-block-list">
<li><a href="https://docs.anthropic.com/en/api/messages" target="_blank" rel="noopener nofollow">Anthropic Messages API 官方文件</a> — 完整的 API 參考與參數說明</li>



<li><a href="https://docs.anthropic.com/en/api/messages-examples" target="_blank" rel="noopener nofollow">Messages API 範例集</a> — 官方提供的各種使用情境範例</li>



<li><a href="https://github.com/anthropics/anthropic-sdk-python" target="_blank" rel="noopener nofollow">Python SDK GitHub</a> — 官方 Python SDK 原始碼與文件</li>



<li><a href="https://github.com/anthropics/anthropic-sdk-typescript" target="_blank" rel="noopener nofollow">TypeScript SDK GitHub</a> — 官方 TypeScript SDK 原始碼與文件</li>



<li><a href="https://docs.anthropic.com/en/docs/build-with-claude/tool-use" target="_blank" rel="noopener nofollow">Tool Use（Function Calling）</a> — 讓 Claude 呼叫外部工具的進階功能</li>



<li><a href="https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching" target="_blank" rel="noopener nofollow">Prompt Caching</a> — 快取機制的詳細說明與最佳實踐</li>
</ul>



<h2 class="wp-block-heading">總結</h2>



<p>Anthropic Messages API 提供了一套設計清晰、功能完整的介面來與 Claude 模型互動。從最基本的文字對話、串流回應、多模態輸入，到 System Prompt 的角色設定與參數調校，每個功能都有其明確的使用場景。</p>



<p>對於剛入門的開發者，建議按照以下步驟開始：先在 Anthropic Console 取得 API Key，使用 Python 或 TypeScript SDK 發送第一個請求，觀察回應結構與 Token 使用量，然後逐步加入 System Prompt、調整 Temperature，最後根據實際需求啟用串流或多模態功能。</p>



<p>隨著你對 API 越來越熟悉，可以進一步探索 Tool Use（Function Calling）、Prompt Caching、Batch API 等進階功能，打造更強大且更具成本效益的 AI 應用。</p>
<div class="saboxplugin-wrap" itemtype="http://schema.org/Person" itemscope itemprop="author"><div class="saboxplugin-tab"><div class="saboxplugin-gravatar"><img alt='ㄚ槌' src='https://secure.gravatar.com/avatar/9914399915f96350f302945e8ddddee1a9b1995350182f513fd2e1fa816c100a?s=100&#038;d=mm&#038;r=g' srcset='https://secure.gravatar.com/avatar/9914399915f96350f302945e8ddddee1a9b1995350182f513fd2e1fa816c100a?s=200&#038;d=mm&#038;r=g 2x' class='avatar avatar-100 photo' height='100' width='100' itemprop="image"/></div><div class="saboxplugin-authorname"><a href="https://blog.che-ya.com/author/a3230230/" class="vcard author" rel="author"><span class="fn">ㄚ槌</span></a></div><div class="saboxplugin-desc"><div itemprop="description"></div></div><div class="saboxplugin-web "><a href="https://blog.che-ya.com" target="_self">blog.che-ya.com</a></div><div class="clearfix"></div></div></div><p><a class="a2a_button_facebook" href="https://www.addtoany.com/add_to/facebook?linkurl=https%3A%2F%2Fblog.che-ya.com%2Fanthropic-messages-api-tutorial%2F&amp;linkname=Anthropic%20Messages%20API%20%E5%85%A5%E9%96%80%E6%95%99%E5%AD%B8" title="Facebook" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_line" href="https://www.addtoany.com/add_to/line?linkurl=https%3A%2F%2Fblog.che-ya.com%2Fanthropic-messages-api-tutorial%2F&amp;linkname=Anthropic%20Messages%20API%20%E5%85%A5%E9%96%80%E6%95%99%E5%AD%B8" title="Line" rel="nofollow noopener" target="_blank"></a><a class="a2a_button_x" href="https://www.addtoany.com/add_to/x?linkurl=https%3A%2F%2Fblog.che-ya.com%2Fanthropic-messages-api-tutorial%2F&amp;linkname=Anthropic%20Messages%20API%20%E5%85%A5%E9%96%80%E6%95%99%E5%AD%B8" title="X" rel="nofollow noopener" target="_blank"></a><a class="a2a_dd addtoany_share_save addtoany_share" href="https://www.addtoany.com/share#url=https%3A%2F%2Fblog.che-ya.com%2Fanthropic-messages-api-tutorial%2F&#038;title=Anthropic%20Messages%20API%20%E5%85%A5%E9%96%80%E6%95%99%E5%AD%B8" data-a2a-url="https://blog.che-ya.com/anthropic-messages-api-tutorial/" data-a2a-title="Anthropic Messages API 入門教學"></a></p>]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
