快速入门:使用LangChainGo和Mistral
通过运行第一个程序开始使用LangChainGo和Mistral平台。
先决条件
设置
在与Mistral API交互之前,您需要将API密钥设置为环境变量。
Linux/macOS (bash/zsh)
export MISTRAL_API_KEY="your_mistral_api_key_here"
Windows (命令提示符)
set MISTRAL_API_KEY=your_mistral_api_key_here
Windows (PowerShell)
$env:MISTRAL_API_KEY="your_mistral_api_key_here"
为了永久设置,可以将环境变量添加到shell配置文件(如~/.bashrc
, ~/.zshrc
等)或Windows系统环境变量中。
步骤
- 设置您的Mistral API密钥:按照上述说明配置API密钥。
- 运行示例程序:执行以下命令:
go run github.com/tmc/langchaingo/examples/mistral-completion-example@main
您应该会看到类似以下的输出:
首次踏上月球的人是尼尔·阿姆斯特朗,时间是在1969年7月20日。他在这次阿波罗11号任务中完成了这一历史性的步伐。阿姆斯特朗在登上月球表面时说出了著名的名言:“这是一个人的一小步,却是人类的一大步。”
首次进入太空的人是苏联宇航员尤里·加加林。他在1961年4月12日乘坐“东方一号”飞船完成了绕地球的轨道飞行。这一历史性的事件标志着人类太空探索的开始。
恭喜!您已成功构建并执行了第一个使用Mistral云端推理服务支持的LangChainGo LLM程序。
以下是整个程序(来自mistral-completion-example):
package main
import (
"context"
"fmt"
"log"
"github.com/tmc/langchaingo/llms"
"github.com/tmc/langchaingo/llms/mistral"
)
func main() {
llm, err := mistral.New(mistral.WithModel("open-mistral-7b"))
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
completionWithStreaming, err := llms.GenerateFromSinglePrompt(ctx, llm, "Who was the first man to walk on the moon?",
llms.WithTemperature(0.8),
llms.WithStreamingFunc(func(ctx context.Context, chunk []byte) error {
fmt.Print(string(chunk))
return nil
}),
)
if err != nil {
log.Fatal(err)
}
// The full string response will be available in completionWithStreaming after the streaming is complete.
// (The Go compiler mandates declared variables be used at least once, hence the `_` assignment. https://go.dev/ref/spec#Blank_identifier)
_ = completionWithStreaming
completionWithoutStreaming, err := llms.GenerateFromSinglePrompt(ctx, llm, "Who was the first man to go to space?",
llms.WithTemperature(0.2),
llms.WithModel("mistral-small-latest"),
)
if err != nil {
log.Fatal(err)
}
fmt.Println("\n" + completionWithoutStreaming)
}