Calculating Token Count for Claude API Using Go: A Step-by-Step Guide

English 简体中文 繁体中文 ภาษาไทย Tiếng Việt
Summary

Understanding token consumption for Claude API interactions is crucial for managing costs and optimizing performance. Developers can implement a Go function to calculate token counts by leveraging Anthropic's count_tokens API endpoint. This involves structuring a JSON request payload with the desired model and message content, setting necessary API key and version headers, then sending an HTTP POST request. The API response is subsequently parsed to extract the input_tokens value, providing a programmatic way to manage token usage within Go applications. This integration allows for precise tracking of token usage for any given input.

當使用大型語言模型(例如 Anthropic 的 Claude)時,了解您的輸入使用了多少個 tokens 對於管理成本和優化效能至關重要。在本部落格中,我們將探討如何使用 Go 計算給定輸入的 token 數量。我們將使用 Anthropic 的 count_tokens API 端點,它提供了一種直接的方法來確定 token 使用情況。

先決條件

在深入研究之前,請確保您擁有:

  1. 一個可運作的 Go 環境(安裝指南)。
  2. 一個 Anthropic API 金鑰。將其設定為環境變數 (ANTHROPIC_API_KEY)。
  3. Go HTTP 請求和 JSON 處理的基本知識。

程式碼

以下是一個完整的 Go 函數,用於計算 Claude 的 token 數量:

package main

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

// RequestPayload 定義 JSON 負載的結構
type RequestPayload struct {
	Model    string `json:"model"`
	System   string `json:"system"`
	Messages []struct {
		Role    string `json:"role"`
		Content string `json:"content"`
	} `json:"messages"`
}

// Response 定義 API 回應的結構
type Response struct {
	InputTokens int `json:"input_tokens"`
}

// CalculateToken 計算給定輸入內容的 token 數量
func CalculateToken(ctx context.Context, content string, encoding string) (int, error) {
	// 定義 API 端點和標頭
	url := "https://api.anthropic.com/v1/messages/count_tokens"
	apiKey := os.Getenv("ANTHROPIC_API_KEY") // 確保已在您的環境中設定
	headers := map[string]string{
		"x-api-key":         apiKey,
		"content-type":      "application/json",
		"anthropic-version": "2023-06-01",
		"anthropic-beta":    "token-counting-2024-11-01",
	}

	// 建立請求負載
	payload := RequestPayload{
		Model:  encoding,
		System: "你是一位科學家",
		Messages: []struct {
			Role    string `json:"role"`
			Content string `json:"content"`
		}{
			{Role: "user", Content: content},
		},
	}

	// 將負載序列化為 JSON
	payloadBytes, err := json.Marshal(payload)
	if err != nil {
		log.Fatalf("錯誤:序列化負載:%v", err)
	}

	// 建立 HTTP POST 請求
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes))
	if err != nil {
		log.Fatalf("錯誤:建立 HTTP 請求:%v", err)
	}

	// 將標頭新增到請求
	for key, value := range headers {
		req.Header.Set(key, value)
	}

	// 傳送請求
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatalf("錯誤:傳送請求:%v", err)
	}
	defer resp.Body.Close()

	// 讀取並解析回應
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Printf("錯誤:讀取回應主體:%v", err)
		return 0, err
	}

	respData := &Response{}
	_ = json.Unmarshal(body, respData)
	fmt.Printf("回應狀態:%s\n", resp.Status)
	fmt.Printf("回應主體:%s\n", body)

	return respData.InputTokens, nil
}

說明

1. 結構化負載

RequestPayload 結構定義 count_tokens API 需要的 JSON 負載。Messages 欄位包含對話歷史記錄,其中每則訊息都有一個角色(例如使用者)和內容。

2. 定義 API 端點和標頭

我們使用 url 作為 token 計數端點,並提供必要的標頭,包括:

  • x-api-key:您的 API 金鑰。
  • content-type:設定為 application/json。
  • anthropic-version 和 anthropic-beta:指定 API 版本和 token 計數的 Beta 功能。

3. 發出 API 請求

函數:

  1. 將負載序列化為 JSON。
  2. 使用序列化的負載建立 POST 請求。
  3. 設定所需的標頭。
  4. 處理回應

讀取回應並取消編組到 Response 結構中,提取 input_tokens 欄位。

範例用法

以下是如何使用 CalculateToken 函數:

func main() {
	ctx := context.Background()
	content := "哈囉!這段文字使用了多少個 tokens?"
	encoding := "claude-2" // 取代為所需的模型名稱

	tokens, err := CalculateToken(ctx, content, encoding)
	if err != nil {
		log.Fatalf("計算 tokens 失敗:%v", err)
	}

	fmt.Printf("輸入內容使用了 %d 個 tokens。\n", tokens)
}

輸出

執行範例將輸出類似以下內容:

回應狀態:200 OK
回應主體:{"input_tokens": 12}
輸入內容使用了 12 個 tokens。

遵循本指南,您可以將 token 計數無縫整合到您的 Go 應用程式中,並更好地管理您與 Claude 的互動。

EXAMPLE GO GUIDE GOLANG CLAUDE TOKEN CALCULATION

  RELATED

  COMMENTS

0

No comment for this article.