이 가이드를 따르려면 다음이 필요합니다:
ANTHROPIC_API_KEY 환경 변수로 설정)필요한 패키지를 설치하세요:
pip install anthropic streamlit python-dotenv다음은 고객 지원 프로세스의 일부를 자동화하기 위해 Claude와 같은 LLM을 사용해야 하는 주요 지표입니다:
다른 LLM 대신 Claude를 선택할 때 고려할 사항:
고객이 Claude와 어떻게, 언제 상호작용할 것으로 예상하는지 정의하기 위해 이상적인 고객 상호작용의 개요를 작성하세요. 이 개요는 솔루션의 기술 요구 사항을 결정하는 데 도움이 됩니다.
다음은 자동차 보험 고객 지원을 위한 채팅 상호작용 예시입니다:
고객 지원 채팅은 질문 답변부터 정보 검색, 요청에 대한 조치 수행까지 여러 다양한 작업이 단일 고객 상호작용으로 묶인 집합입니다. 구축을 시작하기 전에, 이상적인 고객 상호작용을 Claude가 수행할 수 있기를 원하는 모든 작업으로 분해하세요. 이렇게 하면 모든 작업에 대해 Claude를 프롬프트하고 평가할 수 있으며, 테스트 케이스를 작성할 때 고려해야 할 상호작용의 범위를 잘 파악할 수 있습니다.
다음은 예시 보험 상호작용과 관련된 주요 작업입니다:
인사 및 일반 안내
제품 정보
대화 관리
견적 생성
지원 팀과 협력하여 측정 가능한 벤치마크와 목표를 포함한 성공 기준을 정의하고 상세한 평가를 작성하세요.
다음은 Claude가 정의된 작업을 얼마나 성공적으로 수행하는지 평가하는 데 사용할 수 있는 기준과 벤치마크입니다:
다음은 지원 업무에 Claude를 도입했을 때의 비즈니스 영향을 평가하는 데 사용할 수 있는 기준과 벤치마크입니다:
모델 선택은 비용, 정확도, 응답 시간 간의 트레이드오프에 따라 달라집니다.
고객 지원 채팅의 경우, Claude Opus 4.8은 지능, "latency"(지연 시간), 비용의 균형을 맞추는 데 적합합니다. 그러나 RAG, 도구 사용 또는 긴 컨텍스트 프롬프트를 포함한 여러 프롬프트로 구성된 대화 흐름이 있는 경우, latency를 최적화하기 위해 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에게 역할 부여하기를 참조하세요.복잡한 프롬프트는 하위 섹션으로 나누어 한 번에 한 부분씩 작성하는 것이 가장 좋습니다. 각 작업에 대해, 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.
"""이제 이 모든 섹션을 하나의 문자열로 결합하여 프롬프트로 사용하세요.
TASK_SPECIFIC_INSTRUCTIONS = " ".join(
[
STATIC_GREETINGS_AND_GENERAL,
STATIC_CAR_INSURANCE,
STATIC_ELECTRIC_CAR_INSURANCE,
EXAMPLES,
ADDITIONAL_GUARDRAILS,
]
)Claude는 클라이언트 측 도구 사용 기능을 통해 동적으로 작업을 수행하고 정보를 검색할 수 있습니다. 먼저 프롬프트가 사용해야 하는 외부 도구나 API를 나열하세요.
이 예시에서는 견적을 계산하는 도구 하나로 시작합니다.
모델 이름, 도구 정의 및 스텁 구현을 config.py에 추가하세요:
import time
MODEL = "claude-opus-4-8"
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 클래스를 설정하는 것부터 시작하세요.
이 클래스에는 generate_message와 process_user_input이라는 두 가지 주요 메서드가 있어야 합니다.
from anthropic import Anthropic
from config import IDENTITY, TOOLS, MODEL, get_quote
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 = follow_up_response.content[0].text
self.session_state.messages.append(
{"role": "assistant", "content": response_text}
)
return response_text
elif response_message.content[0].type == "text":
response_text = response_message.content[0].text
self.session_state.messages.append(
{"role": "assistant", "content": response_text}
)
return response_text
else:
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")main 메서드를 사용하여 Streamlit으로 이 코드를 배포하고 테스트하세요. 이 main() 함수는 Streamlit 기반 채팅 인터페이스를 설정합니다.
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)
# 처음 두 개를 건너뛰고 사용자 및 어시스턴트 메시지 표시
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는 본질적으로 이러한 시나리오에 대한 복원력이 있지만, 챗봇 가드레일을 강화하기 위한 추가 단계는 다음과 같습니다:
잠재적으로 긴 응답을 처리할 때 스트리밍을 구현하면 사용자 참여도와 만족도를 개선할 수 있습니다. 이 시나리오에서 사용자는 전체 응답이 생성될 때까지 기다리는 대신 답변을 점진적으로 받습니다.
스트리밍을 구현하는 방법은 다음과 같습니다:
경우에 따라 스트리밍은 점진적 표시가 더 긴 처리 시간의 영향을 완화하므로 기본 latency가 더 높은 고급 모델을 사용할 수 있게 합니다.
챗봇의 복잡성이 증가함에 따라 애플리케이션 아키텍처도 이에 맞춰 발전할 수 있습니다. 아키텍처에 추가 레이어를 추가하기 전에 다음과 같은 덜 복잡한 옵션을 고려하세요:
챗봇이 매우 다양한 작업을 처리하는 경우, 초기 고객 쿼리를 라우팅하기 위해 별도의 의도 분류기를 추가하는 것을 고려할 수 있습니다. 기존 애플리케이션의 경우, 이는 고객 쿼리를 분류기를 통해 라우팅한 다음 전문화된 대화(각각 고유한 도구 세트와 시스템 프롬프트를 가진)로 연결하는 의사 결정 트리를 만드는 것을 포함합니다. 참고로, 이 방법은 Claude에 대한 추가 호출이 필요하므로 latency가 증가할 수 있습니다.
이 예시들은 Streamlit 환경 내에서 호출 가능한 Python 함수에 초점을 맞추었지만, 실시간 지원 챗봇을 위해 Claude를 배포하려면 API 서비스가 필요합니다.
다음과 같이 접근할 수 있습니다:
API 래퍼 만들기: 분류 함수를 중심으로 간단한 API 래퍼를 개발하세요. 예를 들어, Flask API 또는 Fast API를 사용하여 코드를 HTTP 서비스로 래핑할 수 있습니다. HTTP 서비스는 사용자 입력을 받아 Assistant 응답을 전체적으로 반환할 수 있습니다. 따라서 서비스는 다음과 같은 특성을 가질 수 있습니다:
웹 인터페이스 구축: Claude 기반 에이전트와 상호작용하기 위한 사용자 친화적인 웹 UI를 구현하세요.
Claude가 고객을 대신하여 작업을 수행할 수 있도록 API에 대한 액세스를 제공하세요.
정의한 성공 기준에 따라 지원 에이전트를 측정하기 위한 평가를 구축하세요.
고객이 생성되는 답변을 실시간으로 볼 수 있도록 응답을 스트리밍하세요.
더 나은 작업 성능을 위해 시스템 프롬프트와 예시를 개선하세요.
Was this page helpful?