Skip to content

Commit 0041a84

Browse files
authored
高级搜索工具 Web search 业务] (#41)
* 高级搜索工具 Web search 业务 * 高级搜索工具 Web search 业务集成测试 * websearch
1 parent 6045b60 commit 0041a84

File tree

9 files changed

+288
-1
lines changed

9 files changed

+288
-1
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
from zhipuai import ZhipuAI
2+
import zhipuai
3+
4+
import logging
5+
import logging.config
6+
7+
8+
def test_tools(logging_conf):
9+
logging.config.dictConfig(logging_conf) # type: ignore
10+
client = ZhipuAI() # 填写您自己的APIKey
11+
try:
12+
response = client.tools.web_search(
13+
model="web-search-pro",
14+
messages=[
15+
{
16+
"content": "你好",
17+
"role": "user",
18+
}
19+
],
20+
stream=False
21+
)
22+
print(response)
23+
24+
25+
26+
except zhipuai.core._errors.APIRequestFailedError as err:
27+
print(err)
28+
except zhipuai.core._errors.APIInternalError as err:
29+
print(err)
30+
except zhipuai.core._errors.APIStatusError as err:
31+
print(err)
32+
33+
34+
def test_tools_stream(logging_conf):
35+
logging.config.dictConfig(logging_conf) # type: ignore
36+
client = ZhipuAI() # 填写您自己的APIKey
37+
try:
38+
response = client.tools.web_search(
39+
model="web-search-pro",
40+
messages=[
41+
{
42+
"content": "你好",
43+
"role": "user",
44+
}
45+
],
46+
stream=True
47+
)
48+
for item in response:
49+
print(item)
50+
51+
52+
except zhipuai.core._errors.APIRequestFailedError as err:
53+
print(err)
54+
except zhipuai.core._errors.APIInternalError as err:
55+
print(err)
56+
except zhipuai.core._errors.APIStatusError as err:
57+
print(err)

zhipuai/_client.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ def __init__(
5959
self.fine_tuning = api_resource.fine_tuning.FineTuning(self)
6060
self.batches = api_resource.Batches(self)
6161
self.knowledge = api_resource.Knowledge(self)
62+
self.tools = api_resource.Tools(self)
6263

6364
@property
6465
@override

zhipuai/api_resource/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,9 @@
2424
from .knowledge import (
2525
Knowledge
2626
)
27-
27+
from .tools import (
28+
Tools
29+
)
2830
__all__ = [
2931
'AsyncCompletions',
3032
'Chat',
@@ -36,5 +38,6 @@
3638
'FineTuning',
3739
'Batches',
3840
'Knowledge',
41+
'Tools',
3942

4043
]
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
from .tools import Tools
2+
3+
__all__ = ['Tools']
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
from __future__ import annotations
2+
3+
from typing import TYPE_CHECKING, List, Union, Dict, Optional
4+
from typing_extensions import Literal
5+
6+
from ...core import NOT_GIVEN, Body, Headers, NotGiven, BaseAPI, maybe_transform, StreamResponse, deepcopy_minimal
7+
8+
import httpx
9+
10+
from ...core import (
11+
make_request_options,
12+
)
13+
import logging
14+
15+
from ...types.tools import tools_web_search_params, WebSearch, WebSearchChunk
16+
17+
logger = logging.getLogger(__name__)
18+
19+
if TYPE_CHECKING:
20+
from ..._client import ZhipuAI
21+
22+
__all__ = ["Tools"]
23+
24+
25+
class Tools(BaseAPI):
26+
27+
def __init__(self, client: "ZhipuAI") -> None:
28+
super().__init__(client)
29+
30+
def web_search(
31+
self,
32+
*,
33+
model: str,
34+
request_id: Optional[str] | NotGiven = NOT_GIVEN,
35+
stream: Optional[Literal[False]] | Literal[True] | NotGiven = NOT_GIVEN,
36+
messages: Union[str, List[str], List[int], object, None],
37+
scope: Optional[str] | NotGiven = NOT_GIVEN,
38+
location: Optional[str] | NotGiven = NOT_GIVEN,
39+
recent_days: Optional[int] | NotGiven = NOT_GIVEN,
40+
extra_headers: Headers | None = None,
41+
extra_body: Body | None = None,
42+
timeout: float | httpx.Timeout | None | NotGiven = NOT_GIVEN,
43+
) -> WebSearch | StreamResponse[WebSearchChunk]:
44+
45+
body = deepcopy_minimal(
46+
{
47+
"model": model,
48+
"request_id": request_id,
49+
"messages": messages,
50+
"stream": stream,
51+
"scope": scope,
52+
"location": location,
53+
"recent_days": recent_days,
54+
})
55+
return self._post(
56+
"/tools",
57+
body= maybe_transform(body, tools_web_search_params.WebSearchParams),
58+
options=make_request_options(
59+
extra_headers=extra_headers, extra_body=extra_body, timeout=timeout
60+
),
61+
cast_type=WebSearch,
62+
stream=stream or False,
63+
stream_cls=StreamResponse[WebSearchChunk],
64+
)

zhipuai/types/tools/__init__.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from .web_search import (
2+
WebSearch,
3+
SearchIntent,
4+
SearchResult,
5+
SearchRecommend,
6+
)
7+
8+
from .web_search_chunk import (
9+
WebSearchChunk
10+
)
11+
12+
__all__ = [
13+
'WebSearch',
14+
'SearchIntent',
15+
'SearchResult',
16+
'SearchRecommend',
17+
'WebSearchChunk'
18+
]
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
2+
from __future__ import annotations
3+
4+
from typing import Union, Optional, List
5+
from typing_extensions import Literal, Required, TypedDict
6+
7+
__all__ = ["WebSearchParams"]
8+
9+
10+
class WebSearchParams(TypedDict):
11+
"""
12+
工具名:web-search-pro参数类型定义
13+
14+
Attributes:
15+
:param model: str, 模型名称
16+
:param request_id: Optional[str], 请求ID
17+
:param stream: Optional[bool], 是否流式
18+
:param messages: Union[str, List[str], List[int], object, None],
19+
包含历史对话上下文的内容,按照 {"role": "user", "content": "你好"} 的json 数组形式进行传参
20+
当前版本仅支持 User Message 单轮对话,工具会理解User Message并进行搜索,
21+
请尽可能传入不带指令格式的用户原始提问,以提高搜索准确率。
22+
:param scope: Optional[str], 指定搜索范围,全网、学术等,默认全网
23+
:param location: Optional[str], 指定搜索用户地区 location 提高相关性
24+
:param recent_days: Optional[int],支持指定返回 N 天(1-30)更新的搜索结果
25+
26+
27+
"""
28+
model: str
29+
request_id: Optional[str]
30+
stream: Optional[bool]
31+
messages: Union[str, List[str], List[int], object, None]
32+
scope: Optional[str] = None
33+
location: Optional[str] = None
34+
recent_days: Optional[int] = None

zhipuai/types/tools/web_search.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
from typing import List, Optional
2+
3+
from ..chat.chat_completion import Function
4+
from ...core import BaseModel
5+
6+
__all__ = [
7+
"WebSearch",
8+
"SearchIntent",
9+
"SearchResult",
10+
"SearchRecommend",
11+
]
12+
13+
14+
class SearchIntent(BaseModel):
15+
index: int
16+
# 搜索轮次,默认为 0
17+
query: str
18+
# 搜索优化 query
19+
intent: str
20+
# 判断的意图类型
21+
keywords: str
22+
# 搜索关键词
23+
24+
25+
class SearchResult(BaseModel):
26+
index: int
27+
# 搜索轮次,默认为 0
28+
title: str
29+
# 标题
30+
link: str
31+
# 链接
32+
content: str
33+
# 内容
34+
icon: str
35+
# 图标
36+
media: str
37+
# 来源媒体
38+
refer: str
39+
# 角标序号 [ref_1]
40+
41+
42+
class SearchRecommend(BaseModel):
43+
index: int
44+
# 搜索轮次,默认为 0
45+
query: str
46+
# 推荐query
47+
48+
49+
class WebSearchMessageToolCall(BaseModel):
50+
id: str
51+
search_intent: Optional[SearchIntent]
52+
search_result: Optional[SearchResult]
53+
search_recommend: Optional[SearchRecommend]
54+
type: str
55+
56+
57+
class WebSearchMessage(BaseModel):
58+
role: str
59+
tool_calls: Optional[List[WebSearchMessageToolCall]] = None
60+
61+
62+
class WebSearchChoice(BaseModel):
63+
index: int
64+
finish_reason: str
65+
message: WebSearchMessage
66+
67+
68+
class WebSearch(BaseModel):
69+
created: Optional[int] = None
70+
choices: List[WebSearchChoice]
71+
request_id: Optional[str] = None
72+
id: Optional[str] = None
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
from typing import List, Optional, Dict, Any
2+
3+
from .web_search import SearchIntent, SearchResult, SearchRecommend
4+
from ...core import BaseModel
5+
6+
__all__ = [
7+
"WebSearchChunk"
8+
]
9+
10+
11+
class ChoiceDeltaToolCall(BaseModel):
12+
index: int
13+
id: Optional[str] = None
14+
15+
search_intent: Optional[SearchIntent] = None
16+
search_result: Optional[SearchResult] = None
17+
search_recommend: Optional[SearchRecommend] = None
18+
type: Optional[str] = None
19+
20+
21+
class ChoiceDelta(BaseModel):
22+
role: Optional[str] = None
23+
tool_calls: Optional[List[ChoiceDeltaToolCall]] = None
24+
25+
26+
class Choice(BaseModel):
27+
delta: ChoiceDelta
28+
finish_reason: Optional[str] = None
29+
index: int
30+
31+
32+
class WebSearchChunk(BaseModel):
33+
id: Optional[str] = None
34+
choices: List[Choice]
35+
created: Optional[int] = None

0 commit comments

Comments
 (0)