Skip to content

Commit c5c4aef

Browse files
pelmennoteamtjbckjoaoback
authored
Yandex web search (open-webui#20922)
Co-authored-by: Tim Baek <tim@openwebui.com> Co-authored-by: joaoback <156559121+joaoback@users.noreply.github.com>
1 parent 533c7b2 commit c5c4aef

5 files changed

Lines changed: 251 additions & 1 deletion

File tree

backend/open_webui/config.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3410,6 +3410,24 @@ class BannerModel(BaseModel):
34103410
os.environ.get("EXTERNAL_WEB_LOADER_API_KEY", ""),
34113411
)
34123412

3413+
YANDEX_WEB_SEARCH_URL = PersistentConfig(
3414+
"YANDEX_WEB_SEARCH_URL",
3415+
"rag.web.search.yandex_web_search_url",
3416+
os.environ.get("YANDEX_WEB_SEARCH_URL", ""),
3417+
)
3418+
3419+
YANDEX_WEB_SEARCH_API_KEY = PersistentConfig(
3420+
"YANDEX_WEB_SEARCH_API_KEY",
3421+
"rag.web.search.yandex_web_search_api_key",
3422+
os.environ.get("YANDEX_WEB_SEARCH_API_KEY", ""),
3423+
)
3424+
3425+
YANDEX_WEB_SEARCH_CONFIG = PersistentConfig(
3426+
"YANDEX_WEB_SEARCH_CONFIG",
3427+
"rag.web.search.yandex_web_search_config",
3428+
os.environ.get("YANDEX_WEB_SEARCH_CONFIG", ""),
3429+
)
3430+
34133431
####################################
34143432
# Images
34153433
####################################

backend/open_webui/main.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,9 @@
353353
EXTERNAL_WEB_SEARCH_API_KEY,
354354
EXTERNAL_WEB_LOADER_URL,
355355
EXTERNAL_WEB_LOADER_API_KEY,
356+
YANDEX_WEB_SEARCH_URL,
357+
YANDEX_WEB_SEARCH_API_KEY,
358+
YANDEX_WEB_SEARCH_CONFIG,
356359
# WebUI
357360
WEBUI_AUTH,
358361
WEBUI_NAME,
@@ -1008,6 +1011,9 @@ async def lifespan(app: FastAPI):
10081011
app.state.config.EXTERNAL_WEB_SEARCH_API_KEY = EXTERNAL_WEB_SEARCH_API_KEY
10091012
app.state.config.EXTERNAL_WEB_LOADER_URL = EXTERNAL_WEB_LOADER_URL
10101013
app.state.config.EXTERNAL_WEB_LOADER_API_KEY = EXTERNAL_WEB_LOADER_API_KEY
1014+
app.state.config.YANDEX_WEB_SEARCH_URL = YANDEX_WEB_SEARCH_URL
1015+
app.state.config.YANDEX_WEB_SEARCH_API_KEY = YANDEX_WEB_SEARCH_API_KEY
1016+
app.state.config.YANDEX_WEB_SEARCH_CONFIG = YANDEX_WEB_SEARCH_CONFIG
10111017

10121018

10131019
app.state.config.PLAYWRIGHT_WS_URL = PLAYWRIGHT_WS_URL
Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,147 @@
1+
import base64
2+
import io
3+
import json
4+
import logging
5+
import os
6+
from typing import Optional, List
7+
8+
import requests
9+
10+
from fastapi import Request
11+
12+
from open_webui.retrieval.web.main import SearchResult, get_filtered_results
13+
from open_webui.utils.headers import include_user_info_headers
14+
15+
from xml.etree import ElementTree as ET
16+
from xml.etree.ElementTree import Element
17+
18+
log = logging.getLogger(__name__)
19+
20+
21+
def xml_element_contents_to_string(element: Element) -> str:
22+
buffer = [element.text if element.text else ""]
23+
24+
for child in element:
25+
buffer.append(xml_element_contents_to_string(child))
26+
27+
buffer.append(element.tail if element.tail else "")
28+
29+
return "".join(buffer)
30+
31+
32+
def search_yandex(
33+
request: Request,
34+
yandex_search_url: str,
35+
yandex_search_api_key: str,
36+
yandex_search_config: str,
37+
query: str,
38+
count: int,
39+
filter_list: Optional[List[str]] = None,
40+
user=None,
41+
) -> List[SearchResult]:
42+
try:
43+
headers = {
44+
"User-Agent": "Open WebUI (https://github.com/open-webui/open-webui) RAG Bot",
45+
"Authorization": f"Api-Key {yandex_search_api_key}",
46+
}
47+
48+
if user is not None:
49+
headers = include_user_info_headers(headers, user)
50+
51+
chat_id = getattr(request.state, "chat_id", None)
52+
if chat_id:
53+
headers["X-OpenWebUI-Chat-Id"] = str(chat_id)
54+
55+
payload = {} if yandex_search_config == "" else json.loads(yandex_search_config)
56+
57+
if type(payload.get("query", None)) != dict:
58+
payload["query"] = {}
59+
60+
if "searchType" not in payload["query"]:
61+
payload["query"]["searchType"] = "SEARCH_TYPE_RU"
62+
63+
payload["query"]["queryText"] = query
64+
65+
if type(payload.get("groupSpec", None)) != dict:
66+
payload["groupSpec"] = {}
67+
68+
if "groupMode" not in payload["groupSpec"]:
69+
payload["groupSpec"]["groupMode"] = "GROUP_MODE_DEEP"
70+
71+
payload["groupSpec"]["groupsOnPage"] = count
72+
payload["groupSpec"]["docsInGroup"] = 1
73+
74+
response = requests.post(
75+
"https://searchapi.api.cloud.yandex.net/v2/web/search" if yandex_search_url == "" else yandex_search_url,
76+
headers=headers,
77+
json=payload,
78+
)
79+
80+
response.raise_for_status()
81+
82+
response_body = response.json()
83+
if "rawData" not in response_body:
84+
raise Exception(f"No `rawData` in response body: {response_body}")
85+
86+
search_result_body_bytes = base64.decodebytes(bytes(response_body["rawData"], "utf-8"))
87+
88+
doc_root = ET.parse(io.BytesIO(search_result_body_bytes))
89+
90+
results = []
91+
92+
for group in doc_root.findall("response/results/grouping/group"):
93+
results.append({
94+
"url": xml_element_contents_to_string(group.find("doc/url")).strip("\n"),
95+
"title": xml_element_contents_to_string(group.find("doc/title")).strip("\n"),
96+
"snippet": xml_element_contents_to_string(group.find("doc/passages/passage")),
97+
})
98+
99+
results = get_filtered_results(results, filter_list)
100+
101+
results = [
102+
SearchResult(
103+
link=result.get("url"),
104+
title=result.get("title"),
105+
snippet=result.get("snippet"),
106+
)
107+
for result in results[:count]
108+
]
109+
110+
log.info(f"Yandex search results: {results}")
111+
112+
return results
113+
except Exception as e:
114+
log.error(f"Error in search: {e}")
115+
116+
return []
117+
118+
119+
if __name__ == "__main__":
120+
from starlette.datastructures import Headers
121+
from fastapi import FastAPI
122+
123+
result = search_yandex(
124+
Request(
125+
{
126+
"type": "http",
127+
"asgi.version": "3.0",
128+
"asgi.spec_version": "2.0",
129+
"method": "GET",
130+
"path": "/internal",
131+
"query_string": b"",
132+
"headers": Headers({}).raw,
133+
"client": ("127.0.0.1", 12345),
134+
"server": ("127.0.0.1", 80),
135+
"scheme": "http",
136+
"app": FastAPI(),
137+
},
138+
None,
139+
),
140+
os.environ.get("YANDEX_WEB_SEARCH_URL", ""),
141+
os.environ.get("YANDEX_WEB_SEARCH_API_KEY", ""),
142+
os.environ.get("YANDEX_WEB_SEARCH_CONFIG", "{\"query\": {\"searchType\": \"SEARCH_TYPE_COM\"}}"),
143+
"TOP movies of the past year",
144+
3,
145+
)
146+
147+
print(result)

backend/open_webui/routers/retrieval.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@
7676
from open_webui.retrieval.web.sougou import search_sougou
7777
from open_webui.retrieval.web.firecrawl import search_firecrawl
7878
from open_webui.retrieval.web.external import search_external
79+
from open_webui.retrieval.web.yandex import search_yandex
7980

8081
from open_webui.retrieval.utils import (
8182
get_content_from_url,
@@ -578,6 +579,9 @@ async def get_rag_config(request: Request, user=Depends(get_admin_user)):
578579
"YOUTUBE_LOADER_LANGUAGE": request.app.state.config.YOUTUBE_LOADER_LANGUAGE,
579580
"YOUTUBE_LOADER_PROXY_URL": request.app.state.config.YOUTUBE_LOADER_PROXY_URL,
580581
"YOUTUBE_LOADER_TRANSLATION": request.app.state.YOUTUBE_LOADER_TRANSLATION,
582+
"YANDEX_WEB_SEARCH_URL": request.app.state.config.YANDEX_WEB_SEARCH_URL,
583+
"YANDEX_WEB_SEARCH_API_KEY": request.app.state.config.YANDEX_WEB_SEARCH_API_KEY,
584+
"YANDEX_WEB_SEARCH_CONFIG": request.app.state.config.YANDEX_WEB_SEARCH_CONFIG,
581585
},
582586
}
583587

@@ -641,6 +645,9 @@ class WebConfig(BaseModel):
641645
YOUTUBE_LOADER_LANGUAGE: Optional[List[str]] = None
642646
YOUTUBE_LOADER_PROXY_URL: Optional[str] = None
643647
YOUTUBE_LOADER_TRANSLATION: Optional[str] = None
648+
YANDEX_WEB_SEARCH_URL: Optional[str] = None
649+
YANDEX_WEB_SEARCH_API_KEY: Optional[str] = None
650+
YANDEX_WEB_SEARCH_CONFIG: Optional[str] = None
644651

645652

646653
class ConfigForm(BaseModel):
@@ -1176,6 +1183,15 @@ async def update_rag_config(
11761183
request.app.state.YOUTUBE_LOADER_TRANSLATION = (
11771184
form_data.web.YOUTUBE_LOADER_TRANSLATION
11781185
)
1186+
request.app.state.config.YANDEX_WEB_SEARCH_URL = (
1187+
form_data.web.YANDEX_WEB_SEARCH_URL
1188+
)
1189+
request.app.state.config.YANDEX_WEB_SEARCH_API_KEY = (
1190+
form_data.web.YANDEX_WEB_SEARCH_API_KEY
1191+
)
1192+
request.app.state.config.YANDEX_WEB_SEARCH_CONFIG = (
1193+
form_data.web.YANDEX_WEB_SEARCH_CONFIG
1194+
)
11791195

11801196
return {
11811197
"status": True,
@@ -1300,6 +1316,9 @@ async def update_rag_config(
13001316
"YOUTUBE_LOADER_LANGUAGE": request.app.state.config.YOUTUBE_LOADER_LANGUAGE,
13011317
"YOUTUBE_LOADER_PROXY_URL": request.app.state.config.YOUTUBE_LOADER_PROXY_URL,
13021318
"YOUTUBE_LOADER_TRANSLATION": request.app.state.YOUTUBE_LOADER_TRANSLATION,
1319+
"YANDEX_WEB_SEARCH_URL": request.app.state.config.YANDEX_WEB_SEARCH_URL,
1320+
"YANDEX_WEB_SEARCH_API_KEY": request.app.state.config.YANDEX_WEB_SEARCH_API_KEY,
1321+
"YANDEX_WEB_SEARCH_CONFIG": request.app.state.config.YANDEX_WEB_SEARCH_CONFIG,
13031322
},
13041323
}
13051324

@@ -2240,6 +2259,17 @@ def search_web(
22402259
request.app.state.config.WEB_SEARCH_DOMAIN_FILTER_LIST,
22412260
user=user,
22422261
)
2262+
elif engine == "yandex":
2263+
return search_yandex(
2264+
request,
2265+
request.app.state.config.YANDEX_WEB_SEARCH_URL,
2266+
request.app.state.config.YANDEX_WEB_SEARCH_API_KEY,
2267+
request.app.state.config.YANDEX_WEB_SEARCH_CONFIG,
2268+
query,
2269+
request.app.state.config.WEB_SEARCH_RESULT_COUNT,
2270+
request.app.state.config.WEB_SEARCH_DOMAIN_FILTER_LIST,
2271+
user=user,
2272+
)
22432273
else:
22442274
raise Exception("No search engine API key found in environment variables")
22452275

src/lib/components/admin/Settings/WebSearch.svelte

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import { toast } from 'svelte-sonner';
88
import SensitiveInput from '$lib/components/common/SensitiveInput.svelte';
99
import Tooltip from '$lib/components/common/Tooltip.svelte';
10+
import Textarea from '$lib/components/common/Textarea.svelte';
1011
1112
const i18n = getContext('i18n');
1213
@@ -35,7 +36,8 @@
3536
'perplexity',
3637
'sougou',
3738
'firecrawl',
38-
'external'
39+
'external',
40+
'yandex'
3941
];
4042
let webLoaderEngines = ['playwright', 'firecrawl', 'tavily', 'external'];
4143
@@ -735,6 +737,53 @@
735737
/>
736738
</div>
737739
</div>
740+
{:else if webConfig.WEB_SEARCH_ENGINE === 'yandex'}
741+
<div class="mb-2.5 flex w-full flex-col">
742+
<div>
743+
<div class=" self-center text-xs font-medium mb-1">
744+
{$i18n.t('Yandex Web Search URL')}
745+
</div>
746+
747+
<div class="flex w-full">
748+
<div class="flex-1">
749+
<input
750+
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
751+
type="text"
752+
placeholder={$i18n.t('Enter Yandex Web Search URL')}
753+
bind:value={webConfig.YANDEX_WEB_SEARCH_URL}
754+
autocomplete="off"
755+
/>
756+
</div>
757+
</div>
758+
</div>
759+
760+
<div class="mt-2">
761+
<div class=" self-center text-xs font-medium mb-1">
762+
{$i18n.t('Yandex Web Search API Key')}
763+
</div>
764+
765+
<SensitiveInput
766+
placeholder={$i18n.t('Enter Yandex Web Search API Key')}
767+
bind:value={webConfig.YANDEX_WEB_SEARCH_API_KEY}
768+
/>
769+
</div>
770+
771+
<div class="mb-2.5">
772+
<div class=" mb-1 text-xs font-medium">{$i18n.t('Yandex Web Search config')}</div>
773+
774+
<Tooltip
775+
content={$i18n.t('Leave empty to use the default config, or enter a valid json (see https://yandex.cloud/en/docs/search-api/api-ref/WebSearch/search#yandex.cloud.searchapi.v2.WebSearchRequest)')}
776+
placement="top-start"
777+
>
778+
<Textarea
779+
bind:value={webConfig.YANDEX_WEB_SEARCH_CONFIG}
780+
placeholder={$i18n.t(
781+
'Leave empty to use the default config, or enter a valid json (see https://yandex.cloud/en/docs/search-api/api-ref/WebSearch/search#yandex.cloud.searchapi.v2.WebSearchRequest)'
782+
)}
783+
/>
784+
</Tooltip>
785+
</div>
786+
</div>
738787
{/if}
739788

740789
{#if webConfig.WEB_SEARCH_ENGINE === 'duckduckgo'}

0 commit comments

Comments
 (0)