from anthropic import Anthropic
from anthropic.types import (
MessageParam,
TextBlockParam,
SearchResultBlockParam,
ToolResultBlockParam
)
client = Anthropic()
# 定义知识库搜索工具
knowledge_base_tool = {
"name": "search_knowledge_base",
"description": "搜索公司知识库以获取信息",
"input_schema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "搜索查询"
}
},
"required": ["query"]
}
}
# 处理工具调用的函数
def search_knowledge_base(query):
# 您的搜索逻辑在这里
# 以正确格式返回搜索结果
return [
SearchResultBlockParam(
type="search_result",
source="https://docs.company.com/product-guide",
title="产品配置指南",
content=[
TextBlockParam(
type="text",
text="要配置产品,请导航到设置 > 配置。默认超时时间为30秒,但可以根据您的需要在10-120秒之间调整。"
)
],
citations={"enabled": True}
),
SearchResultBlockParam(
type="search_result",
source="https://docs.company.com/troubleshooting",
title="故障排除指南",
content=[
TextBlockParam(
type="text",
text="如果遇到超时错误,请首先检查配置设置。常见原因包括网络延迟和不正确的超时值。"
)
],
citations={"enabled": True}
)
]
# 使用工具创建消息
response = client.messages.create(
model="claude-sonnet-4-5", # 适用于所有支持的模型
max_tokens=1024,
tools=[knowledge_base_tool],
messages=[
MessageParam(
role="user",
content="如何配置超时设置?"
)
]
)
# 当Claude调用工具时,提供搜索结果
if response.content[0].type == "tool_use":
tool_result = search_knowledge_base(response.content[0].input["query"])
# 将工具结果发送回去
final_response = client.messages.create(
model="claude-sonnet-4-5", # 适用于所有支持的模型
max_tokens=1024,
messages=[
MessageParam(role="user", content="如何配置超时设置?"),
MessageParam(role="assistant", content=response.content),
MessageParam(
role="user",
content=[
ToolResultBlockParam(
type="tool_result",
tool_use_id=response.content[0].id,
content=tool_result # 搜索结果放在这里
)
]
)
]
)