Unofficial Golang client library for Mistral AI platform
go get github.com/robertjkeck2/mistral-go
Requires Go 1.21 or later
package main
import (
"context"
"fmt"
"os"
"github.com/robertjkeck2/go-mistral"
)
func main() {
client := mistral.NewMistralClient(os.Getenv("MISTRAL_API_KEY"))
resp, err := client.CreateChatCompletion(
context.Background(),
mistral.ChatCompletionRequest{
Model: "mistral-tiny",
Messages: []mistral.ChatMessage{{Role: mistral.RoleUser, Content: "What is the best French cheese?"}},
},
)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(resp.Choices[0].Message.Content)
}
- Sign up for a Mistral account at https://console.mistral.ai/.
- If you don't already have one, create an account.
- In the
Your subscription
section, clickManage
. - Update your billing information in the
Billing information
section. - Create a new subscription in the
Current subscription
section. - Go to the
API Keys
tab in the left sidebar. - Click
Generate a new key
and copy the key. Save the key somewhere safe and do not share this key with anyone.
Chat Completion Streaming
package main
import (
"context"
"errors"
"fmt"
"io"
"os"
"github.com/robertjkeck2/go-mistral"
)
func main() {
client := mistral.NewMistralClient(os.Getenv("MISTRAL_API_KEY"))
stream, err := client.CreateChatCompletionStream(
context.Background(),
mistral.ChatCompletionRequest{
Model: "mistral-tiny",
Messages: []mistral.ChatMessage{{Role: mistral.RoleUser, Content: "What is the best French cheese?"}},
},
)
if err != nil {
fmt.Println(err)
return
}
defer stream.Close()
for {
var response mistral.ChatCompletionStreamResponse
response, err = stream.Recv()
if errors.Is(err, io.EOF) {
return
}
if err != nil {
fmt.Println(err)
return
}
fmt.Printf(response.Choices[0].Delta.Content)
}
}
Embeddings
package main
import (
"context"
"fmt"
"os"
"github.com/robertjkeck2/go-mistral"
)
func main() {
client := mistral.NewMistralClient(os.Getenv("MISTRAL_API_KEY"))
resp, err := client.CreateEmbedding(
context.Background(),
mistral.EmbeddingRequest{
Model: "mistral-embed",
Input: []string{"What is the best French cheese?"},
},
)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(resp.Data[0].Embedding)
}
List Models
package main
import (
"context"
"fmt"
"os"
"github.com/robertjkeck2/go-mistral"
)
func main() {
client := mistral.NewMistralClient(os.Getenv("MISTRAL_API_KEY"))
resp, err := client.ListModels(context.Background())
if err != nil {
fmt.Println(err)
return
}
if len(resp.Data) == 0 {
fmt.Println("No models found")
return
}
for _, model := range resp.Data {
fmt.Println(model.ID)
}
}
Contributions are welcome! Please see CONTRIBUTING.md for more information.
This project is licensed under the MIT License - see the LICENSE file for details.