Golang에서 Ollama API 사용하기

AI 실습 튜토리얼4 개월 전에 게시 됨 Sharenet.ai
643 0
吐司AI

이 문서에서는 Ollama 이 문서는 개발자가 Ollama의 기능을 빠르게 익히고 최대한 활용할 수 있도록 돕기 위해 작성되었습니다. Ollama 자체는 골랑 언어로 개발되었으며, 골랑 언어 버전의 인터페이스 코드는 공식 저장소 디렉토리(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 version이 문서에서 사용된 골랑 버전은 다음과 같습니다.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
© 저작권 정책
AiPPT

관련 문서

댓글 없음

없음
댓글 없음...