찾다
백엔드 개발GolangGo에서 LLM으로 전송된 토큰 수 계산(1부)

Counting the number of Tokens sent to a LLM in Go (part 1)

소개

몇 주 전 저는 비즈니스 파트너 회사의 CFO와 자사 솔루션 내에서 watsonx.ai 기능 구현에 관해 논의했습니다. 비용에 대한 논의 중에 "토큰"이라는 단어를 발음했는데 갑자기 패닉이 일어났습니다 ?

토큰이 무엇인지 설명한 후 질문이 생겼습니다. “우리가 보내고 받는 토큰을 어떻게 계산하나요? 비용이 얼마나 드나요?”

답은 아주 쉬웠습니다. 우리는 watsonx.ai 스튜디오 프롬프트 랩에 가서 몇 가지 간단한 프롬프트를 가지고 왔다 갔다 했고 거기에서 토큰의 수를 확인했습니다. 또한 간단한 입력을 통해 LLM에 보내는 토큰 수를 확인할 수 있는 매우 멋진 웹사이트도 보여주었습니다.

나중에 저는 스스로 토큰 카운터 애플리케이션을 만들어 보는 것이 어떨까요(그리고 오랫동안 Golang을 사용하지 않았기 때문에 Go 언어로 작성하려는 의도였습니다!)라고 생각했습니다. 글쎄요, 그보다 좀 더 복잡할 것 같은데요?

첫 번째 시도 — Regex 사용

처음에는 Regex를 사용하면 어느 정도 만족스러운 결과를 얻을 수 있겠다는 생각이 들었습니다.

다음 Go 앱을 설정했습니다.

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
    "regexp"
    "strings"

    "github.com/sqweek/dialog"
)

// countTokens approximates the number of tokens in a text based on whitespace and punctuation.
func countTokens(text string) int {
    // A simple regex to split text into words and punctuation
    tokenizer := regexp.MustCompile(`\w+|[^\w\s]`)
    tokens := tokenizer.FindAllString(text, -1)
    return len(tokens)
}

func main() {

    // Open a file dialog box and let the user select a text file
    filePath, err := dialog.File().Filter("Text Files", "txt").Load()
    if err != nil {
        if err.Error() == "Cancelled" {
            fmt.Println("File selection was cancelled.")
            return
        }
        log.Fatalf("Error selecting file: %v", err)
    }

    // Output the selected file name
    fmt.Printf("Selected file: %s\n", filePath)

    // Specify the file to read
    //filePath := "input.txt"

    // Open the file
    file, err := os.Open(filePath)
    if err != nil {
        fmt.Printf("Error opening file: %v\n", err)
        return
    }
    defer file.Close()

    // Read the file line by line
    var content strings.Builder
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        content.WriteString(scanner.Text())
        content.WriteString("\n")
    }

    if err := scanner.Err(); err != nil {
        fmt.Printf("Error reading file: %v\n", err)
        return
    }

    // Get the text content
    text := content.String()

    // Count the tokens
    tokenCount := countTokens(text)

    // Output the result
    fmt.Printf("The file contains approximately %d tokens.\n", tokenCount)
}

아시겠지만 제가 GUI와 대화 상자를 좋아해서 입력 텍스트 파일을 선택할 수 있는 대화 상자를 구현했습니다.

여기 텍스트 파일이 있습니다(내가 찾은 임의의 텍스트?).

The popularity of the Rust language continues to explode; yet, many critical codebases remain authored in C, and cannot be realistically rewritten by hand. Automatically translating C to Rust is thus an appealing course of action. Several works have gone down this path, handling an ever-increasing subset of C through a variety of Rust features, such as unsafe. While the prospect of automation is appealing, producing code that relies on unsafe negates the memory safety guarantees offered by Rust, and therefore the main advantages of porting existing codebases to memory-safe languages.
We instead explore a different path, and explore what it would take to translate C to safe Rust; that is, to produce code that is trivially memory safe, because it abides by Rust's type system without caveats. Our work sports several original contributions: a type-directed translation from (a subset of) C to safe Rust; a novel static analysis based on "split trees" that allows expressing C's pointer arithmetic using Rust's slices and splitting operations; an analysis that infers exactly which borrows need to be mutable; and a compilation strategy for C's struct types that is compatible with Rust's distinction between non-owned and owned allocations.
We apply our methodology to existing formally verified C codebases: the HACL* cryptographic library, and binary parsers and serializers from EverParse, and show that the subset of C we support is sufficient to translate both applications to safe Rust. Our evaluation shows that for the few places that do violate Rust's aliasing discipline, automated, surgical rewrites suffice; and that the few strategic copies we insert have a negligible performance impact. Of particular note, the application of our approach to HACL* results in a 80,000 line verified cryptographic library, written in pure Rust, that implements all modern algorithms - the first of its kind.

코드를 실행하면 다음과 같은 결과가 나타납니다.

The file contains approximately 359 tokens.

괜찮을 것 같긴 한데, 음… 그렇긴 한데… 어떤 모델과 비교하면?? 그리고 Regex를 구현하는 방법도 다양하므로 이 방법은 전혀 포함되지 않습니다 ?!

두 번째 시도 - 특정 모델에 대해 실행

내가 알아낸 것은 특정 LLM에 특정 "토크나이저"를 사용하지 않는 한 이전 방법은 정확하지 않다는 것입니다. 그래서 나는 현재 시중에 나와 있는 gpt 3.5와 같은 모델에 대해 어떻게 하면 정확한 결과를 얻을 수 있는지 알아보기 시작했습니다. 인터넷에서 좀 조사한 끝에 제가 만든 앱이 나왔습니다.

package main

import (
 "bufio"
 "bytes"
 "fmt"
 "log"
 "os"
 "os/exec"

 "github.com/joho/godotenv"
 "github.com/sqweek/dialog"
)

func main() {


 // Open a file dialog box and let the user select a text file
 filePath, err := dialog.File().Filter("Text Files", "txt").Load()
 if err != nil {
  if err.Error() == "Cancelled" {
   fmt.Println("File selection was cancelled.")
   return
  }
  log.Fatalf("Error selecting file: %v", err)
 }

 // Output the selected file name
 fmt.Printf("Selected file: %s\n", filePath)

 // Open the file
 file, err := os.Open(filePath)
 if err != nil {
  fmt.Printf("Error opening file: %v\n", err)
  return
 }
 defer file.Close()

 // Read the file content
 var content bytes.Buffer
 scanner := bufio.NewScanner(file)
 for scanner.Scan() {
  content.WriteString(scanner.Text())
  content.WriteString("\n")
 }

 if err := scanner.Err(); err != nil {
  fmt.Printf("Error reading file: %v\n", err)
  return
 }

 // Specify the model
 model := "gpt-3.5-turbo"

 // Execute the Python script
 cmd := exec.Command("python3", "tokenizer.py", model)
 cmd.Stdin = bytes.NewReader(content.Bytes())
 output, err := cmd.Output()
 if err != nil {
  fmt.Printf("Error running tokenizer script: %v\n", err)
  return
 }

 // Print the token count
 fmt.Printf("Token count: %s", output)
}

위 코드에서 볼 수 있듯이 Microsoft 사이트에서 찾은 Python 앱에 대한 호출이 있습니다. 이 앱은 (구현되었기 때문에) "tiktoken” 라이브러리를 사용하여 gpt에 대한 토큰 수를 결정합니다! 모델명도 하드코딩 되어있습니다.

import sys
from tiktoken import encoding_for_model

def count_tokens(model, text):
    enc = encoding_for_model(model)
    tokens = enc.encode(text)
    return len(tokens)

if __name__ == "__main__":
    # Read model name and text from stdin
    model = sys.argv[1]  # E.g., "gpt-3.5-turbo"
    text = sys.stdin.read()
    print(count_tokens(model, text))

잘 작동합니다. 이전에 제공된 동일한 텍스트에 대해 이제 내가 찾은 모든 웹사이트에 대해 정확한 366개의 토큰 수를 얻었고 모델을 GPT 3.5

로 설정했습니다.

내가 작성하고 싶은 것은 "Golang"에 완전히 포함된 코드입니다... 그리고 Huggingface에서 찾을 수 있는 모든 모델(또는 거의 모든 모델)에서 실행할 수 있기를 원합니다. ibm-granite/granite-3.1–8b-instruct) ?

이 글의 2부(WIP)입니다.

지금까지 다음을 탐색 중입니다(좋죠?) Github repos;

  • 토크나이저: https://github.com/sugarme/tokenizer
  • 토크나이저: https://github.com/daulet/tokenizers
  • 그리고 마지막으로 중요한 것은 -> 고허깅페이스: https://github.com/gomlx/go-huggingface?tab=readme-ov-file

결론

읽어주셔서 감사하고 의견을 남겨주세요.

그리고 두 번째 앱이 나올 때까지 지켜봐주세요... ?

위 내용은 Go에서 LLM으로 전송된 토큰 수 계산(1부)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Golang vs. C : 코드 예제 및 성능 분석Golang vs. C : 코드 예제 및 성능 분석Apr 15, 2025 am 12:03 AM

Golang은 빠른 개발 및 동시 프로그래밍에 적합한 반면 C는 극심한 성능과 기본 제어가 필요한 프로젝트에 더 적합합니다. 1) Golang의 동시성 모델은 Goroutine 및 Channel을 통한 동시성 프로그래밍을 단순화합니다. 2) C의 템플릿 프로그래밍은 일반적인 코드 및 성능 최적화를 제공합니다. 3) Golang의 쓰레기 수집은 편리하지만 성능에 영향을 줄 수 있습니다. C의 메모리 관리는 복잡하지만 제어는 괜찮습니다.

Golang의 영향 : 속도, 효율성 및 단순성Golang의 영향 : 속도, 효율성 및 단순성Apr 14, 2025 am 12:11 AM

goimpactsdevelopmentpositively throughlyspeed, 효율성 및 단순성.

C와 Golang : 성능이 중요 할 때C와 Golang : 성능이 중요 할 때Apr 13, 2025 am 12:11 AM

C는 하드웨어 리소스 및 고성능 최적화가 직접 제어되는 시나리오에 더 적합하지만 Golang은 빠른 개발 및 높은 동시성 처리가 필요한 시나리오에 더 적합합니다. 1.C의 장점은 게임 개발과 같은 고성능 요구에 적합한 하드웨어 특성 및 높은 최적화 기능에 가깝습니다. 2. Golang의 장점은 간결한 구문 및 자연 동시성 지원에 있으며, 이는 동시성 서비스 개발에 적합합니다.

Golang in Action : 실제 예제 및 응용 프로그램Golang in Action : 실제 예제 및 응용 프로그램Apr 12, 2025 am 12:11 AM

Golang은 실제 응용 분야에서 탁월하며 단순성, 효율성 및 동시성으로 유명합니다. 1) 동시 프로그래밍은 Goroutines 및 채널을 통해 구현됩니다. 2) Flexible Code는 인터페이스 및 다형성을 사용하여 작성됩니다. 3) NET/HTTP 패키지로 네트워크 프로그래밍 단순화, 4) 효율적인 동시 크롤러 구축, 5) 도구 및 모범 사례를 통해 디버깅 및 최적화.

Golang : Go 프로그래밍 언어가 설명되었습니다Golang : Go 프로그래밍 언어가 설명되었습니다Apr 10, 2025 am 11:18 AM

GO의 핵심 기능에는 쓰레기 수집, 정적 연결 및 동시성 지원이 포함됩니다. 1. Go Language의 동시성 모델은 고루틴 및 채널을 통한 효율적인 동시 프로그래밍을 실현합니다. 2. 인터페이스 및 다형성은 인터페이스 방법을 통해 구현되므로 서로 다른 유형을 통일 된 방식으로 처리 할 수 ​​있습니다. 3. 기본 사용법은 기능 정의 및 호출의 효율성을 보여줍니다. 4. 고급 사용에서 슬라이스는 동적 크기 조정의 강력한 기능을 제공합니다. 5. 레이스 조건과 같은 일반적인 오류는 Getest-race를 통해 감지 및 해결할 수 있습니다. 6. 성능 최적화는 sync.pool을 통해 개체를 재사용하여 쓰레기 수집 압력을 줄입니다.

Golang의 목적 : 효율적이고 확장 가능한 시스템 구축Golang의 목적 : 효율적이고 확장 가능한 시스템 구축Apr 09, 2025 pm 05:17 PM

Go Language는 효율적이고 확장 가능한 시스템을 구축하는 데 잘 작동합니다. 장점은 다음과 같습니다. 1. 고성능 : 기계 코드로 컴파일, 빠른 달리기 속도; 2. 동시 프로그래밍 : 고어 라틴 및 채널을 통한 멀티 태스킹 단순화; 3. 단순성 : 간결한 구문, 학습 및 유지 보수 비용 절감; 4. 크로스 플랫폼 : 크로스 플랫폼 컴파일, 쉬운 배포를 지원합니다.

SQL 분류의 진술에 의한 순서 결과가 때때로 무작위로 보이는 이유는 무엇입니까?SQL 분류의 진술에 의한 순서 결과가 때때로 무작위로 보이는 이유는 무엇입니까?Apr 02, 2025 pm 05:24 PM

SQL 쿼리 결과의 정렬에 대해 혼란스러워합니다. SQL을 학습하는 과정에서 종종 혼란스러운 문제가 발생합니다. 최근 저자는 "Mick-SQL 기본 사항"을 읽고 있습니다.

기술 스택 컨버전스는 기술 스택 선택의 프로세스 일뿐입니까?기술 스택 컨버전스는 기술 스택 선택의 프로세스 일뿐입니까?Apr 02, 2025 pm 05:21 PM

기술 스택 컨버전스와 기술 선택의 관계, 소프트웨어 개발에서 기술 스택의 선택 및 관리는 매우 중요한 문제입니다. 최근에 일부 독자들은 ...

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
4 몇 주 전By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25 : Myrise에서 모든 것을 잠금 해제하는 방법
1 몇 달 전By尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는