A 3rd-Party Golang Client Library for Zhipu AI Platform
go get -u github.com/yankeguo/zhipu
// this will use environment variables ZHIPUAI_API_KEY
client, err := zhipu.NewClient()
// or you can specify the API key
client, err = zhipu.NewClient(zhipu.WithAPIKey("your api key"))
ChatCompletion
service := client.ChatCompletionService("glm-4-flash").
AddMessage(zhipu.ChatCompletionMessage{
Role: "user",
Content: "你好",
})
res, err := service.Do(context.Background())
if err != nil {
zhipu.GetAPIErrorCode(err) // get the API error code
} else {
println(res.Choices[0].Message.Content)
}
ChatCompletion (Stream)
service := client.ChatCompletionService("glm-4-flash").
AddMessage(zhipu.ChatCompletionMessage{
Role: "user",
Content: "你好",
}).SetStreamHandler(func(chunk zhipu.ChatCompletionResponse) error {
println(chunk.Choices[0].Delta.Content)
return nil
})
res, err := service.Do(context.Background())
if err != nil {
zhipu.GetAPIErrorCode(err) // get the API error code
} else {
// this package will combine the stream chunks and build a final result mimicking the non-streaming API
println(res.Choices[0].Message.Content)
}
Embedding
service := client.EmbeddingService("embedding-v2").SetInput("你好呀")
service.Do(context.Background())
Image Generation
service := client.ImageGenerationService("cogview-3").SetPrompt("一只可爱的小猫咪")
service.Do(context.Background())
Upload File (Retrieval)
service := client.FileCreateService(zhipu.FilePurposeRetrieval)
service.SetLocalFile(filepath.Join("testdata", "test-file.txt"))
service.SetKnowledgeID("your-knowledge-id")
service.Do(context.Background())
Upload File (Fine-Tune)
service := client.FileCreateService(zhipu.FilePurposeFineTune)
service.SetLocalFile(filepath.Join("testdata", "test-file.jsonl"))
service.Do(context.Background())
Batch Create
service := client.BatchCreateService().
SetInputFileID("fileid").
SetCompletionWindow(zhipu.BatchCompletionWindow24h).
SetEndpoint(BatchEndpointV4ChatCompletions)
service.Do(context.Background())
Note
More APIs are coming soon.
Batch File Writer
f, err := os.OpenFile("batch.jsonl", os.O_CREATE|os.O_WRONLY, 0644)
bw := zhipu.NewBatchFileWriter(f)
bw.Add("action_1", client.ChatCompletionService("glm-4-flash").
AddMessage(zhipu.ChatCompletionMessage{
Role: "user",
Content: "你好",
}))
bw.Add("action_2", client.EmbeddingService("embedding-v2").SetInput("你好呀"))
bw.Add("action_3", client.ImageGenerationService("cogview-3").SetPrompt("一只可爱的小猫咪"))
GUO YANKE, MIT License