1+ package ollama
2+
3+ import (
4+ "fmt"
5+ "net/http"
6+ "encoding/json"
7+ "bytes"
8+ "io"
9+
10+ "github.com/dfanso/commit-msg/pkg/types"
11+
12+ )
13+
14+ type OllamaRequest struct {
15+ Model string `json:"model"`
16+ Prompt string `json:"prompt"`
17+ }
18+
19+ type OllamaResponse struct {
20+ Response string `json:"response"`
21+ Done bool `json:"done"`
22+ }
23+
24+ func GenerateCommitMessage (_ * types.Config , changes string , url string , model string ) (string , error ) {
25+ // Use llama3:latest as the default model
26+ if model == "" {
27+ model = "llama3:latest"
28+ }
29+
30+ // Preparing the prompt
31+ prompt := fmt .Sprintf ("%s\n \n %s" , types .CommitPrompt , changes )
32+
33+ // Generating the request body - add stream: false for non-streaming response
34+ reqBody := map [string ]interface {}{
35+ "model" : model ,
36+ "prompt" : prompt ,
37+ "stream" : false ,
38+ }
39+
40+ // Generating the body
41+ body , err := json .Marshal (reqBody )
42+ if err != nil {
43+ return "" , fmt .Errorf ("failed to marshal request: %v" , err )
44+ }
45+
46+ resp , err := http .Post (url , "application/json" , bytes .NewBuffer (body ))
47+ if err != nil {
48+ return "" , fmt .Errorf ("failed to send request to Ollama: %v" , err )
49+ }
50+ defer resp .Body .Close ()
51+
52+ // Read the full response body for better error handling
53+ responseBody , err := io .ReadAll (resp .Body )
54+ if err != nil {
55+ return "" , fmt .Errorf ("failed to read response body: %v" , err )
56+ }
57+
58+ // Check HTTP status
59+ if resp .StatusCode != http .StatusOK {
60+ return "" , fmt .Errorf ("Ollama API returned status %d: %s" , resp .StatusCode , string (responseBody ))
61+ }
62+
63+ // Since we set stream: false, we get a single response object
64+ var response OllamaResponse
65+ if err := json .Unmarshal (responseBody , & response ); err != nil {
66+ return "" , fmt .Errorf ("failed to decode response: %v" , err )
67+ }
68+
69+ // Check if we got any response
70+ if response .Response == "" {
71+ return "" , fmt .Errorf ("received empty response from Ollama" )
72+ }
73+
74+ return response .Response , nil
75+ }
0 commit comments