feat(web-search): add Bocha AI Search provider (#3036)
* feat(web-search): add Bocha AI Search provider
Add a Bocha (bochaai.com) web search provider following the Metaso
adapter pattern: hardcoded official endpoint (SSRF-safe), Bearer auth,
4MB response cap, error-detail extraction, and RFC3339 date parsing
(datePublished preferred, dateLastCrawled fallback).
Tenant-facing config fields:
- freshness: noLimit/oneDay/oneWeek/oneMonth/oneYear (default noLimit)
- summary: request long text summaries, preferred as snippets (default on)
Wiring: registry factory in container, provider type enum + /types
metadata (dynamic form fields), frontend provider union type, and
swagger docs enum entries.
* fix(web-search): match Bocha's real wire format for codes and error messages
Live endpoint probing showed errors return {"message": .., "code": "401"}
(string code, message field) instead of the documented {msg, code:int}.
Parse the code tolerantly (string or number) and extract the detail from
message/msg so auth and rate-limit failures surface their reason.
* fix(web-search): allow Bocha in provider CRUD validation
In-service integration testing caught a fourth wiring point the adapter,
registry, /types metadata and frontend covered but CRUD did not: the
service-layer whitelist (isValidProviderType) and parameter validation
switches rejected provider type 'bocha', so providers could be tested
via POST /web-search-providers/test but never created or updated.
Add Bocha to both switches (delegating to ValidateBochaParameters like
Metaso/Zhipu) with service-level test coverage.
* fix(web-search): correct Bocha legacy timestamp timezone
---------
Co-authored-by: vicfei <vicfei@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
main
parent
bd7aa40119
commit
15727591a7
|
|
@ -22622,7 +22622,8 @@ const docTemplate = `{
|
|||
"keenable",
|
||||
"zhipu",
|
||||
"exa",
|
||||
"metaso"
|
||||
"metaso",
|
||||
"bocha"
|
||||
],
|
||||
"x-enum-varnames": [
|
||||
"WebSearchProviderTypeBing",
|
||||
|
|
@ -22635,7 +22636,8 @@ const docTemplate = `{
|
|||
"WebSearchProviderTypeKeenable",
|
||||
"WebSearchProviderTypeZhipu",
|
||||
"WebSearchProviderTypeExa",
|
||||
"WebSearchProviderTypeMetaso"
|
||||
"WebSearchProviderTypeMetaso",
|
||||
"WebSearchProviderTypeBocha"
|
||||
]
|
||||
},
|
||||
"github_com_Tencent_WeKnora_internal_types.WikiConfig": {
|
||||
|
|
|
|||
|
|
@ -22615,7 +22615,8 @@
|
|||
"keenable",
|
||||
"zhipu",
|
||||
"exa",
|
||||
"metaso"
|
||||
"metaso",
|
||||
"bocha"
|
||||
],
|
||||
"x-enum-varnames": [
|
||||
"WebSearchProviderTypeBing",
|
||||
|
|
@ -22628,7 +22629,8 @@
|
|||
"WebSearchProviderTypeKeenable",
|
||||
"WebSearchProviderTypeZhipu",
|
||||
"WebSearchProviderTypeExa",
|
||||
"WebSearchProviderTypeMetaso"
|
||||
"WebSearchProviderTypeMetaso",
|
||||
"WebSearchProviderTypeBocha"
|
||||
]
|
||||
},
|
||||
"github_com_Tencent_WeKnora_internal_types.WikiConfig": {
|
||||
|
|
|
|||
|
|
@ -4397,6 +4397,7 @@ definitions:
|
|||
- zhipu
|
||||
- exa
|
||||
- metaso
|
||||
- bocha
|
||||
type: string
|
||||
x-enum-varnames:
|
||||
- WebSearchProviderTypeBing
|
||||
|
|
@ -4410,6 +4411,7 @@ definitions:
|
|||
- WebSearchProviderTypeZhipu
|
||||
- WebSearchProviderTypeExa
|
||||
- WebSearchProviderTypeMetaso
|
||||
- WebSearchProviderTypeBocha
|
||||
github_com_Tencent_WeKnora_internal_types.WikiConfig:
|
||||
properties:
|
||||
content_instructions:
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ export interface WebSearchProviderEntity {
|
|||
id?: string
|
||||
tenant_id?: number
|
||||
name: string
|
||||
provider: 'bing' | 'google' | 'duckduckgo' | 'tavily' | 'ollama' | 'baidu' | 'searxng' | 'keenable' | 'zhipu' | 'metaso' | 'exa'
|
||||
provider: 'bing' | 'google' | 'duckduckgo' | 'tavily' | 'ollama' | 'baidu' | 'searxng' | 'keenable' | 'zhipu' | 'metaso' | 'exa' | 'bocha'
|
||||
description?: string
|
||||
parameters: {
|
||||
// api_key is never returned by the server in this shape; it lives behind
|
||||
|
|
|
|||
|
|
@ -139,7 +139,8 @@ func isValidProviderType(provider types.WebSearchProviderType) bool {
|
|||
types.WebSearchProviderTypeKeenable,
|
||||
types.WebSearchProviderTypeMetaso,
|
||||
types.WebSearchProviderTypeZhipu,
|
||||
types.WebSearchProviderTypeExa:
|
||||
types.WebSearchProviderTypeExa,
|
||||
types.WebSearchProviderTypeBocha:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
|
|
@ -184,6 +185,10 @@ func validateProviderParameters(provider types.WebSearchProviderType, params typ
|
|||
if err := infra_web_search.ValidateMetasoParameters(params); err != nil {
|
||||
return err
|
||||
}
|
||||
case types.WebSearchProviderTypeBocha:
|
||||
if err := infra_web_search.ValidateBochaParameters(params); err != nil {
|
||||
return err
|
||||
}
|
||||
case types.WebSearchProviderTypeDuckDuckGo:
|
||||
// No API key required
|
||||
case types.WebSearchProviderTypeKeenable:
|
||||
|
|
|
|||
|
|
@ -62,3 +62,24 @@ func TestValidateProviderParametersMetaso(t *testing.T) {
|
|||
t.Fatal("Metaso provider type is not accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateProviderParametersBocha(t *testing.T) {
|
||||
valid := types.WebSearchProviderParameters{
|
||||
APIKey: "sk-test",
|
||||
ExtraConfig: map[string]string{"freshness": "oneWeek", "summary": "true"},
|
||||
}
|
||||
if err := validateProviderParameters(types.WebSearchProviderTypeBocha, valid); err != nil {
|
||||
t.Fatalf("valid Bocha parameters rejected: %v", err)
|
||||
}
|
||||
invalid := valid
|
||||
invalid.ExtraConfig = map[string]string{"freshness": "oneHour"}
|
||||
if err := validateProviderParameters(types.WebSearchProviderTypeBocha, invalid); err == nil {
|
||||
t.Fatal("invalid Bocha freshness was accepted")
|
||||
}
|
||||
if err := validateProviderParameters(types.WebSearchProviderTypeBocha, types.WebSearchProviderParameters{}); err == nil {
|
||||
t.Fatal("missing Bocha API key was accepted")
|
||||
}
|
||||
if !isValidProviderType(types.WebSearchProviderTypeBocha) {
|
||||
t.Fatal("Bocha provider type is not accepted")
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1627,6 +1627,7 @@ func registerWebSearchProviders(registry *infra_web_search.Registry) {
|
|||
registry.Register("zhipu", infra_web_search.NewZhipuProvider)
|
||||
registry.Register("exa", infra_web_search.NewExaProvider)
|
||||
registry.Register("metaso", infra_web_search.NewMetasoProvider)
|
||||
registry.Register("bocha", infra_web_search.NewBochaProvider)
|
||||
}
|
||||
|
||||
// registerIMService registers adapter factories, loads enabled channels, and
|
||||
|
|
|
|||
|
|
@ -0,0 +1,253 @@
|
|||
package web_search
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/Tencent/WeKnora/internal/types/interfaces"
|
||||
)
|
||||
|
||||
const (
|
||||
// defaultBochaSearchURL is the hardcoded Bocha API URL.
|
||||
// Not configurable by tenants — prevents SSRF.
|
||||
defaultBochaSearchURL = "https://api.bochaai.com/v1/web-search"
|
||||
defaultBochaTimeout = 30 * time.Second
|
||||
defaultBochaResults = 10
|
||||
maxBochaResults = 50
|
||||
maxBochaResponseBytes = 4 << 20
|
||||
defaultBochaFreshness = "noLimit"
|
||||
)
|
||||
|
||||
var validBochaFreshness = map[string]struct{}{
|
||||
"noLimit": {}, "oneDay": {}, "oneWeek": {}, "oneMonth": {}, "oneYear": {},
|
||||
}
|
||||
|
||||
// BochaProvider implements web search using the Bocha AI Search API.
|
||||
type BochaProvider struct {
|
||||
client *http.Client
|
||||
baseURL string
|
||||
apiKey string
|
||||
freshness string
|
||||
summary bool
|
||||
}
|
||||
|
||||
func NewBochaProvider(params types.WebSearchProviderParameters) (interfaces.WebSearchProvider, error) {
|
||||
if err := ValidateBochaParameters(params); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client, err := NewSearchHTTPClient(defaultBochaTimeout, params.ProxyURL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &BochaProvider{
|
||||
client: client, baseURL: defaultBochaSearchURL,
|
||||
apiKey: strings.TrimSpace(params.APIKey),
|
||||
freshness: bochaFreshness(params.ExtraConfig), summary: bochaSummary(params.ExtraConfig),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func ValidateBochaParameters(params types.WebSearchProviderParameters) error {
|
||||
if strings.TrimSpace(params.APIKey) == "" {
|
||||
return fmt.Errorf("API key is required for Bocha provider")
|
||||
}
|
||||
if freshness := bochaFreshness(params.ExtraConfig); freshness == "" {
|
||||
return fmt.Errorf("invalid Bocha freshness: %s", params.ExtraConfig["freshness"])
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func bochaFreshness(extraConfig map[string]string) string {
|
||||
if freshness := strings.TrimSpace(extraConfig["freshness"]); freshness != "" {
|
||||
if _, ok := validBochaFreshness[freshness]; ok {
|
||||
return freshness
|
||||
}
|
||||
return ""
|
||||
}
|
||||
return defaultBochaFreshness
|
||||
}
|
||||
|
||||
func bochaSummary(extraConfig map[string]string) bool {
|
||||
return strings.TrimSpace(extraConfig["summary"]) != "false"
|
||||
}
|
||||
|
||||
func (p *BochaProvider) Name() string { return "bocha" }
|
||||
|
||||
func (p *BochaProvider) Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error) {
|
||||
query = strings.TrimSpace(query)
|
||||
if query == "" {
|
||||
return nil, fmt.Errorf("query is empty")
|
||||
}
|
||||
if maxResults <= 0 {
|
||||
maxResults = defaultBochaResults
|
||||
}
|
||||
if maxResults > maxBochaResults {
|
||||
maxResults = maxBochaResults
|
||||
}
|
||||
|
||||
body, err := json.Marshal(bochaSearchRequest{
|
||||
Query: query, Freshness: p.freshness, Summary: p.summary, Count: maxResults,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to marshal Bocha request: %w", err)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.baseURL, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create Bocha request: %w", err)
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+p.apiKey)
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
logger.Infof(ctx, "[WebSearch][Bocha] query=%q maxResults=%d freshness=%s", query, maxResults, p.freshness)
|
||||
resp, err := p.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to execute Bocha request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
respBody, err := readBochaResponseBody(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, bochaHTTPError(resp.StatusCode, respBody)
|
||||
}
|
||||
|
||||
var response bochaSearchResponse
|
||||
if err := json.Unmarshal(respBody, &response); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal Bocha response: %w", err)
|
||||
}
|
||||
if response.Code != 0 && response.Code != bochaCode(http.StatusOK) {
|
||||
return nil, fmt.Errorf("Bocha API returned code %d", response.Code)
|
||||
}
|
||||
results := make([]*types.WebSearchResult, 0, len(response.Data.WebPages.Value))
|
||||
for _, item := range response.Data.WebPages.Value {
|
||||
if strings.TrimSpace(item.Name) == "" && strings.TrimSpace(item.URL) == "" {
|
||||
continue
|
||||
}
|
||||
snippet := strings.TrimSpace(item.Summary)
|
||||
if snippet == "" {
|
||||
snippet = strings.TrimSpace(item.Snippet)
|
||||
}
|
||||
result := &types.WebSearchResult{Title: item.Name, URL: item.URL, Snippet: snippet, Source: "bocha"}
|
||||
if includeDate {
|
||||
if publishedAt, ok := parseBochaDate(item.DatePublished); ok {
|
||||
result.PublishedAt = &publishedAt
|
||||
} else if publishedAt, ok := parseBochaLastCrawled(item.DateLastCrawled); ok {
|
||||
result.PublishedAt = &publishedAt
|
||||
}
|
||||
}
|
||||
results = append(results, result)
|
||||
if len(results) >= maxResults {
|
||||
break
|
||||
}
|
||||
}
|
||||
logger.Infof(ctx, "[WebSearch][Bocha] returned %d results", len(results))
|
||||
return results, nil
|
||||
}
|
||||
|
||||
func readBochaResponseBody(reader io.Reader) ([]byte, error) {
|
||||
body, err := io.ReadAll(io.LimitReader(reader, maxBochaResponseBytes+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read Bocha response: %w", err)
|
||||
}
|
||||
if len(body) > maxBochaResponseBytes {
|
||||
return nil, fmt.Errorf("Bocha response exceeds %d bytes", maxBochaResponseBytes)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
func bochaHTTPError(statusCode int, body []byte) error {
|
||||
var apiError struct {
|
||||
Message string `json:"message"`
|
||||
Msg string `json:"msg"`
|
||||
}
|
||||
if json.Unmarshal(body, &apiError) == nil {
|
||||
detail := strings.TrimSpace(apiError.Message)
|
||||
if detail == "" {
|
||||
detail = strings.TrimSpace(apiError.Msg)
|
||||
}
|
||||
if detail != "" {
|
||||
return fmt.Errorf("Bocha API returned status %d: %s", statusCode, detail)
|
||||
}
|
||||
}
|
||||
detail := strings.TrimSpace(string(body))
|
||||
if len(detail) > 4096 {
|
||||
detail = detail[:4096]
|
||||
}
|
||||
if detail == "" {
|
||||
return fmt.Errorf("Bocha API returned status %d", statusCode)
|
||||
}
|
||||
return fmt.Errorf("Bocha API returned status %d: %s", statusCode, detail)
|
||||
}
|
||||
|
||||
func parseBochaLastCrawled(value string) (time.Time, bool) {
|
||||
// Bocha v1's legacy dateLastCrawled field labels UTC+8 wall time with Z.
|
||||
// Correct only this field; datePublished and explicit offsets are accurate.
|
||||
value = strings.TrimSpace(value)
|
||||
if strings.HasSuffix(value, "Z") {
|
||||
value = strings.TrimSuffix(value, "Z") + "+08:00"
|
||||
}
|
||||
return parseBochaDate(value)
|
||||
}
|
||||
|
||||
func parseBochaDate(value string) (time.Time, bool) {
|
||||
for _, layout := range []string{time.RFC3339Nano, "2006-01-02 15:04:05", "2006-01-02"} {
|
||||
if parsed, err := time.Parse(layout, strings.TrimSpace(value)); err == nil {
|
||||
return parsed, true
|
||||
}
|
||||
}
|
||||
return time.Time{}, false
|
||||
}
|
||||
|
||||
// bochaCode tolerates the API's mixed code encoding: errors return a
|
||||
// JSON string ("401") while success responses may return a number (200).
|
||||
type bochaCode int
|
||||
|
||||
func (c *bochaCode) UnmarshalJSON(data []byte) error {
|
||||
s := strings.Trim(strings.TrimSpace(string(data)), `"`)
|
||||
if s == "" || s == "null" {
|
||||
*c = 0
|
||||
return nil
|
||||
}
|
||||
n, err := strconv.Atoi(s)
|
||||
if err != nil {
|
||||
*c = 0
|
||||
return nil
|
||||
}
|
||||
*c = bochaCode(n)
|
||||
return nil
|
||||
}
|
||||
|
||||
type bochaSearchRequest struct {
|
||||
Query string `json:"query"`
|
||||
Freshness string `json:"freshness"`
|
||||
Summary bool `json:"summary"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
type bochaSearchResponse struct {
|
||||
Code bochaCode `json:"code"`
|
||||
Data struct {
|
||||
WebPages struct {
|
||||
Value []bochaWebPage `json:"value"`
|
||||
} `json:"webPages"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type bochaWebPage struct {
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
Snippet string `json:"snippet"`
|
||||
Summary string `json:"summary"`
|
||||
DatePublished string `json:"datePublished"`
|
||||
DateLastCrawled string `json:"dateLastCrawled"`
|
||||
}
|
||||
|
|
@ -0,0 +1,168 @@
|
|||
package web_search
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
func TestBochaProviderSearch(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
t.Fatalf("method = %s, want POST", r.Method)
|
||||
}
|
||||
if got := r.Header.Get("Authorization"); got != "Bearer sk-test" {
|
||||
t.Fatalf("Authorization = %q", got)
|
||||
}
|
||||
var request bochaSearchRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if request.Query != "WeKnora" || request.Freshness != "oneWeek" || !request.Summary || request.Count != 2 {
|
||||
t.Fatalf("unexpected request: %+v", request)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"code":200,"log_id":"x","msg":null,"data":{"webPages":{"value":[
|
||||
{"name":"First","url":"https://example.com/1","summary":"Summary","snippet":"Snippet","dateLastCrawled":"2026-08-09T08:18:30Z"},
|
||||
{"name":"Second","url":"https://example.com/2","snippet":"Fallback snippet","dateLastCrawled":"invalid"},
|
||||
{"name":"Third","url":"https://example.com/3","snippet":"must be capped"}
|
||||
]}}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
bocha := &BochaProvider{client: server.Client(), baseURL: server.URL, apiKey: "sk-test", freshness: "oneWeek", summary: true}
|
||||
results, err := bocha.Search(context.Background(), " WeKnora ", 2, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(results) != 2 {
|
||||
t.Fatalf("len(results) = %d, want 2", len(results))
|
||||
}
|
||||
if results[0].Snippet != "Summary" || results[1].Snippet != "Fallback snippet" {
|
||||
t.Fatalf("unexpected snippets: %q, %q", results[0].Snippet, results[1].Snippet)
|
||||
}
|
||||
if results[0].Source != "bocha" || results[0].PublishedAt == nil {
|
||||
t.Fatalf("unexpected first result: %+v", results[0])
|
||||
}
|
||||
if want := time.Date(2026, 8, 9, 0, 18, 30, 0, time.UTC); !results[0].PublishedAt.Equal(want) {
|
||||
t.Fatalf("date = %v, want %v", results[0].PublishedAt, want)
|
||||
}
|
||||
if results[1].PublishedAt != nil {
|
||||
t.Fatalf("invalid date should be ignored: %v", results[1].PublishedAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBochaProviderSearchDates(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
published string
|
||||
lastCrawled string
|
||||
includeDate bool
|
||||
want string
|
||||
}{
|
||||
{"legacy fallback", "", "2026-08-09T02:18:30Z", true, "2026-08-08T18:18:30Z"},
|
||||
{"invalid published fallback", "invalid", " 2026-08-09T02:18:30.123Z ", true, "2026-08-08T18:18:30.123Z"},
|
||||
{"published UTC preferred", "2026-08-09T02:18:30Z", "2026-08-09T02:18:30Z", true, "2026-08-09T02:18:30Z"},
|
||||
{"published explicit offset", "2026-08-09T02:18:30+08:00", "invalid", true, "2026-08-08T18:18:30Z"},
|
||||
{"fallback explicit offset", "", "2026-08-09T02:18:30+08:00", true, "2026-08-08T18:18:30Z"},
|
||||
{"invalid dates", "invalid", "invalid", true, ""},
|
||||
{"date excluded", "2026-08-09T02:18:30+08:00", "2026-08-09T02:18:30Z", false, ""},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
var response bochaSearchResponse
|
||||
response.Code = 200
|
||||
response.Data.WebPages.Value = []bochaWebPage{{
|
||||
Name: "Result", URL: "https://example.com",
|
||||
DatePublished: tt.published, DateLastCrawled: tt.lastCrawled,
|
||||
}}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(response); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
bocha := &BochaProvider{
|
||||
client: server.Client(), baseURL: server.URL, apiKey: "sk-test", freshness: defaultBochaFreshness,
|
||||
}
|
||||
results, err := bocha.Search(context.Background(), "test", 1, tt.includeDate)
|
||||
if err != nil || len(results) != 1 {
|
||||
t.Fatalf("results = %v, err = %v", results, err)
|
||||
}
|
||||
got := results[0].PublishedAt
|
||||
if tt.want == "" {
|
||||
if got != nil {
|
||||
t.Fatalf("date = %v, want nil", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if got == nil || got.UTC().Format(time.RFC3339Nano) != tt.want {
|
||||
t.Fatalf("date = %v, want %s", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateBochaParameters(t *testing.T) {
|
||||
if err := ValidateBochaParameters(types.WebSearchProviderParameters{}); err == nil {
|
||||
t.Fatal("expected missing API key error")
|
||||
}
|
||||
if err := ValidateBochaParameters(types.WebSearchProviderParameters{APIKey: "sk-test", ExtraConfig: map[string]string{"freshness": "oneHour"}}); err == nil {
|
||||
t.Fatal("expected invalid freshness error")
|
||||
}
|
||||
if err := ValidateBochaParameters(types.WebSearchProviderParameters{APIKey: "sk-test"}); err != nil {
|
||||
t.Fatalf("default parameters: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBochaProviderHTTPError(t *testing.T) {
|
||||
// Error body captured from the live API (2026-09-05): the message field is
|
||||
// "message" and the code is a JSON string.
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write([]byte(`{"log_id":"4a995aed60e4088e","message":"Invalid API KEY","code":"401"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
bocha := &BochaProvider{client: server.Client(), baseURL: server.URL, apiKey: "bad", freshness: defaultBochaFreshness, summary: true}
|
||||
_, err := bocha.Search(context.Background(), "test", 1, false)
|
||||
if err == nil || !strings.Contains(err.Error(), "Invalid API KEY") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBochaProviderAPIErrorWithHTTPOK(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"code":"429","message":"rate limited"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
bocha := &BochaProvider{client: server.Client(), baseURL: server.URL, apiKey: "sk-test", freshness: defaultBochaFreshness, summary: true}
|
||||
_, err := bocha.Search(context.Background(), "test", 1, false)
|
||||
if err == nil || !strings.Contains(err.Error(), "429") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBochaProviderSearchAcceptsStringAndNumericCode(t *testing.T) {
|
||||
for _, body := range []string{
|
||||
`{"code":"200","data":{"webPages":{"value":[{"name":"A","url":"https://example.com/a","snippet":"s1"}]}}}`,
|
||||
`{"code":200,"data":{"webPages":{"value":[{"name":"B","url":"https://example.com/b","snippet":"s2"}]}}}`,
|
||||
} {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
bocha := &BochaProvider{client: server.Client(), baseURL: server.URL, apiKey: "sk-test", freshness: defaultBochaFreshness, summary: true}
|
||||
results, err := bocha.Search(context.Background(), "test", 1, false)
|
||||
if err != nil || len(results) != 1 {
|
||||
t.Fatalf("body %s: results = %v, err = %v", body, results, err)
|
||||
}
|
||||
server.Close()
|
||||
}
|
||||
}
|
||||
|
|
@ -26,6 +26,7 @@ const (
|
|||
WebSearchProviderTypeZhipu WebSearchProviderType = "zhipu"
|
||||
WebSearchProviderTypeExa WebSearchProviderType = "exa"
|
||||
WebSearchProviderTypeMetaso WebSearchProviderType = "metaso"
|
||||
WebSearchProviderTypeBocha WebSearchProviderType = "bocha"
|
||||
)
|
||||
|
||||
// WebSearchProviderEntity represents a configured web search provider instance for a workspace.
|
||||
|
|
@ -324,5 +325,41 @@ func GetWebSearchProviderTypes() []WebSearchProviderTypeInfo {
|
|||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "bocha",
|
||||
Name: "Bocha AI Search",
|
||||
RequiresAPIKey: true,
|
||||
SupportsProxy: true,
|
||||
Description: "Bocha AI Web Search API (requires API key)",
|
||||
DocsURL: "https://open.bochaai.com/",
|
||||
ConfigFields: []WebSearchProviderConfigField{
|
||||
{
|
||||
Key: "freshness",
|
||||
Label: "Freshness",
|
||||
Type: "select",
|
||||
Required: true,
|
||||
Default: "noLimit",
|
||||
Description: "Time range filter applied by Bocha; noLimit is recommended.",
|
||||
Options: []WebSearchProviderConfigFieldOption{
|
||||
{Label: "No limit", Value: "noLimit"},
|
||||
{Label: "Past day", Value: "oneDay"},
|
||||
{Label: "Past week", Value: "oneWeek"},
|
||||
{Label: "Past month", Value: "oneMonth"},
|
||||
{Label: "Past year", Value: "oneYear"},
|
||||
},
|
||||
},
|
||||
{
|
||||
Key: "summary",
|
||||
Label: "Summary",
|
||||
Type: "select",
|
||||
Default: "true",
|
||||
Description: "Request long text summaries and prefer them as result snippets.",
|
||||
Options: []WebSearchProviderConfigFieldOption{
|
||||
{Label: "Enabled", Value: "true"},
|
||||
{Label: "Disabled", Value: "false"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -76,3 +76,27 @@ func TestGetWebSearchProviderTypesIncludesMetaso(t *testing.T) {
|
|||
t.Fatalf("unexpected Metaso scope metadata: %+v", field)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetWebSearchProviderTypesIncludesBocha(t *testing.T) {
|
||||
var bocha *WebSearchProviderTypeInfo
|
||||
providerTypes := GetWebSearchProviderTypes()
|
||||
for i := range providerTypes {
|
||||
if providerTypes[i].ID == string(WebSearchProviderTypeBocha) {
|
||||
bocha = &providerTypes[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if bocha == nil {
|
||||
t.Fatal("Bocha provider type not found")
|
||||
}
|
||||
if !bocha.RequiresAPIKey || !bocha.SupportsProxy || len(bocha.ConfigFields) != 2 {
|
||||
t.Fatalf("unexpected Bocha metadata: %+v", bocha)
|
||||
}
|
||||
freshness := bocha.ConfigFields[0]
|
||||
if freshness.Key != "freshness" || freshness.Default != "noLimit" || len(freshness.Options) != 5 {
|
||||
t.Fatalf("unexpected Bocha freshness metadata: %+v", freshness)
|
||||
}
|
||||
if summary := bocha.ConfigFields[1]; summary.Key != "summary" || summary.Default != "true" {
|
||||
t.Fatalf("unexpected Bocha summary metadata: %+v", summary)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue