このガイドに従うには、以下が必要です:
ANTHROPIC_API_KEY環境変数として設定)必要なパッケージをインストールします:
pip install anthropic streamlit python-dotenvカスタマーサポートプロセスの一部を自動化するためにClaudeのようなLLMを採用すべきであることを示す主な指標は次のとおりです:
他のLLMよりもClaudeを選択する際の考慮事項:
顧客がClaudeとどのように、いつやり取りすることを期待するかを定義するために、理想的な顧客インタラクションの概要を作成します。この概要は、ソリューションの技術要件を決定するのに役立ちます。
自動車保険のカスタマーサポートにおけるチャットインタラクションの例を以下に示します:
カスタマーサポートチャットは、質問への回答から情報の取得、リクエストに対するアクションの実行まで、単一の顧客インタラクションにまとめられた複数の異なるタスクの集合体です。構築を開始する前に、理想的な顧客インタラクションを、Claudeに実行させたいすべてのタスクに分解します。これにより、すべてのタスクについてClaudeにプロンプトを与えて評価できるようになり、テストケースを作成する際に考慮すべきインタラクションの範囲を把握できます。
保険インタラクションの例に関連する主なタスクは次のとおりです:
挨拶と一般的なガイダンス
製品情報
サポートチームと協力して、測定可能なベンチマークと目標を用いて成功基準を定義し、詳細な評価を作成します。
定義されたタスクをClaudeがどの程度うまく実行できるかを評価するために使用できる基準とベンチマークは次のとおりです:
サポートにClaudeを採用することによるビジネスへの影響を評価するために使用できる基準とベンチマークは次のとおりです:
モデルの選択は、コスト、精度、応答時間のトレードオフによって決まります。
カスタマーサポートチャットの場合、Claude Opus 5は、長いマルチステップの会話にわたる深い推論を必要とする最も複雑なサポートシナリオを含め、知能、レイテンシ、コストのバランスを取るのに適しています。ただし、RAG、ツール使用、または長いコンテキストのプロンプトを含む複数のプロンプトによる会話フローがある場合は、レイテンシを最適化するためにClaude Haiku 4.5の方が適している場合があります。
カスタマーサポートにClaudeを使用するには、Claudeが適切に応答するための十分な指示とコンテキストを持ちながら、幅広い顧客の問い合わせに対応できる十分な柔軟性を持つ必要があります。
まず、システムプロンプトから始めて、強力なプロンプトの要素を書きます。config.pyというファイルを作成し、以下の各ブロックを追加します:
IDENTITY = """You are Eva, a friendly and knowledgeable AI assistant for Acme Insurance
Company. Your role is to warmly welcome customers and provide information on
Acme's insurance offerings, which include car insurance and electric car
insurance. You can also help customers get quotes for their insurance needs."""Userターン内に書いた方がうまく機能します(唯一の例外はロールプロンプティングです)。詳細はシステムプロンプトでClaudeに役割を与えるをご覧ください。複雑なプロンプトはサブセクションに分解し、一度に1つの部分を書くのが最善です。各タスクについて、Claudeがタスクをうまく実行するために必要なプロンプトの部分を定義するステップバイステップのプロセスに従うことで、より大きな成功を収めることができるかもしれません。この自動車保険カスタマーサポートの例では、「挨拶と一般的なガイダンス」タスクから始めて、プロンプトのすべての部分を段階的に書いていきます。これにより、プロンプト全体の個々の部分をより迅速に調整できるため、プロンプトのデバッグも容易になります。
STATIC_GREETINGS_AND_GENERAL = """
<static_context>
Acme Auto Insurance: Your Trusted Companion on the Road
About:
At Acme Insurance, we understand that your vehicle is more than just a mode of transportation—it's your ticket to life's adventures.
Since 1985, we've been crafting auto insurance policies that give drivers the confidence to explore, commute, and travel with peace of mind.
Whether you're navigating city streets or embarking on cross-country road trips, Acme is there to protect you and your vehicle.
Our innovative auto insurance policies are designed to adapt to your unique needs, covering everything from fender benders to major collisions.
With Acme's award-winning customer service and swift claim resolution, you can focus on the joy of driving while we handle the rest.
We're not just an insurance provider—we're your co-pilot in life's journeys.
Choose Acme Auto Insurance and experience the assurance that comes with superior coverage and genuine care. Because at Acme, we don't just
insure your car—we fuel your adventures on the open road.
Note: We also offer specialized coverage for electric vehicles, ensuring that drivers of all car types can benefit from our protection.
Acme Insurance offers the following products:
- Car insurance
- Electric car insurance
- Two-wheeler insurance
Business hours: Monday-Friday, 9 AM - 5 PM EST
Customer service number: 1-800-123-4567
</static_context>
"""次に、自動車保険と電気自動車保険の情報についても同じことを行います。
STATIC_CAR_INSURANCE = """
<static_context>
Car Insurance Coverage:
Acme's car insurance policies typically cover:
1. Liability coverage: Pays for bodily injury and property damage you cause to others.
2. Collision coverage: Pays for damage to your car in an accident.
3. Comprehensive coverage: Pays for damage to your car from non-collision incidents.
4. Medical payments coverage: Pays for medical expenses after an accident.
5. Uninsured/underinsured motorist coverage: Protects you if you're hit by a driver with insufficient insurance.
Optional coverages include:
- Rental car reimbursement
- Roadside assistance
- New car replacement
</static_context>
"""
STATIC_ELECTRIC_CAR_INSURANCE = """
<static_context>
Electric Car Insurance:
Our specialized electric car insurance goes beyond traditional auto coverage,
offering tailored protection for your high-tech investment. In addition to standard coverages, we offer:
- Safeguarding expensive battery systems
- Covering home charging equipment
- Adapting to the rapidly evolving world of electric vehicles
Whether you're driving a Rivian, Nissan Leaf, Chevrolet Bolt,
or any other electric vehicle, our knowledgeable agents are ready to craft a policy
that gives you the confidence to enjoy every electron-powered mile.
</static_context>
"""静的コンテンツが揃ったので、Claudeの応答を導くために少なくとも4〜5個の「良い」インタラクションのサンプルを追加します。これらの例は、理想的な顧客インタラクションを代表するものであり、ガードレール、ツール呼び出しなどを含めることができます。
EXAMPLES = """
Here are a few examples of how you can interact with customers:
<example 1>
H: Hi, do you offer commercial insurance for small businesses?
A: Ah! Unfortunately, we don't offer commercial insurance at this time.
However, we do provide a range of personal insurance products including car insurance and electric car insurance.
Would you like to know more about these offerings?
</example 1>
<example 2>
H: Hi, what are your business hours?
A: Our business hours are Monday to Friday, 9 AM to 5 PM EST.
If you have any questions or need assistance, feel free to reach out during those times.
How else can I assist you today?
</example 2>
<example 3>
H: I'm shopping for car insurance. What does Acme offer?
A: Great choice! Acme's car insurance policies typically include:
- Liability coverage: Protects you if you're at fault in an accident
- Collision coverage: Pays for damage to your car in an accident
- Comprehensive coverage: Covers non-collision incidents like theft or vandalism
- Medical payments coverage: Pays for medical expenses after an accident
- Uninsured/underinsured motorist coverage: Protects you from drivers with insufficient insurance
We also offer optional coverages like rental car reimbursement, roadside assistance, and new car replacement.
Would you like more details on any of these coverages, or do you have specific questions about insuring your vehicle?
</example 3>
<example 4>
H: I'd like to hear about your electric car insurance.
A: Certainly! Our electric car insurance is specially designed to meet the unique needs of electric vehicle owners.
In addition to all the standard coverages we offer for regular cars, our electric car policies include:
- Battery coverage: Protection against damage or degradation of your vehicle's expensive battery system
- Tech package: Covers repairs or replacement of advanced electronics and onboard computer systems
- Charging station coverage: Protects both home and portable charging equipment
- Cybersecurity protection: Coverage against hacking or digital threats
- Specialized roadside assistance: Includes flatbed towing to protect the vehicle's undercarriage
We cover a wide range of electric vehicles, including popular models from Tesla, Rivian, Nissan, Chevrolet, and more.
Is there a specific electric vehicle you're looking to insure, or would you like more details on any of these coverages?
</example 4>
<example 5>
H: I'd like to get a quote for my car insurance.
A: Certainly! I'd be happy to help you get a quote for your car insurance.
To provide you with an accurate quote, I'll need to collect some information about your vehicle and the primary driver.
Let's start with the basics:
1. What is the make and model of your vehicle?
2. What year was it manufactured?
3. Approximately how many miles have you driven?
4. What is the age of the primary driver?
Once you provide this information, I'll use our quoting tool to generate a personalized insurance quote for you.
</example 5>
"""また、Claudeが顧客とどのようにやり取りすべきかについての、すべきこととすべきでないことを概説する重要な指示も含める必要があります。 これは、ブランドのガードレールやサポートポリシーから引用できます。
ADDITIONAL_GUARDRAILS = """Please adhere to the following guardrails:
1. Only provide information about insurance types listed in our offerings.
2. If asked about an insurance type we don't offer, politely state
that we don't provide that service.
3. Do not speculate about future product offerings or company plans.
4. Don't make promises or enter into agreements it's not authorized to make.
You only provide information and guidance.
5. Do not mention any competitor's products or services.
"""次に、これらすべてのセクションを1つの文字列に結合して、プロンプトとして使用します。
TASK_SPECIFIC_INSTRUCTIONS = " ".join(
[
STATIC_GREETINGS_AND_GENERAL,
STATIC_CAR_INSURANCE,
STATIC_ELECTRIC_CAR_INSURANCE,
EXAMPLES,
ADDITIONAL_GUARDRAILS,
]
)Claudeは、クライアントサイドのツール使用機能を使用して、アクションを実行し、情報を動的に取得することができます。まず、プロンプトが使用すべき外部ツールやAPIをリストアップします。
この例では、見積もりを計算するための1つのツールから始めます。
モデル名、ツール定義、スタブ実装をconfig.pyに追加します:
import time
MODEL = "claude-opus-5"
TOOLS = [
{
"name": "get_quote",
"description": "Calculate the insurance quote based on user input. Returned value is per month premium.",
"input_schema": {
"type": "object",
"properties": {
"make": {"type": "string", "description": "The make of the vehicle."},
"model": {"type": "string", "description": "The model of the vehicle."},
"year": {
"type": "integer",
"description": "The year the vehicle was manufactured.",
},
"mileage": {
"type": "integer",
"description": "The mileage on the vehicle.",
},
"driver_age": {
"type": "integer",
"description": "The age of the primary driver.",
},
},
"required": ["make", "model", "year", "mileage", "driver_age"],
},
}
]
def get_quote(make, model, year, mileage, driver_age):
"""Returns the premium per month in USD"""
# HTTPエンドポイントやデータベースを呼び出して見積もりを取得できます。
# ここでは、1秒の遅延をシミュレートし、固定の見積もり100を返します。
time.sleep(1)
return 100テスト用の本番環境にデプロイして評価を実行しなければ、プロンプトがどの程度うまく機能するかを知ることは困難です。プロンプト、Anthropic SDK、ユーザーインターフェース用のStreamlitを使用して、小さなアプリケーションを構築します。
chatbot.pyというファイル(または使用する言語の同等のモジュール)で、Anthropic SDKとのやり取りをカプセル化するChatBotクラスを設定します。
このクラスには2つの主要なメソッドが必要です:APIを呼び出してメッセージを生成するメソッドと、受信した各ユーザー入力を処理するメソッドです。
mainメソッドを使用して、このコードをStreamlitでデプロイしてテストします。このmain()関数は、Streamlitベースのチャットインターフェースを設定します。StreamlitはPythonフレームワークであるため、このウォークスルーの部分はPythonのみで示されています。上記のChatBotクラスは、任意の言語に移植できる部分です。
これをapp.pyというファイルで行います
import streamlit as st
from chatbot import ChatBot
from config import TASK_SPECIFIC_INSTRUCTIONS
def main():
st.title("Chat with Eva, Acme Insurance Company's Assistant🤖")
if "messages" not in st.session_state:
st.session_state.messages = [
{"role": "user", "content": TASK_SPECIFIC_INSTRUCTIONS},
{"role": "assistant", "content": "Understood"},
]
chatbot = ChatBot(st.session_state)
# 最初の2つをスキップしてユーザーとアシスタントのメッセージを表示
for message in st.session_state.messages[2:]:
# ツール使用ブロックを無視
if isinstance(message["content"], str):
with st.chat_message(message["role"]):
st.markdown(message["content"])
if user_msg := st.chat_input("Type your message here..."):
st.chat_message("user").markdown(user_msg)
with st.chat_message("assistant"):
with st.spinner("Eva is thinking..."):
response_placeholder = st.empty()
full_response = chatbot.process_user_input(user_msg)
response_placeholder.markdown(full_response)
if __name__ == "__main__":
main()次のコマンドでプログラムを実行します:
streamlit run app.pyプロンプティングは、本番環境で使用できるようにするために、テストと最適化が必要になることがよくあります。ソリューションの準備状況を判断するには、定量的手法と定性的手法を組み合わせた体系的なプロセスを使用してチャットボットのパフォーマンスを評価します。定義した成功基準に基づいて強力な経験的評価を作成することで、プロンプトを最適化できます。
複雑なシナリオでは、標準的なプロンプトエンジニアリング手法やガードレール実装戦略を超えて、パフォーマンスを向上させるための追加の戦略を検討すると役立つ場合があります。一般的なシナリオをいくつか紹介します:
大量の静的および動的コンテキストを扱う場合、すべての情報をプロンプトに含めると、コストの増加、応答時間の低下、コンテキストウィンドウの制限への到達につながる可能性があります。このシナリオでは、「Retrieval Augmented Generation」(検索拡張生成)、すなわちRAGの手法を実装することで、パフォーマンスと効率を向上させることができます。
Voyageなどの埋め込みモデルを使用して情報をベクトル表現に変換することで、よりスケーラブルで応答性の高いシステムを作成できます。このアプローチにより、すべてのプロンプトに可能なすべてのコンテキストを含めるのではなく、現在のクエリに基づいて関連情報を動的に取得できます。
サポートユースケースにRAGを実装することで、広範なコンテキスト要件を持つシステムにおいて、精度の向上、応答時間の短縮、APIコストの削減が実証されています。実例についてはRAGレシピを参照してください。
口座残高やポリシーの詳細など、リアルタイムの情報を必要とするクエリを扱う場合、埋め込みベースのRAGアプローチでは不十分です。代わりに、ツール使用により、チャットボットが正確でリアルタイムな応答を提供する能力を強化できます。例えば、ツール使用を使用して、顧客情報の検索、注文詳細の取得、顧客に代わっての注文のキャンセルを行うことができます。
ツール使用:カスタマーサービスエージェントレシピで概説されているこのアプローチにより、ライブデータをClaudeの応答に統合し、よりパーソナライズされた効率的な顧客体験を提供できます。
チャットボットをデプロイする際、特にカスタマーサービスのシナリオでは、誤用、範囲外のクエリ、不適切な応答に関連するリスクを防ぐことが重要です。Claudeはこのようなシナリオに対して本質的に耐性がありますが、チャットボットのガードレールを強化するための追加の手順を以下に示します:
長くなる可能性のある応答を扱う場合、ストリーミングを実装することでユーザーのエンゲージメントと満足度を向上させることができます。このシナリオでは、ユーザーは応答全体が生成されるのを待つのではなく、段階的に回答を受け取ります。
ストリーミングの実装方法は次のとおりです:
場合によっては、ストリーミングにより、段階的な表示が長い処理時間の影響を軽減するため、ベースレイテンシが高いより高度なモデルの使用が可能になります。
チャットボットの複雑さが増すにつれて、アプリケーションアーキテクチャもそれに合わせて進化させることができます。アーキテクチャにさらなるレイヤーを追加する前に、以下の(網羅的ではない)オプションを検討してください:
チャットボットが非常に多様なタスクを処理する場合は、最初の顧客クエリをルーティングするために別の意図分類器を追加することを検討するとよいでしょう。既存のアプリケーションの場合、これには、顧客のクエリを分類器を通じて、専門化された会話(独自のツールセットとシステムプロンプトを持つ)にルーティングする決定木を作成することが含まれます。なお、この方法ではClaudeへの追加の呼び出しが必要となり、レイテンシが増加する可能性があります。
これらの例はStreamlit環境内で呼び出し可能なPython関数に焦点を当ててきましたが、リアルタイムサポートチャットボットにClaudeをデプロイするにはAPIサービスが必要です。
これにアプローチする方法は次のとおりです:
APIラッパーを作成する:分類関数の周りにシンプルなAPIラッパーを開発します。例えば、Flask APIやFast APIを使用してコードをHTTPサービスにラップできます。HTTPサービスはユーザー入力を受け取り、アシスタントの応答全体を返すことができます。したがって、サービスには次の特性を持たせることができます:
Webインターフェースを構築する:Claudeを活用したエージェントとやり取りするための、ユーザーフレンドリーなWeb UIを実装します。
ClaudeにAPIへのアクセスを与えて、顧客に代わってアクションを実行できるようにします。
定義した成功基準に対してサポートエージェントを測定するための評価を構築します。
応答をストリーミングして、顧客が生成中の回答を確認できるようにします。
より良いタスクパフォーマンスのために、システムプロンプトと例を改良します。
Was this page helpful?
会話管理
見積もり生成
# chatbot.py では、上記で作成した config.py からこれらをインポートします:
# from config import IDENTITY, TOOLS, MODEL, get_quote
from anthropic import Anthropic
from dotenv import load_dotenv
load_dotenv()
class ChatBot:
def __init__(self, session_state):
self.anthropic = Anthropic()
self.session_state = session_state
def generate_message(
self,
messages,
max_tokens,
):
try:
response = self.anthropic.messages.create(
model=MODEL,
system=IDENTITY,
max_tokens=max_tokens,
messages=messages,
tools=TOOLS,
)
return response
except Exception as e:
return {"error": str(e)}
def process_user_input(self, user_input):
self.session_state.messages.append({"role": "user", "content": user_input})
response_message = self.generate_message(
messages=self.session_state.messages,
max_tokens=2048,
)
if "error" in response_message:
return f"An error occurred: {response_message['error']}"
if response_message.content[-1].type == "tool_use":
tool_use = response_message.content[-1]
func_name = tool_use.name
func_params = tool_use.input
tool_use_id = tool_use.id
result = self.handle_tool_use(func_name, func_params)
self.session_state.messages.append(
{"role": "assistant", "content": response_message.content}
)
self.session_state.messages.append(
{
"role": "user",
"content": [
{
"type": "tool_result",
"tool_use_id": tool_use_id,
"content": f"{result}",
}
],
}
)
follow_up_response = self.generate_message(
messages=self.session_state.messages,
max_tokens=2048,
)
if "error" in follow_up_response:
return f"An error occurred: {follow_up_response['error']}"
response_text = next(
(block.text for block in follow_up_response.content if block.type == "text"),
None,
)
if response_text is None:
raise Exception("An error occurred: Unexpected response type")
self.session_state.messages.append(
{"role": "assistant", "content": response_text}
)
return response_text
text_block = next(
(block for block in response_message.content if block.type == "text"), None
)
if text_block is not None:
response_text = text_block.text
self.session_state.messages.append(
{"role": "assistant", "content": response_text}
)
return response_text
raise Exception("An error occurred: Unexpected response type")
def handle_tool_use(self, func_name, func_params):
if func_name == "get_quote":
premium = get_quote(**func_params)
return f"Quote generated: ${premium:.2f} per month"
raise Exception("An unexpected tool was used")