搜索
首页后端开发Golang计算 Go 中发送给 LLM 的 Token 数量(第 2 部分)

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

介绍

这是编写 Go 应用程序的第二部分,该应用程序用于根据所选文本确定用户发送给 LLM 的令牌数量。

在上一篇文章中,我提到我只想构建一些仅用 Golang 编写的东西,在我查看的 Github 存储库中,这个似乎非常好:go-hggingface。该代码似乎很新,但它“有点”适合我。

执行

首先,代码访问 Hugginface 以获取所有与 LLM 相关的“标记器”列表,因此用户应该拥有 HF 标记。因此,我将令牌放入 .env 文件中,如图所示。

HF_TOKEN="your-huggingface-token"

然后使用下页中提供的示例 (https://github.com/gomlx/go-huggingface?tab=readme-ov-file),我围绕它构建了自己的代码。

package main

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

 "github.com/gomlx/go-huggingface/hub"
 "github.com/gomlx/go-huggingface/tokenizers"

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

 "fyne.io/fyne/v2"
 "fyne.io/fyne/v2/app"
 "fyne.io/fyne/v2/container"
 "fyne.io/fyne/v2/widget"
 //"github.com/inancgumus/scree"
)

var (
 // Model IDs we use for testing.
 hfModelIDs = []string{
  "ibm-granite/granite-3.1-8b-instruct",
  "meta-llama/Llama-3.3-70B-Instruct",
  "mistralai/Mistral-7B-Instruct-v0.3",
  "google/gemma-2-2b-it",
  "sentence-transformers/all-MiniLM-L6-v2",
  "protectai/deberta-v3-base-zeroshot-v1-onnx",
  "KnightsAnalytics/distilbert-base-uncased-finetuned-sst-2-english",
  "KnightsAnalytics/distilbert-NER",
  "SamLowe/roberta-base-go_emotions-onnx",
 }
)

func runCmd(name string, arg ...string) {
 cmd := exec.Command(name, arg...)
 cmd.Stdout = os.Stdout
 cmd.Run()
}

func ClearTerminal() {
 switch runtime.GOOS {
 case "darwin":
  runCmd("clear")
 case "linux":
  runCmd("clear")
 case "windows":
  runCmd("cmd", "/c", "cls")
 default:
  runCmd("clear")
 }
}

func FileSelectionDialog() string {
 // 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.")
  }
  log.Fatalf("Error selecting file: %v", err)
 }

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

func main() {

 var filePath string

 // read the '.env' file
 err := godotenv.Load()
 if err != nil {
  log.Fatal("Error loading .env file")
 }
 // get the value of the 'HF_TOKEN' environment variable
 hfAuthToken := os.Getenv("HF_TOKEN")
 if hfAuthToken == "" {
  log.Fatal("HF_TOKEN environment variable is not set")
 }

 // to display a list of LLMs to determine the # of tokens later on regarding the given text
 var llm string = ""
 var modelID string = ""
 myApp := app.New()
 myWindow := myApp.NewWindow("Select a LLM in the list")
 items := hfModelIDs
 // Label to display the selected item
 selectedItem := widget.NewLabel("Selected LLM: None")
 // Create a list widget
 list := widget.NewList(
  func() int {
   // Return the number of items in the list
   return len(items)
  },
  func() fyne.CanvasObject {
   // Template for each list item
   return widget.NewLabel("Template")
  },
  func(id widget.ListItemID, obj fyne.CanvasObject) {
   // Update the template with the actual data
   obj.(*widget.Label).SetText(items[id])
  },
 )
 // Handle list item selection
 list.OnSelected = func(id widget.ListItemID) {
  selectedItem.SetText("Selected LLM:" + items[id])
  llm = items[id]
 }

 // Layout with the list and selected item label
 content := container.NewVBox(
  list,
  selectedItem,
 )

 // Set the content of the window
 myWindow.SetContent(content)
 myWindow.Resize(fyne.NewSize(300, 400))
 myWindow.ShowAndRun()
 ClearTerminal()
 fmt.Printf("Selected LLM: %s\n", llm)
 //////

 //List files for the selected model
 for _, modelID := range hfModelIDs {
  if modelID == llm {
   fmt.Printf("\n%s:\n", modelID)
   repo := hub.New(modelID).WithAuth(hfAuthToken)
   for fileName, err := range repo.IterFileNames() {
    if err != nil {
     panic(err)
    }
    fmt.Printf("fileName\t%s\n", fileName)
    fmt.Printf("repo\t%s\n", repo)
    fmt.Printf("modelID\t%s\n", modelID)
   }
  }
 }

 //List tokenizer classes for the selected model
 for _, modelID := range hfModelIDs {
  if modelID == llm {
   fmt.Printf("\n%s:\n", modelID)
   repo := hub.New(modelID).WithAuth(hfAuthToken)
   fmt.Printf("\trepo=%s\n", repo)
   config, err := tokenizers.GetConfig(repo)
   if err != nil {
    panic(err)
   }
   fmt.Printf("\ttokenizer_class=%s\n", config.TokenizerClass)
  }
 }

 // Models URL -> "https://huggingface.co/api/models"
 repo := hub.New(modelID).WithAuth(hfAuthToken)
 tokenizer, err := tokenizers.New(repo)
 if err != nil {
  panic(err)
 }

 // call file selection dialogbox
 filePath = FileSelectionDialog()

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

 // Put the text file content into a buffer and convert it to a string.
 buf := new(bytes.Buffer)
 buf.ReadFrom(filerc)
 sentence := buf.String()

 tokens := tokenizer.Encode(sentence)
 fmt.Println("Sentence:\n", sentence)

 fmt.Printf("Tokens:  \t%v\n", tokens)
}

在“hfModelIDs”的“var”部分中,我添加了一些新的引用,例如 IBM 的 Granite、Meta 的 LLama 以及 Mistral 模型。

Huggingface 令牌也直接在 Go 代码中获取和读取。

我添加了一个对话框来显示法学硕士列表(我最终会更改),一个对话框来添加文件中的文本(我喜欢这种东西?)以及一些要清除和删除的代码行清洁屏幕?!

输入文字如下;

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.

测试
执行后的代码会显示一个对话框 bx,您可以在其中选择所需的 LLM。

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

如果一切顺利,下一步是在本地下载“tokenizer”文件(请参阅 Github 存储库的说明),然后会显示一个对话框,选择包含要评估的内容的文本文件令牌数量。

到目前为止,我已请求访问 Meta LLama 和 Google“google/gemma-2–2b-it”模型,并正在等待访问权限被授予。

google/gemma-2-2b-it:
        repo=google/gemma-2-2b-it
panic: request for metadata from "https://huggingface.co/google/gemma-2-2b-it/resolve/299a8560bedf22ed1c72a8a11e7dce4a7f9f51f8/tokenizer_config.json" failed with the following message: "403 Forbidden"

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

结论

我认为实现我想要的目标的正确途径是,一个能够确定代币数量的 Golang 程序是用户发送到 LLM 的查询。

该项目的唯一目的是了解针对各种 LLM 的查询中确定令牌数量背后的内部系统,并发现它们是如何计算的。

感谢您的阅读并欢迎评论。

最终结论之前,敬请期待……?

以上是计算 Go 中发送给 LLM 的 Token 数量(第 2 部分)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Golang的影响:速度,效率和简单性Golang的影响:速度,效率和简单性Apr 14, 2025 am 12:11 AM

GoimpactsdevelopmentPositationalityThroughSpeed,效率和模拟性。1)速度:gocompilesquicklyandrunseff,ifealforlargeprojects.2)效率:效率:ITScomprehenSevestAndArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增强开发的简单性:3)SimpleflovelmentIcties:3)简单性。

C和Golang:表演至关重要时C和Golang:表演至关重要时Apr 13, 2025 am 12:11 AM

C 更适合需要直接控制硬件资源和高性能优化的场景,而Golang更适合需要快速开发和高并发处理的场景。1.C 的优势在于其接近硬件的特性和高度的优化能力,适合游戏开发等高性能需求。2.Golang的优势在于其简洁的语法和天然的并发支持,适合高并发服务开发。

Golang行动:现实世界中的示例和应用程序Golang行动:现实世界中的示例和应用程序Apr 12, 2025 am 12:11 AM

Golang在实际应用中表现出色,以简洁、高效和并发性着称。 1)通过Goroutines和Channels实现并发编程,2)利用接口和多态编写灵活代码,3)使用net/http包简化网络编程,4)构建高效并发爬虫,5)通过工具和最佳实践进行调试和优化。

Golang:Go编程语言解释了Golang:Go编程语言解释了Apr 10, 2025 am 11:18 AM

Go语言的核心特性包括垃圾回收、静态链接和并发支持。1.Go语言的并发模型通过goroutine和channel实现高效并发编程。2.接口和多态性通过实现接口方法,使得不同类型可以统一处理。3.基本用法展示了函数定义和调用的高效性。4.高级用法中,切片提供了动态调整大小的强大功能。5.常见错误如竞态条件可以通过gotest-race检测并解决。6.性能优化通过sync.Pool重用对象,减少垃圾回收压力。

Golang的目的:建立高效且可扩展的系统Golang的目的:建立高效且可扩展的系统Apr 09, 2025 pm 05:17 PM

Go语言在构建高效且可扩展的系统中表现出色,其优势包括:1.高性能:编译成机器码,运行速度快;2.并发编程:通过goroutines和channels简化多任务处理;3.简洁性:语法简洁,降低学习和维护成本;4.跨平台:支持跨平台编译,方便部署。

SQL排序中ORDER BY语句结果为何有时看似随机?SQL排序中ORDER BY语句结果为何有时看似随机?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 Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能