gateway_web_search.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. package handler
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "strconv"
  10. "strings"
  11. "github.com/Wei-Shaw/sub2api/internal/pkg/ip"
  12. "github.com/Wei-Shaw/sub2api/internal/pkg/logger"
  13. "github.com/Wei-Shaw/sub2api/internal/pkg/websearch"
  14. "github.com/Wei-Shaw/sub2api/internal/pkg/xai"
  15. middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
  16. "github.com/Wei-Shaw/sub2api/internal/service"
  17. "github.com/gin-gonic/gin"
  18. "github.com/google/uuid"
  19. "github.com/tidwall/gjson"
  20. "go.uber.org/zap"
  21. )
  22. const (
  23. defaultGrokWebSearchResults = 5
  24. maxGrokWebSearchResults = 20
  25. )
  26. func (h *GatewayHandler) WebSearch(c *gin.Context) {
  27. isXSearch := c.GetBool("grok_x_search_endpoint")
  28. var req grokStandaloneSearchRequest
  29. if err := c.ShouldBindJSON(&req); err != nil {
  30. c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{
  31. "type": "invalid_request_error",
  32. "message": err.Error(),
  33. }})
  34. return
  35. }
  36. query := strings.TrimSpace(req.Query)
  37. if query == "" {
  38. query = strings.TrimSpace(req.Input)
  39. }
  40. if query == "" {
  41. c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{
  42. "type": "invalid_request_error",
  43. "message": "query is required",
  44. }})
  45. return
  46. }
  47. req.Query = query
  48. maxResults := 0
  49. if req.MaxResults != nil {
  50. maxResults = *req.MaxResults
  51. }
  52. maxResults = normalizeGrokWebSearchMaxResults(maxResults)
  53. searchModel := resolveGrokStandaloneSearchModel()
  54. searchLabel := "web_search"
  55. if isXSearch {
  56. searchLabel = "x_search"
  57. }
  58. apiKey, ok := middleware2.GetAPIKeyFromContext(c)
  59. if !ok || apiKey == nil {
  60. c.JSON(http.StatusUnauthorized, gin.H{"error": gin.H{
  61. "type": "authentication_error",
  62. "message": "API key required",
  63. }})
  64. return
  65. }
  66. if apiKey.Group == nil || apiKey.Group.Platform != "grok" {
  67. c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{
  68. "type": "invalid_request_error",
  69. "message": searchLabel + " is only supported for grok groups",
  70. }})
  71. return
  72. }
  73. // Billing eligibility (same as other requests)
  74. subscription, _ := middleware2.GetSubscriptionFromContext(c)
  75. if err := h.billingCacheService.CheckBillingEligibility(c.Request.Context(), apiKey.User, apiKey, apiKey.Group, subscription, service.QuotaPlatform(c.Request.Context(), apiKey)); err != nil {
  76. status, code, message, retryAfter := billingErrorDetails(err)
  77. if retryAfter > 0 {
  78. c.Header("Retry-After", strconv.Itoa(retryAfter))
  79. }
  80. c.JSON(status, gin.H{"error": gin.H{"type": code, "message": message}})
  81. return
  82. }
  83. subject, _ := middleware2.GetAuthSubjectFromContext(c)
  84. reqLog := requestLogger(c, "handler.gateway.web_search")
  85. // Audit user search query before upstream Grok web_search traffic.
  86. auditBody, _ := json.Marshal(map[string]any{
  87. "messages": []map[string]any{{
  88. "role": "user", "content": req.Query,
  89. }},
  90. })
  91. if decision := h.checkSecurityAudit(c, reqLog, apiKey, subject, service.ContentModerationProtocolOpenAIChat, searchModel, auditBody); decision != nil && !decision.AllowNextStage {
  92. status := decision.HTTPStatus
  93. if status == 0 {
  94. status = http.StatusForbidden
  95. }
  96. code := decision.ErrorCode
  97. if code == "" {
  98. code = "content_policy_violation"
  99. }
  100. msg := decision.ClientMessage
  101. if msg == "" {
  102. msg = "Request blocked by content policy"
  103. }
  104. c.JSON(status, gin.H{"error": gin.H{"type": code, "message": msg}})
  105. return
  106. }
  107. // Use exactly the same scheduling as other requests (SelectAccountWithLoadAwareness handles load, rate limit, sticky, etc.)
  108. groupID := apiKey.GroupID
  109. if groupID == nil {
  110. c.JSON(http.StatusBadRequest, gin.H{"error": gin.H{
  111. "type": "invalid_request_error",
  112. "message": "group required",
  113. }})
  114. return
  115. }
  116. failedAccounts := make(map[int64]struct{})
  117. var account *service.Account
  118. var accountReleaseFunc func()
  119. var nativeResp *websearch.SearchResponse
  120. var providerName string
  121. var err error
  122. // Acquire + release holder for the whole handler (including failover retries).
  123. defer func() {
  124. if accountReleaseFunc != nil {
  125. accountReleaseFunc()
  126. }
  127. }()
  128. // First attempt + up to 3 failover accounts (max 4 total).
  129. for attempt := 0; attempt < 4; attempt++ {
  130. selected, selectErr := h.gatewayService.SelectAccountWithLoadAwareness(
  131. c.Request.Context(), groupID, "", searchModel, failedAccounts, "", 0,
  132. )
  133. if selectErr != nil {
  134. if attempt == 0 {
  135. c.JSON(http.StatusServiceUnavailable, gin.H{"error": gin.H{
  136. "type": "scheduling_error",
  137. "message": selectErr.Error(),
  138. }})
  139. return
  140. }
  141. break
  142. }
  143. if selected == nil || selected.Account == nil {
  144. if attempt == 0 {
  145. c.JSON(http.StatusServiceUnavailable, gin.H{"error": gin.H{
  146. "type": "scheduling_error",
  147. "message": "No available accounts",
  148. }})
  149. return
  150. }
  151. break
  152. }
  153. release, acquireOK, acquireErr := h.acquireWebSearchAccountSlot(c, selected)
  154. if !acquireOK {
  155. // First hop: surface concurrency errors; later hops try another account.
  156. if attempt == 0 && acquireErr != nil {
  157. h.handleConcurrencyError(c, acquireErr, "account", false)
  158. return
  159. }
  160. failedAccounts[selected.Account.ID] = struct{}{}
  161. continue
  162. }
  163. account = selected.Account
  164. accountReleaseFunc = release
  165. if isXSearch {
  166. nativeResp, providerName, err = h.doGrokNativeXSearch(c.Request.Context(), c, account, req, searchModel, maxResults)
  167. } else {
  168. nativeResp, providerName, err = h.doGrokNativeWebSearch(c.Request.Context(), c, account, req.Query, maxResults, searchModel)
  169. }
  170. if err == nil {
  171. break
  172. }
  173. var failoverErr *service.UpstreamFailoverError
  174. if !errors.As(err, &failoverErr) || !failoverErr.ShouldRetryNextAccount() {
  175. break
  176. }
  177. failedAccounts[account.ID] = struct{}{}
  178. if accountReleaseFunc != nil {
  179. accountReleaseFunc()
  180. accountReleaseFunc = nil
  181. }
  182. account = nil
  183. }
  184. if err != nil || nativeResp == nil {
  185. msg := "web search failed"
  186. if err != nil {
  187. msg = err.Error()
  188. }
  189. c.JSON(http.StatusBadGateway, gin.H{"error": gin.H{"type": "web_search_error", "message": msg}})
  190. return
  191. }
  192. if account == nil {
  193. c.JSON(http.StatusServiceUnavailable, gin.H{"error": gin.H{
  194. "type": "scheduling_error",
  195. "message": "No available accounts",
  196. }})
  197. return
  198. }
  199. userAgent := c.GetHeader("User-Agent")
  200. clientIP := ip.GetClientIP(c)
  201. inboundEndpoint := GetInboundEndpoint(c)
  202. upstreamEndpoint := GetUpstreamEndpoint(c, account.Platform)
  203. requestPayloadHash := service.HashUsageRequestPayload([]byte(req.Query))
  204. quotaPlatform := service.QuotaPlatform(c.Request.Context(), apiKey)
  205. // Request IDs are billing idempotency keys, so they must be unique per invocation.
  206. // Query/IP/UA hashes would collapse repeated identical searches into one charge.
  207. searchRequestID := searchLabel + ":" + uuid.NewString()
  208. if apiKey.Group != nil {
  209. if p := apiKey.Group.GetSearchPricePer1k(); p != nil && *p == 0 {
  210. logger.L().With(
  211. zap.String("component", "handler.gateway.web_search"),
  212. zap.Int64("group_id", apiKey.Group.ID),
  213. ).Info("gateway.web_search.search_price_per_1k_explicit_free")
  214. }
  215. }
  216. h.submitMandatoryUsageRecordTask(c.Request.Context(), func(ctx context.Context) {
  217. if err := h.gatewayService.RecordUsage(ctx, &service.RecordUsageInput{
  218. Result: &service.ForwardResult{
  219. RequestID: searchRequestID,
  220. Model: "grok-" + strings.ReplaceAll(searchLabel, "_", "-"),
  221. SearchCount: 1,
  222. Duration: 0,
  223. },
  224. APIKey: apiKey,
  225. User: apiKey.User,
  226. Account: account,
  227. Subscription: subscription,
  228. InboundEndpoint: inboundEndpoint,
  229. UpstreamEndpoint: upstreamEndpoint,
  230. UserAgent: userAgent,
  231. IPAddress: clientIP,
  232. RequestPayloadHash: requestPayloadHash,
  233. APIKeyService: h.apiKeyService,
  234. QuotaPlatform: quotaPlatform,
  235. }); err != nil {
  236. logger.L().With(
  237. zap.String("component", "handler.gateway.web_search"),
  238. zap.Int64("user_id", apiKey.User.ID),
  239. zap.Int64("api_key_id", apiKey.ID),
  240. zap.Int64("account_id", account.ID),
  241. ).Error("gateway.web_search.record_usage_failed", zap.Error(err))
  242. }
  243. })
  244. c.JSON(http.StatusOK, gin.H{
  245. "query": req.Query,
  246. "results": nativeResp.Results,
  247. "provider": providerName,
  248. "max_results": maxResults,
  249. })
  250. }
  251. // acquireWebSearchAccountSlot resolves an immediate slot or WaitPlan wait.
  252. // On failure returns (nil, false, err); err is non-nil for concurrency acquire
  253. // failures so the first hop can map them to HTTP. Wait-queue full returns
  254. // (nil, false, nil) so failover can try another account.
  255. func (h *GatewayHandler) acquireWebSearchAccountSlot(
  256. c *gin.Context,
  257. selected *service.AccountSelectionResult,
  258. ) (release func(), ok bool, acquireErr error) {
  259. if selected == nil || selected.Account == nil {
  260. return nil, false, nil
  261. }
  262. if selected.Acquired {
  263. return selected.ReleaseFunc, true, nil
  264. }
  265. if selected.WaitPlan == nil || h.concurrencyHelper == nil {
  266. return nil, false, nil
  267. }
  268. account := selected.Account
  269. accountWaitCounted := false
  270. canWait, waitErr := h.concurrencyHelper.IncrementAccountWaitCount(c.Request.Context(), account.ID, selected.WaitPlan.MaxWaiting)
  271. if waitErr != nil {
  272. logger.L().Warn("gateway.web_search.account_wait_counter_increment_failed",
  273. zap.Int64("account_id", account.ID),
  274. zap.Error(waitErr),
  275. )
  276. // Best-effort wait without counter (same as first-hop legacy path).
  277. } else if !canWait {
  278. return nil, false, nil
  279. } else {
  280. accountWaitCounted = true
  281. }
  282. releaseWait := func() {
  283. if accountWaitCounted {
  284. h.concurrencyHelper.DecrementAccountWaitCount(c.Request.Context(), account.ID)
  285. accountWaitCounted = false
  286. }
  287. }
  288. streamStarted := false
  289. slotRelease, err := h.concurrencyHelper.AcquireAccountSlotWithWaitTimeout(
  290. c,
  291. account.ID,
  292. selected.WaitPlan.MaxConcurrency,
  293. selected.WaitPlan.Timeout,
  294. false,
  295. &streamStarted,
  296. )
  297. releaseWait()
  298. if err != nil {
  299. return nil, false, err
  300. }
  301. return slotRelease, true, nil
  302. }
  303. // doGrokNativeWebSearch executes web search using the Grok account's native capability
  304. // by calling the responses endpoint with web_search tool, then normalizes sources to unified format.
  305. func (h *GatewayHandler) doGrokNativeWebSearch(ctx context.Context, c *gin.Context, account *service.Account, query string, maxResults int, model string) (*websearch.SearchResponse, string, error) {
  306. maxResults = normalizeGrokWebSearchMaxResults(maxResults)
  307. // Build a minimal responses request that triggers Grok web search tool.
  308. // Ask for structured metadata because xAI action.sources commonly contains URLs only.
  309. searchBody := map[string]any{
  310. "model": xai.ResolveDefaultTextModel(model),
  311. "input": buildGrokWebSearchPrompt(query, maxResults),
  312. "tools": []map[string]any{{"type": "web_search"}},
  313. "include": []string{"web_search_call.action.sources"},
  314. "store": false,
  315. "stream": false,
  316. }
  317. bodyBytes, _ := json.Marshal(searchBody)
  318. respBytes, err := h.gatewayService.DoGrokNativeResponsesJSON(ctx, account, bodyBytes)
  319. if err != nil {
  320. return nil, "", err
  321. }
  322. // Extract sources from Grok responses output.
  323. // Prefer web_search_call.action.sources (standardized), fallback to annotations or text links.
  324. results := extractGrokWebSearchSources(respBytes, maxResults)
  325. return &websearch.SearchResponse{
  326. Results: results,
  327. Query: query,
  328. }, "grok-native", nil
  329. }
  330. func (h *GatewayHandler) doGrokNativeXSearch(ctx context.Context, c *gin.Context, account *service.Account, req grokStandaloneSearchRequest, model string, maxResults int) (*websearch.SearchResponse, string, error) {
  331. maxResults = normalizeGrokWebSearchMaxResults(maxResults)
  332. bodyBytes, err := buildGrokXSearchResponsesBody(req, model)
  333. if err != nil {
  334. return nil, "", err
  335. }
  336. respBytes, err := h.gatewayService.DoGrokNativeResponsesJSON(ctx, account, bodyBytes)
  337. if err != nil {
  338. return nil, "", err
  339. }
  340. results := extractGrokWebSearchSources(respBytes, maxResults)
  341. return &websearch.SearchResponse{
  342. Results: results,
  343. Query: req.Query,
  344. }, "grok-native", nil
  345. }
  346. func normalizeGrokWebSearchMaxResults(maxResults int) int {
  347. if maxResults <= 0 {
  348. return defaultGrokWebSearchResults
  349. }
  350. if maxResults > maxGrokWebSearchResults {
  351. return maxGrokWebSearchResults
  352. }
  353. return maxResults
  354. }
  355. func buildGrokWebSearchPrompt(query string, maxResults int) string {
  356. return fmt.Sprintf(`Search the web for the user query below. Return ONLY valid JSON with this exact shape: {"results":[{"url":"https://...","title":"page title","snippet":"concise factual summary"}]}. Return at most %d unique results. Every URL must be an actual web_search source. Populate a non-empty title and snippet for every result. Do not wrap the JSON in markdown.
  357. User query:
  358. %s`, normalizeGrokWebSearchMaxResults(maxResults), query)
  359. }
  360. // extractGrokWebSearchSources returns model-enriched results only when their URLs
  361. // are present in the actual web_search sources, then falls back to raw sources.
  362. func extractGrokWebSearchSources(body []byte, maxResults int) []websearch.SearchResult {
  363. if len(body) == 0 || !gjson.ValidBytes(body) {
  364. return nil
  365. }
  366. maxResults = normalizeGrokWebSearchMaxResults(maxResults)
  367. sources := make(map[string]websearch.SearchResult)
  368. var sourceOrder []string
  369. addSource := func(rawURL, title, snippet string) {
  370. key, ok := normalizeGrokWebSearchURL(rawURL)
  371. if !ok {
  372. return
  373. }
  374. result, exists := sources[key]
  375. if !exists {
  376. result.URL = strings.TrimSpace(rawURL)
  377. sourceOrder = append(sourceOrder, key)
  378. }
  379. if result.Title == "" {
  380. result.Title = usableGrokWebSearchTitle(title, result.URL)
  381. }
  382. if result.Snippet == "" {
  383. result.Snippet = strings.TrimSpace(snippet)
  384. }
  385. sources[key] = result
  386. }
  387. output := gjson.GetBytes(body, "output")
  388. output.ForEach(func(_, item gjson.Result) bool {
  389. callType := item.Get("type").String()
  390. if callType == "web_search_call" || callType == "x_search_call" {
  391. sources := item.Get("action.sources")
  392. if sources.IsArray() {
  393. sources.ForEach(func(_, src gjson.Result) bool {
  394. addSource(src.Get("url").String(), src.Get("title").String(), src.Get("snippet").String())
  395. return true
  396. })
  397. }
  398. }
  399. if item.Get("type").String() == "message" {
  400. item.Get("content").ForEach(func(_, part gjson.Result) bool {
  401. if part.Get("type").String() != "output_text" {
  402. return true
  403. }
  404. part.Get("annotations").ForEach(func(_, ann gjson.Result) bool {
  405. if ann.Get("type").String() == "url_citation" || ann.Get("type").String() == "web" {
  406. addSource(ann.Get("url").String(), ann.Get("title").String(), "")
  407. }
  408. return true
  409. })
  410. return true
  411. })
  412. }
  413. return true
  414. })
  415. var out []websearch.SearchResult
  416. seen := make(map[string]bool)
  417. output.ForEach(func(_, item gjson.Result) bool {
  418. if item.Get("type").String() != "message" {
  419. return true
  420. }
  421. item.Get("content").ForEach(func(_, part gjson.Result) bool {
  422. if part.Get("type").String() != "output_text" || len(out) >= maxResults {
  423. return true
  424. }
  425. for _, result := range parseGrokWebSearchStructuredResults(part.Get("text").String()) {
  426. key, ok := normalizeGrokWebSearchURL(result.URL)
  427. if !ok || seen[key] {
  428. continue
  429. }
  430. source, allowed := sources[key]
  431. if !allowed {
  432. continue
  433. }
  434. seen[key] = true
  435. result.URL = source.URL
  436. result.Title = usableGrokWebSearchTitle(result.Title, result.URL)
  437. if result.Title == "" {
  438. result.Title = source.Title
  439. }
  440. result.Snippet = strings.TrimSpace(result.Snippet)
  441. if result.Snippet == "" {
  442. result.Snippet = source.Snippet
  443. }
  444. out = append(out, result)
  445. if len(out) >= maxResults {
  446. break
  447. }
  448. }
  449. return true
  450. })
  451. return len(out) < maxResults
  452. })
  453. for _, key := range sourceOrder {
  454. if len(out) >= maxResults {
  455. break
  456. }
  457. if seen[key] {
  458. continue
  459. }
  460. result := sources[key]
  461. if result.Title == "" {
  462. result.Title = grokWebSearchTitleFromURL(result.URL)
  463. }
  464. seen[key] = true
  465. out = append(out, result)
  466. }
  467. return out
  468. }
  469. func parseGrokWebSearchStructuredResults(text string) []websearch.SearchResult {
  470. text = strings.TrimSpace(text)
  471. start := strings.IndexByte(text, '{')
  472. end := strings.LastIndexByte(text, '}')
  473. if start < 0 || end < start {
  474. return nil
  475. }
  476. var payload struct {
  477. Results []websearch.SearchResult `json:"results"`
  478. }
  479. if err := json.Unmarshal([]byte(text[start:end+1]), &payload); err != nil {
  480. return nil
  481. }
  482. return payload.Results
  483. }
  484. func normalizeGrokWebSearchURL(rawURL string) (string, bool) {
  485. u, err := url.Parse(strings.TrimSpace(rawURL))
  486. if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") {
  487. return "", false
  488. }
  489. u.Scheme = strings.ToLower(u.Scheme)
  490. u.Host = strings.ToLower(u.Host)
  491. u.Fragment = ""
  492. if u.Path == "" {
  493. u.Path = "/"
  494. }
  495. return u.String(), true
  496. }
  497. func usableGrokWebSearchTitle(title, rawURL string) string {
  498. title = strings.TrimSpace(title)
  499. if title == "" || title == rawURL {
  500. return ""
  501. }
  502. if _, err := strconv.Atoi(title); err == nil {
  503. return ""
  504. }
  505. return title
  506. }
  507. func grokWebSearchTitleFromURL(rawURL string) string {
  508. u, err := url.Parse(rawURL)
  509. if err != nil || u.Host == "" {
  510. return rawURL
  511. }
  512. return strings.TrimPrefix(strings.ToLower(u.Host), "www.")
  513. }