DEV Community

Cover image for LangChain Go
Stefan Alfbo
Stefan Alfbo

Posted on

LangChain Go

LangChain is a very popular framework for developing applications powered by large language models (LLMs). This framework is written in Python and was released as an open source project by Harrison Chase.

The good news is that Travis Cline has made a LangChain implementation in Go for us that like to tinker with that language.

There is lot of examples on how to use the framework on their GitHub repository. However here is another quickstart example to get started with LangChain in Go.

Initialize the project (we will be using the OpenAI API in this example).

mkdir langchain-example && cd $_

go mod init langchain.example
touch main.go

export OPENAI_API_KEY="<your OpenAI API key>"

code .
Enter fullscreen mode Exit fullscreen mode

We will need two packages in this example, so let add those dependencies.

go get github.com/tmc/langchaingo/llms github.com/tm
c/langchaingo/llms/openai
Enter fullscreen mode Exit fullscreen mode

The llms package provides providers for interacting with different LLMs, and in this example we want to use the openai provider.

Open the main.go file and lets add some code. First we add an OpenAI LLM client with this code.

llm, err := openai.New()
if err != nil {
    log.Fatal(err)
}
Enter fullscreen mode Exit fullscreen mode

Now we are ready to write a simple prompt and interact with the LLM, lets use the following prompt, What is Go?. This can be done with the function GenerateFromSinglePrompt, which require a context, a llm and a prompt, but we can also pass some options, if we want more control.

ctx := context.Background()
prompt := "What is Go?"
content, err := llms.GenerateFromSinglePrompt(
    ctx,
    llm,
    prompt,
)
if err != nil {
    log.Fatal(err)
}
Enter fullscreen mode Exit fullscreen mode

That's all that is needed, here is the complete main.go file.

package main

import (
    "context"
    "fmt"

    "github.com/tmc/langchaingo/llms"
    "github.com/tmc/langchaingo/llms/openai"
)

func main() {
    llm, err := openai.New()
    if err != nil {
        fmt.Println(err)
    }

    ctx := context.Background()
    prompt := "What is Go?"
    content, err := llms.GenerateFromSinglePrompt(
        ctx,
        llm,
        prompt,
    )
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println(content)
}
Enter fullscreen mode Exit fullscreen mode

So if we run the program, go run main.go, we will get this response.

Go, also known as Golang, is a statically typed, compiled programming language developed by Google. It was designed to be efficient, reliable, and easy to use for building scalable and high-performance software. Go is often used for web development, cloud computing, and system programming. It features a simple and clean syntax, built-in support for concurrency, and a strong standard library.

Nice, that was easy, so give it a try!

Happy prompting!

Top comments (0)