Files
crowsnest/src/internal/util/openai.go

89 lines
1.8 KiB
Go
Raw Normal View History

2025-01-20 20:34:23 +01:00
package util
import (
"bytes"
"encoding/json"
"errors"
"fmt"
2025-01-20 21:20:23 +01:00
"io"
2025-01-20 20:34:23 +01:00
"net/http"
)
2025-01-27 09:17:25 +01:00
type response struct {
2025-01-20 20:34:23 +01:00
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
2025-01-27 09:17:25 +01:00
type OpenAi struct {
ApiKey string
}
func (oai *OpenAi) Summarize(text string) (string, error) {
apiURL := "https://openrouter.ai/api/v1/chat/completions"
2025-01-20 20:34:23 +01:00
// Request payload
payload := map[string]interface{}{
"model": "google/gemini-2.5-flash-lite",
2025-01-20 20:34:23 +01:00
"messages": []map[string]string{
{
"role": "system",
2025-01-20 20:34:23 +01:00
"content": "Fasse den folgenden Zeitungsartikel in maximal 75 Wörtern zusammen. Konzentriere dich auf die wichtigsten Informationen, wie das Hauptthema, die zentralen Aussagen und relevante Hintergründe. Gib **außschließlich** die Zusammenfassung zurück.",
},
{
"role": "user",
"content": text,
},
},
}
// Convert payload to JSON
jsonData, err := json.Marshal(payload)
if err != nil {
return "", err
}
// Create an HTTP request
req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonData))
if err != nil {
return "", err
}
// Add headers
req.Header.Set("Content-Type", "application/json")
2025-01-27 09:17:25 +01:00
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", oai.ApiKey))
2025-01-20 20:34:23 +01:00
// Send the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Read the response
2025-01-20 21:20:23 +01:00
body, err := io.ReadAll(resp.Body)
2025-01-20 20:34:23 +01:00
if err != nil {
return "", err
}
2025-01-20 21:20:23 +01:00
// Unmarshal the JSON response
2025-01-27 09:17:25 +01:00
var response response
2025-01-20 20:34:23 +01:00
err = json.Unmarshal(body, &response)
if err != nil {
2025-01-20 21:20:23 +01:00
return "", err
2025-01-20 20:34:23 +01:00
}
// Extract and print the content
2025-01-20 21:20:23 +01:00
var content string
2025-01-20 20:34:23 +01:00
if len(response.Choices) > 0 {
content = response.Choices[0].Message.Content
} else {
2025-01-20 21:20:23 +01:00
return "", errors.New("could not find content in response")
2025-01-20 20:34:23 +01:00
}
2025-01-20 21:20:23 +01:00
return content, nil
2025-01-20 20:34:23 +01:00
}