Quickstart: LangChainGo with OpenAI
Get started by running your first program with LangChainGo and OpenAI. OpenAI's GPT models are renowned for their proficiency and expansive capabilities.
Prerequisites
- OpenAI API Key: Sign up on OpenAI and retrieve your API key.
- Go: Download and install Go.
Setup
Before interacting with the OpenAI API, you need to set up your API key as an environment variable.
Linux/macOS (bash/zsh)
export OPENAI_API_KEY="your_openai_api_key_here"
Windows (Command Prompt)
set OPENAI_API_KEY=your_openai_api_key_here
Windows (PowerShell)
$env:OPENAI_API_KEY="your_openai_api_key_here"
For permanent setup, add the environment variable to your shell's profile file (~/.bashrc
, ~/.zshrc
, etc.) or system environment variables on Windows.
Steps
-
Set up your OpenAI API Key: Follow the setup instructions above to configure your API key.
-
Run the example: Execute the following command:
go run github.com/tmc/langchaingo/examples/openai-completion-example@main
You should see output similar to the following:
The first man to walk on the moon was Neil
Congratulations! You have successfully built and executed your first LangChainGo LLM-backed program using OpenAI's cloud-based inference.
Here is the entire program (from openai-completion-example):
package main
import (
"context"
"fmt"
"log"
"github.com/tmc/langchaingo/llms"
"github.com/tmc/langchaingo/llms/openai"
)
func main() {
llm, err := openai.New()
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
completion, err := llms.GenerateFromSinglePrompt(ctx,
llm,
"The first man to walk on the moon",
llms.WithTemperature(0.8),
llms.WithStopWords([]string{"Armstrong"}),
)
if err != nil {
log.Fatal(err)
}
fmt.Println("The first man to walk on the moon:")
fmt.Println(completion)
}