AIパーソナル・ラーニング
と実践的なガイダンス
TRAE

GolangでOllama APIを使う

この記事では オーラマ Ollama自体はGolang言語で開発されており、Golang言語版のインターフェース・コードは公式リポジトリ・ディレクトリ https://github.com/ollama/ollama/tree/main/api に、公式ドキュメントは https://github.com/ollama/ollama/tree/main/api にあります。公式ドキュメントは https://pkg.go.dev/github.com/ollama/ollama/api にあります。このドキュメントを学ぶことで、Ollama をあなたのプロジェクトに簡単に統合することができます。

公式リポジトリhttps://github.com/ollama/ollama/tree/main/api/examples提供了一些示例代、以下のコードはこれらのサンプルを参照し、修正したものです。すべてのサンプルはnotebook/C4/Golang_API_example真ん中

 

環境準備

作業を始める前に、開発環境が以下の条件を満たしていることを確認してください:

  1. Golang開発環境はgo versiongolangのバージョンをチェックしてください。go1.23.6

    参考 https://golang.google.cn/doc/install进行安装

  2. プロジェクト・ディレクトリを作成し、初期化する
mkdir ollama-demo && cd ollama-demo
go mod init ollama-demo
  1. 依存関係のインストール
go get github.com/ollama/ollama/api

 

使用方法

カタログの作成chatカタログにファイルを作成するmain.goこの例ではdeepseek-r1:7bモデルを使用している):

package main
import (
"context"
"fmt"
"log"
"github.com/ollama/ollama/api"
)
func main() {
client, err := api.ClientFromEnvironment()
if err != nil {
log.Fatal(err)
}
messages := []api.Message{
api.Message{
Role:    "user",
Content: "为什么天空是蓝色的?",
},
}
ctx := context.Background()
req := &api.ChatRequest{
Model:    "deepseek-r1:7b",
Messages: messages,
}
respFunc := func(resp api.ChatResponse) error {
fmt.Print(resp.Message.Content)
return nil
}
err = client.Chat(ctx, req, respFunc)
if err != nil {
log.Fatal(err)
}
}

うごきだす go run chat/main.go

 

ストリーミング出力

カタログの作成generate-streamingカタログにファイルを作成するmain.go

package main
import (
"context"
"fmt"
"log"
"github.com/ollama/ollama/api"
)
func main() {
client, err := api.ClientFromEnvironment()
if err != nil {
log.Fatal(err)
}
// By default, GenerateRequest is streaming.
req := &api.GenerateRequest{
Model:  "deepseek-r1:7b",
Prompt: "为什么天空是蓝色的?",
}
ctx := context.Background()
respFunc := func(resp api.GenerateResponse) error {
// Only print the response here; GenerateResponse has a number of other
// interesting fields you want to examine.
// In streaming mode, responses are partial so we call fmt.Print (and not
// Println) in order to avoid spurious newlines being introduced. The
// model will insert its own newlines if it wants.
fmt.Print(resp.Response)
return nil
}
err = client.Generate(ctx, req, respFunc)
if err != nil {
log.Fatal(err)
}
fmt.Println()
}

うごきだす go run generate-streaming/main.go


 

構造化出力

カタログの作成structured_outputカタログにファイルを作成するmain.go以下の通りである。

package main
import (
"context"
"encoding/json"
"fmt"
"log"
"strings"
"github.com/ollama/ollama/api"
)
type CountryInfo struct {
Capital    string  `json:"capital"`
Population float64 `json:"population"`
Area       float64 `json:"area"`
}
func main() {
client, err := api.ClientFromEnvironment()
if err != nil {
log.Fatal(err)
}
messages := []api.Message{
api.Message{
Role:    "user",
Content: "请介绍美国的首都、人口、占地面积信息,并以 JSON 格式返回。",
},
}
ctx := context.Background()
req := &api.ChatRequest{
Model:    "deepseek-r1:7b",
Messages: messages,
Stream:   new(bool), // false
Format:   []byte(`"json"`),
Options: map[string]interface{}{
"temperature": 0.0,
},
}
respFunc := func(resp api.ChatResponse) error {
fmt.Printf("%s\n", strings.TrimSpace(resp.Message.Content))
var info CountryInfo
err := json.Unmarshal([]byte(resp.Message.Content), &info)
if err != nil {
log.Fatal(err)
}
fmt.Printf("首都: %s,人口: %f,面积: %f", info.Capital, info.Population, info.Area)
return nil
}
err = client.Chat(ctx, req, respFunc)
if err != nil {
log.Fatal(err)
}
}

を指定する。ChatRequest依頼済みFormat: []byte("json"), このパラメータは、モデルが構造化されたデータを返すことを可能にします。json.Unmarshal返されたデータを解析する。

うごきだす go run structured_output/main.go 次のような出力が得られる:

{"capital": "Washington, D.C.", "population": 3.672e6, "area": 7.058e6}
首都: Washington, D.C.,人口: 3672000.000000,面积: 7058000.000000
無断転載を禁じます:チーフAIシェアリングサークル " GolangでOllama APIを使う
ja日本語