Files
crowsnest/src/internal/util/openai.go
Elias Kohout c30a9f3f3e
All checks were successful
Build and Push Docker Container / build-and-push (push) Successful in 2m1s
change ai provider from openai to openrouter
2026-02-14 20:00:19 +01:00

89 lines
1.8 KiB
Go

package util
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
type response struct {
Choices []struct {
Message struct {
Content string `json:"content"`
} `json:"message"`
} `json:"choices"`
}
type OpenAi struct {
ApiKey string
}
func (oai *OpenAi) Summarize(text string) (string, error) {
apiURL := "https://openrouter.ai/api/v1/chat/completions"
// Request payload
payload := map[string]interface{}{
"model": "google/gemini-2.5-flash-lite",
"messages": []map[string]string{
{
"role": "system",
"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")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", oai.ApiKey))
// Send the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
// Read the response
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
// Unmarshal the JSON response
var response response
err = json.Unmarshal(body, &response)
if err != nil {
return "", err
}
// Extract and print the content
var content string
if len(response.Choices) > 0 {
content = response.Choices[0].Message.Content
} else {
return "", errors.New("could not find content in response")
}
return content, nil
}