Mistral
Mistral 平台(https://mistral.ai)提供了一系列不同级别的模型,适用于不同的任务。
本示例演示了如何使用 LangChain 与 Mistral 模型进行交互,并通过 LangChainGo 包装器从 Mistral API 获取流式和非流式的完成结果的示例。
配置API密钥
有以下两种方法可以设置 Mistral 平台的 API 密钥:
- 我们可以通过将环境变量
MISTRAL_API_KEY
设置为 API 密钥来实现。 - 或者,我们可以在初始化包装器时通过其他参数一起进行设置:
model, err := mistral.New(mistral.WithAPIKey(apiKey))
设置模型名称
如上所述,Mistral 平台上提供了许多不同的模型。我们在初始化包装器时可以设置模型名称,并且在执行完成操作时可以通过 langchaingo
覆盖它。
model, err := mistral.New(mistral.WithAPIKey(apiKey), mistral.WithModel("mistral-small-latest"))
- 当前 Mistral.ai 上列出的模型:
open-mistral-7b
(也称为 mistral-tiny-2312)open-mixtral-8x7b
(也称为 mistral-small-2312):注意: 目前似乎无法通过 mistral-go 客户端库使用。mistral-small-latest
(也称为 mistral-small-2402)mistral-medium-latest
(也称为 mistral-medium-2312)mistral-large-latest
(也称为 mistral-large-2402)
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)
}