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"
"os"
)
type Response struct {
Choices [ ] struct {
Message struct {
Content string ` json:"content" `
} ` json:"message" `
} ` json:"choices" `
}
func Summarize ( text string ) ( string , error ) {
apiURL := "https://api.openai.com/v1/chat/completions"
apiKey := os . Getenv ( "OPENAI_API_KEY" )
// Request payload
payload := map [ string ] interface { } {
"model" : "gpt-4o-mini" ,
"messages" : [ ] map [ string ] string {
{
"role" : "developer" ,
"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" , apiKey ) )
// 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-20 20:34:23 +01:00
var response Response
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
}