84 lines
2.3 KiB
Go
84 lines
2.3 KiB
Go
package main
|
|||
|
|
|
||
|
|
import (
|
||
|
|
"bytes"
|
||
|
|
"context"
|
||
|
|
"encoding/json"
|
||
|
|
"fmt"
|
||
|
|
"io"
|
||
|
|
"net/http"
|
||
|
|
"os"
|
||
|
|
"strings"
|
||
|
|
"time"
|
||
|
|
|
||
|
|
"github.com/descrybe/descrybe-v2/apps/api/internal/config"
|
||
|
|
"github.com/descrybe/descrybe-v2/apps/api/internal/db"
|
||
|
|
"github.com/descrybe/descrybe-v2/apps/api/internal/platformsettings"
|
||
|
|
)
|
||
|
|
|
||
|
|
func main() {
|
||
|
|
cfg, err := config.Load()
|
||
|
|
if err != nil {
|
||
|
|
fmt.Println("config:", err)
|
||
|
|
os.Exit(1)
|
||
|
|
}
|
||
|
|
ctx := context.Background()
|
||
|
|
pool, err := db.NewPool(ctx, cfg.DatabaseURL, db.PoolOptions{
|
||
|
|
MaxConns: 2,
|
||
|
|
MinConns: 1,
|
||
|
|
HealthCheckPeriod: 30 * time.Second,
|
||
|
|
MaxConnLifetime: time.Hour,
|
||
|
|
MaxConnIdleTime: 30 * time.Minute,
|
||
|
|
})
|
||
|
|
if err != nil {
|
||
|
|
fmt.Println("db:", err)
|
||
|
|
os.Exit(1)
|
||
|
|
}
|
||
|
|
defer pool.Close()
|
||
|
|
plat := platformsettings.NewService(pool, platformsettings.EnvConfig{
|
||
|
|
AppEncryptionKey: cfg.AppEncryptionKey,
|
||
|
|
CredentialsEncryptionKey: cfg.CredentialsEncryptionKey,
|
||
|
|
TokenSigningSecret: cfg.TokenSigningSecret,
|
||
|
|
DatabaseURL: cfg.DatabaseURL,
|
||
|
|
OpenAIAPIKey: cfg.OpenAIAPIKey,
|
||
|
|
OpenAIBaseURL: cfg.OpenAIBaseURL,
|
||
|
|
OpenAIModel: cfg.OpenAIModel,
|
||
|
|
})
|
||
|
|
rc, err := plat.ResolveAIConfig(ctx, platformsettings.AIRoleProcessing)
|
||
|
|
if err != nil {
|
||
|
|
fmt.Println("resolve:", err)
|
||
|
|
os.Exit(1)
|
||
|
|
}
|
||
|
|
base := strings.TrimRight(strings.TrimSpace(rc.BaseURL), "/")
|
||
|
|
url := base + "/chat/completions"
|
||
|
|
body := map[string]any{
|
||
|
|
"model": rc.Model,
|
||
|
|
"messages": []map[string]string{
|
||
|
|
{"role": "user", "content": "Say PONG"},
|
||
|
|
},
|
||
|
|
"max_tokens": 16,
|
||
|
|
}
|
||
|
|
rawBody, _ := json.Marshal(body)
|
||
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(rawBody))
|
||
|
|
if err != nil {
|
||
|
|
fmt.Println("req:", err)
|
||
|
|
os.Exit(1)
|
||
|
|
}
|
||
|
|
req.Header.Set("Content-Type", "application/json")
|
||
|
|
req.Header.Set("Authorization", "Bearer "+rc.APIKey)
|
||
|
|
cli := &http.Client{Timeout: 30 * time.Second}
|
||
|
|
resp, err := cli.Do(req)
|
||
|
|
if err != nil {
|
||
|
|
fmt.Println("do:", err)
|
||
|
|
os.Exit(1)
|
||
|
|
}
|
||
|
|
defer resp.Body.Close()
|
||
|
|
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1200))
|
||
|
|
s := string(raw)
|
||
|
|
s = strings.ReplaceAll(s, rc.APIKey, "[redacted]")
|
||
|
|
fmt.Printf("source=%s provider=%s model=%s\n", rc.Source, rc.Provider, rc.Model)
|
||
|
|
fmt.Printf("url=%s status=%d bytes=%d\n", url, resp.StatusCode, len(raw))
|
||
|
|
fmt.Printf("content_type=%s\n", resp.Header.Get("Content-Type"))
|
||
|
|
fmt.Printf("body_head=%q\n", s)
|
||
|
|
}
|