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-20250514", # サポートされているすべてのモデルで動作
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-20250514", # サポートされているすべてのモデルで動作
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 # 検索結果をここに入れる
)
]
)
]
)