搜索
首页后端开发GolangGo 调用 LangChain(一)

Calling LangChain from Go (Part 1)

动机

在使用 Golang 和 LLM 进行“假期”测试(之前的帖子...)之后,我一直在寻找一种在 Go 中实现 LangChain 调用的简单方法,最好使用 watsonx.ai

幸运的是,我找到了以下 Github 存储库:https://github.com/tmc/langchaingo(向 Travis Cline 行屈膝礼 https://github.com/tmc)。

在他的存储库中,有一个特定的文件夹:https://github.com/tmc/langchaingo/blob/main/examples/watsonx-llm-example/watsonx_example.go 引起了我的注意!

所以像往常一样,我建立了一个项目并尝试实现它,并提出了我自己的想法(à ma酱?)。

执行

像往常一样需要环境变量,我设置了一个 .env 文件,稍后在应用程序中使用。

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" 

在上一篇文章中,我提到尝试计算法学硕士发送和接收的代币数量。这项工作仍在进行中,因此我直接在应用程序中使用了“tiktoken-go”库,并打算对其进行一些更改(在不久的将来?)。无论如何,就我目前的进度而言,它并没有真正起作用,但它就在那里。

对于应用程序本身,我几乎按原样使用了 Travis 存储库中的代码,并添加和包装了以下功能;

  • 使用对话框进行提示输入(?我喜欢对话框?)
  • 尝试”计算发送给法学硕士和从法学硕士收到的“令牌”数量。 代码本身如下;
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

瞧!

后续步骤

我将为版本 0.2 实现以下功能;

  • 提出用户想要使用的模型,
  • 确定令牌数量的更准确方法,
  • 一些真正的LangChain实现。

结论

这是我从 Go 应用程序调用 LangChain 的工作的一个非常简单的反映。

敬请期待更多精彩内容?

以上是Go 调用 LangChain(一)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
您如何使用PPROF工具分析GO性能?您如何使用PPROF工具分析GO性能?Mar 21, 2025 pm 06:37 PM

本文解释了如何使用PPROF工具来分析GO性能,包括启用分析,收集数据并识别CPU和内存问题等常见的瓶颈。

您如何在GO中编写单元测试?您如何在GO中编写单元测试?Mar 21, 2025 pm 06:34 PM

本文讨论了GO中的编写单元测试,涵盖了最佳实践,模拟技术和有效测试管理的工具。

如何编写模拟对象和存根以进行测试?如何编写模拟对象和存根以进行测试?Mar 10, 2025 pm 05:38 PM

本文演示了创建模拟和存根进行单元测试。 它强调使用接口,提供模拟实现的示例,并讨论最佳实践,例如保持模拟集中并使用断言库。 文章

如何定义GO中仿制药的自定义类型约束?如何定义GO中仿制药的自定义类型约束?Mar 10, 2025 pm 03:20 PM

本文探讨了GO的仿制药自定义类型约束。 它详细介绍了界面如何定义通用功能的最低类型要求,从而改善了类型的安全性和代码可重复使用性。 本文还讨论了局限性和最佳实践

解释GO反射软件包的目的。您什么时候使用反射?绩效有什么影响?解释GO反射软件包的目的。您什么时候使用反射?绩效有什么影响?Mar 25, 2025 am 11:17 AM

本文讨论了GO的反思软件包,用于运行时操作代码,对序列化,通用编程等有益。它警告性能成本,例如较慢的执行和更高的内存使用,建议明智的使用和最佳

您如何在GO中使用表驱动测试?您如何在GO中使用表驱动测试?Mar 21, 2025 pm 06:35 PM

本文讨论了GO中使用表驱动的测试,该方法使用测试用例表来测试具有多个输入和结果的功能。它突出了诸如提高的可读性,降低重复,可伸缩性,一致性和A

如何使用跟踪工具了解GO应用程序的执行流?如何使用跟踪工具了解GO应用程序的执行流?Mar 10, 2025 pm 05:36 PM

本文使用跟踪工具探讨了GO应用程序执行流。 它讨论了手册和自动仪器技术,比较诸如Jaeger,Zipkin和Opentelemetry之类的工具,并突出显示有效的数据可视化

您如何在go.mod文件中指定依赖项?您如何在go.mod文件中指定依赖项?Mar 27, 2025 pm 07:14 PM

本文讨论了通过go.mod,涵盖规范,更新和冲突解决方案管理GO模块依赖关系。它强调了最佳实践,例如语义版本控制和定期更新。

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.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
2 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
2 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

安全考试浏览器

安全考试浏览器

Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。