from anthropic import Anthropic
from anthropic.types import (
MessageParam,
TextBlockParam,
SearchResultBlockParam,
ToolResultBlockParam
)
client = Anthropic()
# 定義知識庫搜尋工具
knowledge_base_tool = {
"name": "search_knowledge_base",
"description": "Search the company knowledge base for information",
"input_schema": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The search query"
}
},
"required": ["query"]
}
}
# 處理工具呼叫的函式
def search_knowledge_base(query):
# 您的搜尋邏輯在此
# 以正確格式返回搜尋結果
return [
SearchResultBlockParam(
type="search_result",
source="https://docs.company.com/product-guide",
title="Product Configuration Guide",
content=[
TextBlockParam(
type="text",
text="To configure the product, navigate to Settings > Configuration. The default timeout is 30 seconds, but can be adjusted between 10-120 seconds based on your needs."
)
],
citations={"enabled": True}
),
SearchResultBlockParam(
type="search_result",
source="https://docs.company.com/troubleshooting",
title="Troubleshooting Guide",
content=[
TextBlockParam(
type="text",
text="If you encounter timeout errors, first check the configuration settings. Common causes include network latency and incorrect timeout values."
)
],
citations={"enabled": True}
)
]
# 使用工具建立訊息
response = client.messages.create(
model="claude-sonnet-4-5", # 適用於所有支援的模型
max_tokens=1024,
tools=[knowledge_base_tool],
messages=[
MessageParam(
role="user",
content="How do I configure the timeout settings?"
)
]
)
# 當 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="How do I configure the timeout settings?"),
MessageParam(role="assistant", content=response.content),
MessageParam(
role="user",
content=[
ToolResultBlockParam(
type="tool_result",
tool_use_id=response.content[0].id,
content=tool_result # 搜尋結果在此
)
]
)
]
)