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之类的大型语言模型时,了解您的输入消耗了多少token对于管理成本和优化性能至关重要。在本博客中,我们将探讨如何使用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端点和标头

我们使用token计数端点的url并提供必要的标头,包括:

  • x-api-key:您的API密钥。
  • content-type:设置为application/json。
  • anthropic-version和anthropic-beta:指定API版本和用于token计数的测试版功能。

3. 发出API请求

该函数:

  1. 将有效负载序列化为JSON。
  2. 使用序列化的有效负载创建一个POST请求。
  3. 设置所需的标头。
  4. 处理响应

读取响应并将其取消编组到Response 结构中,提取input_tokens 字段。

示例用法

以下是如何使用CalculateToken 函数:

func main() {
	ctx := context.Background()
	content := "你好!这段文字消耗了多少个token?"
	encoding := "claude-2" // 使用所需的模型名称替换

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

	fmt.Printf("输入内容消耗了%d个token。\n", tokens)
}

输出

运行示例将输出类似以下内容:

响应状态:200 OK
响应正文:{"input_tokens": 12}
输入内容消耗了12个token。

按照本指南,您可以将token计数无缝集成到您的Go应用程序中,并更好地管理您与Claude的交互。

EXAMPLE GO GUIDE GOLANG CLAUDE TOKEN CALCULATION

  RELATED

  COMMENTS

0

No comment for this article.