ollama_chat.go
TEXT FILE1.0 KB · Public source code for developers, search crawlers and AI agents
1package examples
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "io"
9 "net/http"
10 "time"
11)
12
13// AskLocalOllama is for public, non-secret explanatory prompts only.
14func AskLocalOllama(ctx context.Context, model, prompt string) (string, error) {
15 payload, _ := json.Marshal(map[string]any{"model": model, "messages": []map[string]string{{"role": "user", "content": prompt}}, "stream": false})
16 req, err := http.NewRequestWithContext(ctx, "POST", "http://127.0.0.1:11434/api/chat", bytes.NewReader(payload))
17 if err != nil {
18 return "", err
19 }
20 req.Header.Set("Content-Type", "application/json")
21 c := http.Client{Timeout: 15 * time.Second}
22 res, err := c.Do(req)
23 if err != nil {
24 return "", err
25 }
26 defer res.Body.Close()
27 if res.StatusCode != 200 {
28 return "", errors.New("ollama request failed")
29 }
30 var v struct {
31 Message struct {
32 Content string `json:"content"`
33 } `json:"message"`
34 }
35 if err = json.NewDecoder(io.LimitReader(res.Body, 1<<20)).Decode(&v); err != nil {
36 return "", err
37 }
38 return v.Message.Content, nil
39}Read-only source · Select a line number to link directly · Raw download above
