mirror of
https://github.com/tiennm99/goclaw.git
synced 2026-10-13 00:14:33 +00:00
- HTTP synthesize + test-connection now read tenant tts.timeout_ms (default 120s, was hardcoded 15s/10s). Gemini client default also bumped 30s→120s so both layers align when tenant config unset. - Inline prefix "Speak naturally: " prepended to single-voice text; multi-speaker transcripts pass through unchanged. - ErrTextOnlyResponse sentinel for 400 "text generation" bodies; single-voice retries once with stronger prefix. Narrowed needle list avoids false positives on unrelated 400s. - SynthesizeWithFallbackAdapted now returns errors.Join so sentinel survives fallback chain; HTTP 422 mapping + locale-translated ForLLM in agent tool (EN/VI/ZH catalogs). - Default Gemini model bumped to gemini-3.1-flash-tts-preview.
62 lines
1.7 KiB
Go
62 lines
1.7 KiB
Go
package gemini
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const defaultAPIBase = "https://generativelanguage.googleapis.com"
|
|
|
|
// client handles HTTP communication with the Gemini generateContent API.
|
|
type client struct {
|
|
apiKey string
|
|
apiBase string
|
|
timeoutMs int
|
|
}
|
|
|
|
func newClient(apiKey, apiBase string, timeoutMs int) *client {
|
|
base := strings.TrimRight(apiBase, "/")
|
|
if base == "" {
|
|
base = defaultAPIBase
|
|
}
|
|
if timeoutMs <= 0 {
|
|
timeoutMs = 120000 // match handler default; tenant Config.TimeoutMs=0 → 120s (was 30s)
|
|
}
|
|
return &client{apiKey: apiKey, apiBase: base, timeoutMs: timeoutMs}
|
|
}
|
|
|
|
// buildURL constructs the generateContent endpoint URL for a given model.
|
|
func buildURL(base, model string) string {
|
|
base = strings.TrimRight(base, "/")
|
|
return base + "/v1beta/models/" + model + ":generateContent"
|
|
}
|
|
|
|
// post sends a JSON body to the Gemini API and returns the raw response bytes.
|
|
func (c *client) post(ctx context.Context, model string, body []byte) ([]byte, int, error) {
|
|
url := buildURL(c.apiBase, model)
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
|
|
if err != nil {
|
|
return nil, 0, fmt.Errorf("gemini: create request: %w", err)
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("x-goog-api-key", c.apiKey)
|
|
|
|
hc := &http.Client{Timeout: time.Duration(c.timeoutMs) * time.Millisecond}
|
|
resp, err := hc.Do(req)
|
|
if err != nil {
|
|
return nil, 0, fmt.Errorf("gemini: request failed: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
respBody, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, resp.StatusCode, fmt.Errorf("gemini: read response: %w", err)
|
|
}
|
|
return respBody, resp.StatusCode, nil
|
|
}
|