Google ColabでClaudeのTools機能を触ってみた
はじめに
OpenAIのFunction Callingに匹敵する機能を持つ、Anthropicが提供するClaude Toolsを試してみました。
本記事では、Google Colabで、ClaudeのTools機能を使用して最新のニュースを取得するプロセスを解説します。
必要な準備:
Googleアカウント:Colabを使用するために必須です。
Claude APIキー: Claude APIを利用するために必要です。AnthropicのAPIサイトをから取得できます。
Google Colabでの設定方法
パッケージのインストール
Google Colabのノートブックで以下のコマンドを実行し、必要なパッケージをインストールします。
!pip install anthropic
ライブラリのインポート
インストールしたパッケージから必要なライブラリをインポートし、Claude APIキーを設定します。
from anthropic import Anthropic
anthropic_api_key = "your_anthropic_api_key"
client = Anthropic(api_key=anthropic_api_key)
MODEL_NAME = "claude-3-opus-20240229"
ニュース取得機能の実装
このセクションでは、NewsAPIを使用して特定のキーワードに基づいたニュース記事を取得するための関数fetch_newsの詳細な実装方法について説明します。以下のサイトからNewsAPIを取得し、`your_newsapi_api_key`に貼り付けます。
https://newsapi.org/
import requests
def fetch_news(keywords, language='en'):
API_KEY = 'your_newsapi_api_key'
BASE_URL = 'https://newsapi.org/v2/everything?'
url = f'{BASE_URL}q={keywords}&language={language}&apiKey={API_KEY}'
try:
response = requests.get(url)
response.raise_for_status()
articles = response.json().get('articles', [])
news_results = []
for article in articles[:3]:
news_results.append(f"Title: {article['title']}, Description: {article['description']}, URL: {article['url']}")
return '\n'.join(news_results) if news_results else "No news found."
except requests.RequestException as e:
return str(e)
tools = [
{
"name": "news_fetcher",
"description": "Fetches news based on keywords.",
"input_schema": {
"type": "object",
"properties": {
"keywords": {
"type": "string",
"description": "Keywords to search for news."
},
"language": {
"type": "string",
"description": "The language of the news articles."
}
},
"required": ["keywords"]
}
}
]
アシスタントの設定方法の詳細
アシスタントの設定は、ユーザーからのメッセージを受け取り、Claude 3 OpusのTool機能を使用して質問に回答するプロセスです。以下に、ユーザーのメッセージを受けてニュースを取得し、結果を表示するまでのフローを示します。
def process_tool_call(tool_name, tool_input):
if tool_name == "news_fetcher":
keywords = tool_input["keywords"]
language = tool_input.get("language", "en")
return fetch_news(keywords, language)
def chat_with_claude(user_message):
print(f"\n{'='*50}\nUser Message: {user_message}\n{'='*50}")
message = client.beta.tools.messages.create(
model=MODEL_NAME,
max_tokens=4096,
messages=[{"role": "user", "content": user_message}],
tools=tools,
)
print(f"\nInitial Response:")
print(f"Stop Reason: {message.stop_reason}")
print(f"Content: {message.content}")
if message.stop_reason == "tool_use":
tool_use = next(block for block in message.content if block.type == "tool_use")
tool_name = tool_use.name
tool_input = tool_use.input
print(f"\nTool Used: {tool_name}")
print(f"Tool Input: {tool_input}")
tool_result = process_tool_call(tool_name, tool_input)
print(f"Tool Result: {tool_result}")
response = client.beta.tools.messages.create(
model=MODEL_NAME,
max_tokens=4096,
messages=[
{"role": "user", "content": user_message},
{"role": "assistant", "content": message.content},
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use.id,
"content": tool_result,
}
],
},
],
tools=tools,
)
else:
response = message
final_response = next(
(block.text for block in response.content if hasattr(block, "text")),
None,
)
print(response.content)
print(f"\nFinal Response: {final_response}")
return final_response
実際の質問
実際に「What's the technology news?」と質問して、Claude 3 Opusを通じて最新のテクノロジーニュースを取得してみましょう。この質問により、Claude 3はNewsAPIを利用して、指定されたトピックに関連するニュース記事を検索し、結果を返します。
chat_with_claude("What's the technology news?")
終わりに
OpenAIのFunction Callingに匹敵する機能を持つ、Anthropicが提供するClaude Toolsを試してみましたが、ほぼほぼ機能は同じだなという印象を受けました。
ご質問やご意見がありましたら、Twitter @junichikawaAI までお気軽にフォローしてご連絡ください。
この記事が気に入ったらサポートをしてみませんか?