国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁(yè) 后端開(kāi)發(fā) Golang Go 調(diào)用 LangChain(一)

Go 調(diào)用 LangChain(一)

Jan 02, 2025 pm 09:29 PM

Calling LangChain from Go (Part 1)

動(dòng)機(jī)

在使用 Golang 和 LLM 進(jìn)行“假期”測(cè)試(之前的帖子...)之后,我一直在尋找一種在 Go 中實(shí)現(xiàn) LangChain 調(diào)用的簡(jiǎn)單方法,最好使用 watsonx.ai。

幸運(yùn)的是,我找到了以下 Github 存儲(chǔ)庫(kù):https://github.com/tmc/langchaingo(向 Travis Cline 行屈膝禮 https://github.com/tmc)。

在他的存儲(chǔ)庫(kù)中,有一個(gè)特定的文件夾:https://github.com/tmc/langchaingo/blob/main/examples/watsonx-llm-example/watsonx_example.go 引起了我的注意!

所以像往常一樣,我建立了一個(gè)項(xiàng)目并嘗試實(shí)現(xiàn)它,并提出了我自己的想法(à ma醬?)。

執(zhí)行

像往常一樣需要環(huán)境變量,我設(shè)置了一個(gè) .env 文件,稍后在應(yīng)用程序中使用。

export WATSONX_API_KEY="your-watsonx-api-key"
export WATSONX_PROJECT_ID="your-watsonx-projectid"
# I used the US-SOUTH, could be any other region of IBM Cloud
export SERVICE_URL="https://us-south.ml.cloud.ibm.com" 

在上一篇文章中,我提到嘗試計(jì)算法學(xué)碩士發(fā)送和接收的代幣數(shù)量。這項(xiàng)工作仍在進(jìn)行中,因此我直接在應(yīng)用程序中使用了“tiktoken-go”庫(kù),并打算對(duì)其進(jìn)行一些更改(在不久的將來(lái)?)。無(wú)論如何,就我目前的進(jìn)度而言,它并沒(méi)有真正起作用,但它就在那里。

對(duì)于應(yīng)用程序本身,我?guī)缀醢丛瓨邮褂昧?Travis 存儲(chǔ)庫(kù)中的代碼,并添加和包裝了以下功能;

  • 使用對(duì)話框進(jìn)行提示輸入(?我喜歡對(duì)話框?)
  • 嘗試”計(jì)算發(fā)送給法學(xué)碩士和從法學(xué)碩士收到的“令牌”數(shù)量。 代碼本身如下;
package main

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

    "fyne.io/fyne/v2"
    "fyne.io/fyne/v2/app"
    "fyne.io/fyne/v2/container"
    "fyne.io/fyne/v2/dialog"
    "fyne.io/fyne/v2/widget"

    "github.com/joho/godotenv"
    "github.com/pkoukk/tiktoken-go"
    "github.com/tmc/langchaingo/llms"
    "github.com/tmc/langchaingo/llms/watsonx"
)

const (
    _tokenApproximation = 4
)

const (
    _gpt35TurboContextSize   = 4096
    _gpt432KContextSize      = 32768
    _gpt4ContextSize         = 8192
    _textDavinci3ContextSize = 4097
    _textBabbage1ContextSize = 2048
    _textAda1ContextSize     = 2048
    _textCurie1ContextSize   = 2048
    _codeDavinci2ContextSize = 8000
    _codeCushman1ContextSize = 2048
    _textBisonContextSize    = 2048
    _chatBisonContextSize    = 2048
    _defaultContextSize      = 2048
)

// nolint:gochecknoglobals
var modelToContextSize = map[string]int{
    "gpt-3.5-turbo":    _gpt35TurboContextSize,
    "gpt-4-32k":        _gpt432KContextSize,
    "gpt-4":            _gpt4ContextSize,
    "text-davinci-003": _textDavinci3ContextSize,
    "text-curie-001":   _textCurie1ContextSize,
    "text-babbage-001": _textBabbage1ContextSize,
    "text-ada-001":     _textAda1ContextSize,
    "code-davinci-002": _codeDavinci2ContextSize,
    "code-cushman-001": _codeCushman1ContextSize,
}

var tokens int

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 promptEntryDialog() string {

    var promptEntry string

    // Create a new Fyne application
    myApp := app.New()
    myWindow := myApp.NewWindow("Prompt Entry Dialog")

    // Variable to store user input
    var userInput string

    // Button to show the dialog
    button := widget.NewButton("Click to Enter your prompt's text", func() {
        entry := widget.NewEntry()
        dialog.ShowCustomConfirm("Input Dialog", "OK", "Cancel", entry, func(confirm bool) {
            if confirm {
                userInput = entry.Text
                promptEntry = userInput
                fmt.Println("User Input:", userInput) // Print to the console
                myWindow.Close()
            }
        }, myWindow)
    })

    // Add the button to the window
    myWindow.SetContent(container.NewVBox(
        widget.NewLabel("Click the button below to enter text:"),
        button,
    ))

    // Set the window size and run the application
    myWindow.Resize(fyne.NewSize(400, 200))
    myWindow.ShowAndRun()
    return promptEntry
}

func CountTokens(model, text string, inorout string) int {
    var txtLen int
    e, err := tiktoken.EncodingForModel(model)
    if err != nil {
        e, err = tiktoken.GetEncoding("gpt2")
        if err != nil {
            log.Printf("[WARN] Failed to calculate number of tokens for model, falling back to approximate count")
            txtLen = len([]rune(text))

            fmt.Println("Guessed tokens for the "+inorout+" text:", txtLen/_tokenApproximation)

            return txtLen
        }
    }
    return len(e.Encode(text, nil, nil))
}

func GetModelContextSize(model string) int {
    contextSize, ok := modelToContextSize[model]
    if !ok {
        return _defaultContextSize
    }
    return contextSize
}

func CalculateMaxTokens(model, text string) int {
    return GetModelContextSize(model) - CountTokens(model, text, text)
}

func main() {
    var prompt, model string

    // read the '.env' file
    err := godotenv.Load()
    if err != nil {
        log.Fatal("Error loading .env file")
    }

    ApiKey := os.Getenv("WATSONX_API_KEY")
    if ApiKey == "" {
        log.Fatal("WATSONX_API_KEY environment variable is not set")
    }
    ServiceURL := os.Getenv("SERVICE_URL")
    if ServiceURL == "" {
        log.Fatal("SERVICE_URL environment variable is not set")
    }
    ProjectID := os.Getenv("WATSONX_PROJECT_ID")
    if ProjectID == "" {
        log.Fatal("WATSONX_PROJECT_ID environment variable is not set")
    }

    // LLM from watsonx.ai
    model = "ibm/granite-13b-instruct-v2"
    // model = "meta-llama/llama-3-70b-instruct"

    llm, err := watsonx.New(
        model,
        //// Optional parameters: to be implemented if needed - Not used at this stage but all ready
        // wx.WithWatsonxAPIKey(ApiKey),
        // wx.WithWatsonxProjectID("YOUR WATSONX PROJECT ID"),
    )

    if err != nil {
        log.Fatal(err)
    }
    ctx := context.Background()

    prompt = promptEntryDialog()

    // for the output visibility on the consol - getting rid of system messages
    ClearTerminal()

    // Use the entry variable here
    fmt.Println("Calling the llm with the user's prompt:", prompt)

    tokens = CountTokens(model, prompt, "input")

    completion, err := llms.GenerateFromSinglePrompt(
        ctx,
        llm,
        prompt,
        llms.WithTopK(10),
        llms.WithTopP(0.95),
        llms.WithSeed(25),
    )
    // Check for errors
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(completion)

    tokens = CountTokens(model, completion, "output")

}

效果很好,輸出如下所示。

Calling the llm with the user's prompt: What is the distance in Kilmometers from Earth to Moon?
2024/12/31 11:08:04 [WARN] Failed to calculate number of tokens for model, falling back to approximate count
Guessed tokens for the input text: 13
The distance from Earth to the Moon is about 384,400 kilometers.
2024/12/31 11:08:04 [WARN] Failed to calculate number of tokens for model, falling back to approximate count
Guessed tokens for the output text: 16

#####


Calling the llm with the user's prompt: What is the name of the capital city of France?
2024/12/31 11:39:28 [WARN] Failed to calculate number of tokens for model, falling back to approximate count
Guessed tokens for the input text: 11
Paris
2024/12/31 11:39:28 [WARN] Failed to calculate number of tokens for model, falling back to approximate count
Guessed tokens for the output text: 1

瞧!

后續(xù)步驟

我將為版本 0.2 實(shí)現(xiàn)以下功能;

  • 提出用戶想要使用的模型,
  • 確定令牌數(shù)量的更準(zhǔn)確方法,
  • 一些真正的LangChain實(shí)現(xiàn)。

結(jié)論

這是我從 Go 應(yīng)用程序調(diào)用 LangChain 的工作的一個(gè)非常簡(jiǎn)單的反映。

敬請(qǐng)期待更多精彩內(nèi)容?

以上是Go 調(diào)用 LangChain(一)的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請(qǐng)聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

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

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開(kāi)發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)代碼編輯軟件(SublimeText3)

熱門(mén)話題

將Golang服務(wù)與現(xiàn)有Python基礎(chǔ)架構(gòu)集成的策略 將Golang服務(wù)與現(xiàn)有Python基礎(chǔ)架構(gòu)集成的策略 Jul 02, 2025 pm 04:39 PM

TOIntegrategolangServicesWithExistingPypythoninFrasture,userestapisorgrpcForinter-serviceCommunication,允許GoandGoandPyThonAppStoStoInteractSeamlessSeamLlyThroughlyThroughStandArdArdAdrotized Protoccols.1.usererestapis(ViaFrameWorkslikeSlikeSlikeGiningOandFlaskInpyThon)Orgrococo(wirs Propococo)

了解Web API的Golang和Python之間的性能差異 了解Web API的Golang和Python之間的性能差異 Jul 03, 2025 am 02:40 AM

Golangofferssuperiorperformance,nativeconcurrencyviagoroutines,andefficientresourceusage,makingitidealforhigh-traffic,low-latencyAPIs;2.Python,whileslowerduetointerpretationandtheGIL,provideseasierdevelopment,arichecosystem,andisbettersuitedforI/O-bo

是Golang前端還是后端 是Golang前端還是后端 Jul 08, 2025 am 01:44 AM

Golang主要用于后端開(kāi)發(fā),但也能在前端領(lǐng)域間接發(fā)揮作用。其設(shè)計(jì)目標(biāo)聚焦高性能、并發(fā)處理和系統(tǒng)級(jí)編程,適合構(gòu)建API服務(wù)器、微服務(wù)、分布式系統(tǒng)、數(shù)據(jù)庫(kù)操作及CLI工具等后端應(yīng)用。雖然Golang不是網(wǎng)頁(yè)前端的主流語(yǔ)言,但可通過(guò)GopherJS編譯成JavaScript、通過(guò)TinyGo運(yùn)行于WebAssembly,或搭配模板引擎生成HTML頁(yè)面來(lái)參與前端開(kāi)發(fā)。然而,現(xiàn)代前端開(kāi)發(fā)仍需依賴(lài)JavaScript/TypeScript及其生態(tài)。因此,Golang更適合以高性能后端為核心的技術(shù)棧選擇。

如何完全,干凈地從我的系統(tǒng)中卸載Golang? 如何完全,干凈地從我的系統(tǒng)中卸載Golang? Jun 30, 2025 am 01:58 AM

TocompletelyuninstallGolang,firstdeterminehowitwasinstalled(packagemanager,binary,source,etc.),thenremoveGobinariesanddirectories,cleanupenvironmentvariables,anddeleterelatedtoolsandcaches.Beginbycheckinginstallationmethod:commonmethodsincludepackage

如何使用頻道在Golang的Goroutines之間進(jìn)行通信? 如何使用頻道在Golang的Goroutines之間進(jìn)行通信? Jun 26, 2025 pm 12:08 PM

Go語(yǔ)言中channel用于goroutine間通信與同步。聲明使用make函數(shù),如ch:=make(chanstring),發(fā)送用ch

在構(gòu)建過(guò)程中,'找不到軟件包”錯(cuò)誤是什么意思? 在構(gòu)建過(guò)程中,'找不到軟件包”錯(cuò)誤是什么意思? Jun 26, 2025 pm 12:57 PM

當(dāng)遇到“cannotfindpackage”錯(cuò)誤時(shí),通常是因?yàn)镚o無(wú)法找到目標(biāo)包或依賴(lài)。解決方法如下:1.檢查導(dǎo)入路徑是否正確,確保與模塊路徑或目錄結(jié)構(gòu)一致;2.確認(rèn)已初始化go.mod文件,使用gomodinit和gomodtidy管理依賴(lài);3.運(yùn)行g(shù)oget下載缺失依賴(lài)或清理模塊緩存;4.確保在正確的目錄上下文中執(zhí)行命令,或指定完整的模塊相對(duì)路徑進(jìn)行構(gòu)建。

如何在Golang中使用Select語(yǔ)句進(jìn)行非阻滯渠道操作和超時(shí)? 如何在Golang中使用Select語(yǔ)句進(jìn)行非阻滯渠道操作和超時(shí)? Jun 26, 2025 pm 01:08 PM

在Go中,使用select語(yǔ)句可以有效處理非阻塞通道操作和實(shí)現(xiàn)超時(shí)機(jī)制。通過(guò)default分支實(shí)現(xiàn)非阻塞接收或發(fā)送操作,如1.非阻塞接收:若有值則接收并打印,否則立即執(zhí)行default分支;2.非阻塞發(fā)送:若通道無(wú)接收者則跳過(guò)發(fā)送。此外,結(jié)合time.After可實(shí)現(xiàn)超時(shí)控制,例如等待結(jié)果或2秒后超時(shí)返回。還可組合非阻塞與超時(shí)行為,先嘗試立即獲取值,失敗后再短暫等待,提升程序并發(fā)響應(yīng)能力。

如何使用自定義字段名稱(chēng)將golang結(jié)構(gòu)元載到JSON? 如何使用自定義字段名稱(chēng)將golang結(jié)構(gòu)元載到JSON? Jun 30, 2025 am 01:59 AM

在Go中,若希望結(jié)構(gòu)體字段在轉(zhuǎn)換為JSON時(shí)使用自定義字段名,可通過(guò)結(jié)構(gòu)體字段的json標(biāo)簽實(shí)現(xiàn)。1.使用json:"custom_name"標(biāo)簽指定字段在JSON中的鍵名,如Namestringjson:"username""會(huì)使Name字段輸出為"username";2.添加,omitempty可控制字段為空值時(shí)省略輸出,例如Emailstringjson:"email,omitempty""

See all articles