initial
This commit is contained in:
@@ -0,0 +1,223 @@
|
||||
// Websuche über das Suchwerkzeug von OpenRouter (openrouter:web_search), z.B. mit Firecrawl oder Perplexity.
|
||||
// OpenRouter führt die Suche aus, ein Modell ruft sie auf und reicht die Treffer durch.
|
||||
|
||||
package openrouter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gitea.karlbreuer.com/karl/research/pkg/settings"
|
||||
)
|
||||
|
||||
// gilt, wenn der Aufrufer keine Frist nennt
|
||||
const searchTimeout = 120 * time.Second
|
||||
|
||||
// so viel Text je Treffer bekommt das Modell, gebraucht werden nur die URLs
|
||||
const searchMaxCharacters = 300
|
||||
|
||||
const searchSystem = "You are a web search relay. Call the web search tool exactly once, with the user's message as the query, unchanged. " +
|
||||
"Then respond with only the URLs of the search results, one per line, in the order of the results. " +
|
||||
"No other text and no URLs that are not in the results."
|
||||
|
||||
// SearchResult ist eine Fundstelle der Websuche.
|
||||
type SearchResult struct {
|
||||
URL string
|
||||
Title string
|
||||
}
|
||||
|
||||
type searchRespT struct {
|
||||
Model string `json:"model"`
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
Annotations []struct {
|
||||
Type string `json:"type"`
|
||||
URLCitation struct {
|
||||
URL string `json:"url"`
|
||||
Title string `json:"title"`
|
||||
} `json:"url_citation"`
|
||||
} `json:"annotations"`
|
||||
} `json:"message"`
|
||||
Error *chatErrT `json:"error"`
|
||||
} `json:"choices"`
|
||||
Usage struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
Cost float64 `json:"cost"`
|
||||
// der Name des Feldes unterscheidet sich je nach API
|
||||
ServerToolUse *struct {
|
||||
WebSearchRequests int `json:"web_search_requests"`
|
||||
} `json:"server_tool_use"`
|
||||
ServerToolUseDetails *struct {
|
||||
WebSearchRequests int `json:"web_search_requests"`
|
||||
} `json:"server_tool_use_details"`
|
||||
} `json:"usage"`
|
||||
Error *chatErrT `json:"error"`
|
||||
}
|
||||
|
||||
var urlRe = regexp.MustCompile(`https?://[^\s<>"'\]]+`)
|
||||
|
||||
// WebSearch sucht mit einer Engine von OpenRouter: firecrawl, perplexity, exa oder parallel.
|
||||
// models ist wie bei Ask eine Rangfolge, das Modell muss Werkzeuge aufrufen können.
|
||||
// Die Treffer stammen aus den Quellenangaben, die OpenRouter an die Antwort hängt,
|
||||
// ergänzt um die URLs, die das Modell auflistet.
|
||||
// Die Suche kostet zusätzlich zu den Token des Modells, Firecrawl rechnet je Treffer ab.
|
||||
// timeout ist die Frist für den ganzen Aufruf, 0 heißt searchTimeout.
|
||||
func WebSearch(query, engine string, maxResults int, models []string, timeout time.Duration) ([]SearchResult, Usage, error) {
|
||||
if timeout <= 0 {
|
||||
timeout = searchTimeout
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
|
||||
var u Usage
|
||||
apiKey := settings.Get().OPENROUTER_KEY
|
||||
if apiKey == "" {
|
||||
return nil, u, errors.New("OPENROUTER_KEY nicht gesetzt")
|
||||
}
|
||||
query = strings.TrimSpace(query)
|
||||
if query == "" {
|
||||
return nil, u, errors.New("leere suchanfrage")
|
||||
}
|
||||
if engine == "" || maxResults <= 0 {
|
||||
return nil, u, errors.New("engine oder trefferzahl fehlt")
|
||||
}
|
||||
|
||||
for {
|
||||
active := usableModels(models)
|
||||
if len(active) == 0 {
|
||||
return nil, u, fmt.Errorf("kein gültiges modell in %v", models)
|
||||
}
|
||||
res, usage, err := searchOnce(ctx, apiKey, active, query, engine, maxResults)
|
||||
// abgelehnt, bevor ein Modell gefragt wurde: ohne den falschen Namen erneut senden
|
||||
if err != nil && dropInvalid(err, active) {
|
||||
continue
|
||||
}
|
||||
return res, usage, err
|
||||
}
|
||||
}
|
||||
|
||||
func searchOnce(ctx context.Context, apiKey string, models []string, query, engine string, maxResults int) ([]SearchResult, Usage, error) {
|
||||
var u Usage
|
||||
params := map[string]any{
|
||||
"engine": engine,
|
||||
"max_results": maxResults,
|
||||
// deckelt die Treffer und damit die Kosten, auch wenn das Modell mehrfach sucht
|
||||
"max_total_results": maxResults,
|
||||
}
|
||||
// Firecrawl kennt die Angabe nicht
|
||||
if engine != "firecrawl" {
|
||||
params["max_characters"] = searchMaxCharacters
|
||||
}
|
||||
body := map[string]any{
|
||||
"messages": []map[string]string{
|
||||
{"role": "system", "content": searchSystem},
|
||||
{"role": "user", "content": query},
|
||||
},
|
||||
"tools": []map[string]any{
|
||||
{"type": "openrouter:web_search", "parameters": params},
|
||||
},
|
||||
}
|
||||
if len(models) == 1 {
|
||||
body["model"] = models[0]
|
||||
} else {
|
||||
body["models"] = models
|
||||
}
|
||||
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
return nil, u, fmt.Errorf("request marshal: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, chatURL, bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
return nil, u, fmt.Errorf("request bauen: %w", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
|
||||
resp, err := chatClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, u, fmt.Errorf("request senden: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
out, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, u, fmt.Errorf("body lesen: %w", err)
|
||||
}
|
||||
|
||||
var parsed searchRespT
|
||||
jerr := json.Unmarshal(out, &parsed)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
msg := strings.TrimSpace(string(out))
|
||||
if jerr == nil && parsed.Error != nil && parsed.Error.Message != "" {
|
||||
msg = parsed.Error.Message
|
||||
}
|
||||
return nil, u, &Error{resp.StatusCode, msg}
|
||||
}
|
||||
if jerr != nil {
|
||||
return nil, u, fmt.Errorf("antwort unmarshal: %w; rohausgabe: %s", jerr, string(out))
|
||||
}
|
||||
|
||||
u = Usage{
|
||||
Model: parsed.Model,
|
||||
PromptTokens: parsed.Usage.PromptTokens,
|
||||
CompletionTokens: parsed.Usage.CompletionTokens,
|
||||
Cost: parsed.Usage.Cost,
|
||||
}
|
||||
if u.Model == "" {
|
||||
u.Model = models[0]
|
||||
}
|
||||
if parsed.Error != nil {
|
||||
return nil, u, parsed.Error.asError()
|
||||
}
|
||||
if len(parsed.Choices) == 0 {
|
||||
return nil, u, errors.New("antwort ohne choices")
|
||||
}
|
||||
ch := parsed.Choices[0]
|
||||
if ch.Error != nil {
|
||||
return nil, u, ch.Error.asError()
|
||||
}
|
||||
|
||||
var res []SearchResult
|
||||
seen := map[string]bool{}
|
||||
add := func(url, title string) {
|
||||
url = strings.TrimRight(strings.TrimSpace(url), ".,;:)")
|
||||
if url != "" && !seen[url] {
|
||||
seen[url] = true
|
||||
res = append(res, SearchResult{url, strings.TrimSpace(title)})
|
||||
}
|
||||
}
|
||||
// Quellenangaben kommen direkt von der Suche
|
||||
for _, a := range ch.Message.Annotations {
|
||||
if a.Type == "url_citation" {
|
||||
add(a.URLCitation.URL, a.URLCitation.Title)
|
||||
}
|
||||
}
|
||||
cited := len(res)
|
||||
for _, m := range urlRe.FindAllString(ch.Message.Content, -1) {
|
||||
add(m, "")
|
||||
}
|
||||
|
||||
searches := 0
|
||||
if s := parsed.Usage.ServerToolUse; s != nil {
|
||||
searches += s.WebSearchRequests
|
||||
}
|
||||
if s := parsed.Usage.ServerToolUseDetails; s != nil {
|
||||
searches += s.WebSearchRequests
|
||||
}
|
||||
// ohne Beleg für eine Suche können die URLs vom Modell erfunden sein
|
||||
if len(res) > 0 && cited == 0 && searches == 0 {
|
||||
OnWarning(fmt.Sprintf("suche mit %s: die antwort belegt keine ausgeführte suche, die urls sind ungeprüft", engine))
|
||||
}
|
||||
return res, u, nil
|
||||
}
|
||||
Reference in New Issue
Block a user