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.

เมื่อทำงานกับแบบจำลองภาษาขนาดใหญ่ เช่น Claude จาก Anthropic การทำความเข้าใจว่าอินพุตของคุณใช้โทเค็นจำนวนเท่าใดนั้นมีความสำคัญอย่างยิ่งต่อการจัดการต้นทุนและการเพิ่มประสิทธิภาพการทำงาน ในบล็อกนี้ เราจะสำรวจวิธีการคำนวณจำนวนโทเค็นสำหรับอินพุตที่กำหนดโดยใช้ Go เราจะใช้จุดสิ้นสุด API count_tokens ของ Anthropic ซึ่งเป็นวิธีที่ตรงไปตรงมาในการกำหนดการใช้โทเค็น

ข้อกำหนดเบื้องต้น

ก่อนที่จะดำเนินการต่อ โปรดตรวจสอบให้แน่ใจว่าคุณมี:

  1. สภาพแวดล้อมการทำงานของ Go (คู่มือการติดตั้ง).
  2. API key ของ Anthropic ตั้งค่าเป็นตัวแปรสภาพแวดล้อม (ANTHROPIC_API_KEY).
  3. ความรู้พื้นฐานเกี่ยวกับการร้องขอ Go HTTP และการจัดการ JSON.

โค้ด

นี่คือฟังก์ชัน Go ที่สมบูรณ์สำหรับการคำนวณจำนวนโทเค็นสำหรับ Claude:

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 คำนวณจำนวนโทเค็นสำหรับเนื้อหาอินพุตที่กำหนด
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 กำหนดเพย์โหลด JSON ที่จำเป็นโดย API count_tokens ฟิลด์ Messages ประกอบด้วยประวัติการสนทนา โดยแต่ละข้อความจะมีบทบาท (เช่น ผู้ใช้) และเนื้อหา

2. การกำหนดจุดสิ้นสุด API และส่วนหัว

เราใช้ url สำหรับจุดสิ้นสุดการนับโทเค็นและให้ส่วนหัวที่จำเป็น รวมถึง:

  • x-api-key: API key ของคุณ
  • content-type: ตั้งค่าเป็น application/json
  • anthropic-version และ anthropic-beta: ระบุเวอร์ชัน API และคุณลักษณะเบต้าสำหรับการนับโทเค็น

3. การสร้างการร้องขอ API

ฟังก์ชัน:

  1. แปลงเพย์โหลดเป็น JSON
  2. สร้างการร้องขอ POST ด้วยเพย์โหลดที่แปลงแล้ว
  3. ตั้งค่าส่วนหัวที่จำเป็น
  4. การจัดการการตอบสนอง

การตอบสนองจะถูกอ่านและแยกวิเคราะห์ลงในโครงสร้าง Response โดยดึงฟิลด์ input_tokens ออกมา

ตัวอย่างการใช้งาน

นี่คือวิธีที่คุณสามารถใช้ฟังก์ชัน CalculateToken:

func main() {
	ctx := context.Background()
	content := "สวัสดี! ข้อความนี้ใช้โทเค็นกี่ตัว?"
	encoding := "claude-2" // แทนที่ด้วยชื่อแบบจำลองที่ต้องการ

	tokens, err := CalculateToken(ctx, content, encoding)
	if err != nil {
		log.Fatalf("ไม่สามารถคำนวณโทเค็นได้: %v", err)
	}

	fmt.Printf("เนื้อหาอินพุตใช้โทเค็น %d ตัว\n", tokens)
}

ผลลัพธ์

การรันตัวอย่างจะแสดงผลลัพธ์ที่คล้ายกับนี้:

สถานะการตอบสนอง: 200 OK
เนื้อหาการตอบสนอง: {"input_tokens": 12}
เนื้อหาอินพุตใช้โทเค็น 12 ตัว

โดยทำตามคำแนะนำนี้ คุณสามารถรวมการนับโทเค็นเข้ากับแอปพลิเคชัน Go ของคุณได้อย่างราบรื่นและจัดการการโต้ตอบกับ Claude ได้ดียิ่งขึ้น

EXAMPLE GO GUIDE GOLANG CLAUDE TOKEN CALCULATION

  RELATED

  COMMENTS

0

No comment for this article.