검색
검색
공개 노트 검색
회원가입로그인

[Claude] 클로드 api 사용하기 - 메타 프롬프트 생성 코렙 따라하기

reasonofmoon_a_boy_encountering_a_talking_cat_on_his_way_to_sch_95113382-0c03-4e2c-8869-7e5c0e2993e0

트위터에 올라온 공개된 코렙에서 실행하는 클로드 파이썬 코드 예제가 있어서 소개드립니다.

제가 작년 12월에 발간한 메타프롬프트(meta_prompt)와 같은 제목의 내용이라 관심있게 읽어보았습니다.

이 노트북은 Claude를 활용하여 다양한 작업에 대한 프롬프트 템플릿을 생성하는 예제입니다.

코드를 한 줄씩 자세히 살펴보면서 여러분도 쉽게 따라할 수 있도록 안내해 드리겠습니다.

<원문출처>

https://twitter.com/KeyFactoryNYC/status/1767622576233148768

<구글 코렙>

Google Colaboratory

먼저 이 노트북을 사용하려면 다음 단계를 따르세요:

  1. Google Drive에서 "File -> Save a copy in Drive"를 클릭하여 이 노트북의 사본을 만드세요.

제목 없음 (13)

  1. "Put your API key here!"라고 적힌 곳에 여러분의 Anthropic API 키를 따옴표 안에 입력하세요.

제목 없음 (14)

제목 없음 (15)

제목 없음 (16)

  1. "Replace with your task!"라고 적힌 곳에 여러분이 수행하고 싶은 작업을 입력하세요.

그런 다음 "Runtime -> Run all"을 클릭하면 노트북 하단에 여러분의 프롬프트가 표시될 것입니다. Google Colab에서 개별 셀을 실행하려면 해당 셀을 클릭한 다음 Shift + Enter 키를 동시에 누르면 됩니다.

제목 없음 (17)

이제 코드를 자세히 살펴보겠습니다:

!pip install anthropic

첫 번째 줄은 Anthropic 라이브러리를 설치합니다. 이는 Claude와 상호 작용하는 데 필요합니다.

[Claude] 클로드 api 사용하기 - 메타 프롬프트 생성 코렙 따라하기 image 7

(shift + enter 를 누르면 해당 셀이 실행이 된다)

import anthropic, re
ANTHROPIC_API_KEY = "Put your API key here!" # Put your API key here!
MODEL_NAME = "claude-3-opus-20240229"
CLIENT = anthropic.Anthropic(api_key=ANTHROPIC_API_KEY)

("Put your API key here!" > 큰 따옴표 안에 복사한 api 키를 붙여 넣는다)

그 다음 anthropicre 라이브러리를 가져옵니다. 그런 다음 여러분의 Anthropic API 키, 사용할 Claude 모델의 이름, API 키를 사용하여 생성한 Anthropic 클라이언트를 정의합니다.

metaprompt = '''Today you will be writing instructions...

이 부분은 매우 긴 문자열 형태의 "메타프롬프트"를 정의합니다. 이 프롬프트는 Claude에게 다양한 작업을 수행하는 방법에 대한 지침을 작성하도록 지시합니다. 이는 Claude가 사용자의 작업에 맞는 맞춤형 프롬프트 템플릿을 생성하는 데 도움이 됩니다.

TASK = "Draft an email responding to a customer complaint" # Replace with your task!
VARIABLES = []

여기서는 사용자가 수행하려는 작업을 TASK 변수에 정의하고, Claude가 프롬프트 템플릿에서 사용할 변수들의 목록을 VARIABLES에 정의합니다(선택사항).

variable_string = ""
for variable in VARIABLES:
    variable_string += "n{" + variable.upper() + "}"
print(variable_string)  

이 코드는 VARIABLES에 정의된 변수들을 적절한 형식으로 변환하여 문자열로 만듭니다.

prompt = metaprompt.replace("{{TASK}}", TASK)
assistant_partial = "<Inputs>"
if variable_string:
    assistant_partial += variable_string + "n</Inputs><Instructions Structure>"

message = CLIENT.messages.create(
    model=MODEL_NAME,
    max_tokens=4096,
    messages=[
        {
            "role": "user",
            "content":  prompt
        },
        {
            "role": "assistant",
            "content": assistant_partial
        }
    ],
    temperature=0
).content[0].text

이 부분에서는 TASK를 메타프롬프트에 삽입하고, 앞서 정의한 변수들과 함께 Claude에게 전송할 메시지를 생성합니다. 그런 다음 Anthropic 클라이언트를 사용하여 실제로 Claude에게 메시지를 전송합니다.

def extract_between_tags(tag: str, string: str, strip: bool = False) -> list[str]:
    ext_list = re.findall(f"<{tag}>(.+?)</{tag}>", string, re.DOTALL)
    if strip:
        ext_list = [e.strip() for e in ext_list]
    return ext_list

def remove_empty_tags(text):
    return re.sub(r'<(w+)></1>$', '', text)

def extract_prompt(metaprompt_response):
    between_tags = extract_between_tags("Instructions", metaprompt_response)[0]
    return remove_empty_tags(remove_empty_tags(between_tags).strip()).strip()

def extract_variables(prompt):
    pattern = r'{([^}]+)}'
    variables = re.findall(pattern, prompt)
    return set(variables)

위의 함수들은 Claude의 응답에서 프롬프트 템플릿과 변수를 추출하는 데 사용됩니다.

extracted_prompt_template = extract_prompt(message)
variables = extract_variables(message)

print("Variables:nn" + str(variables))
print("n************************n") 
print("Prompt:")
pretty_print(extracted_prompt_template)

이 코드는 추출된 프롬프트 템플릿과 변수를 출력합니다.

variable_values = {}
for variable in variables:
    print("Enter value for variable:", variable)
    variable_values[variable] = input()
    
prompt_with_variables = extracted_prompt_template
for variable in variable_values:
    prompt_with_variables = prompt_with_variables.replace("{" + variable + "}", variable_values[variable])

message = CLIENT.messages.create(
    model=MODEL_NAME,
    max_tokens=4096,
    messages=[
        {
            "role": "user", 
            "content":  prompt_with_variables
        },
    ],
).content[0].text

print("Claude's output on your prompt:nn")
pretty_print(message)

마지막으로, 이 코드는 사용자로부터 각 변수의 값을 입력받아 프롬프트 템플릿에 삽입합니다. 그런 다음 완성된 프롬프트를 Claude에게 다시 전송하고 Claude의 최종 출력을 인쇄합니다.

[Claude] 클로드 api 사용하기 - 메타 프롬프트 생성 코렙 따라하기 image 8

(네모 칸에 차례대로 고객의 이름(reasonofmoon), 불만의 이유(reason for complaint), 이메일주소를 넣고 실행한다)


클로드의 응답 (영어)

Dear soundfury37,

Thank you for contacting us about the delayed delivery of your recent book purchase.

I sincerely apologize for the inconvenience and frustration this has caused you.

We strive to process and ship orders quickly, and in this case we clearly fell short of our standard.

I have looked into the status of your order, and I can confirm that the delivery has been unacceptably delayed on our end.

This is not the level of service we aim to provide to valued customers like yourself.

Please know that I am personally working with our shipping department to get your book packaged and sent out to you as our top priority.

To make things right, I would like to offer you a 20% refund on your order.

You can expect to see this refund posted to your original payment method within the next 1-2 business days.

I realize this doesn't undo the frustration of the last few weeks, but I hope this gesture demonstrates our commitment to your satisfaction.

Your book is now set to arrive by the end of this week at the latest.

You will receive a shipping confirmation email with a tracking number once the package is on its way.

Please let me know if you have any other questions or concerns in the meantime.

I can be reached directly at jsanchez@bookbarn.com or 1-800-555-1234.

Thank you again for making us aware of this issue.

I appreciate your patience and understanding as we work to get your order fulfilled as quickly as possible.

We value your business and look forward to serving you better in the future.

Best regards,

Jesse Sanchez

Customer Service Manager

클로드의 응답(한국어)

soundfury37님께,

최근 구매하신 책의 배송 지연에 대해 연락 주셔서 감사합니다.

이로 인해 불편과 실망을 드려 진심으로 사과드립니다.

저희는 주문을 신속하게 처리하고 배송하기 위해 노력하지만, 이번 경우에는 저희 기준에 미치지 못했습니다.

주문 상태를 확인해 보았고, 배송이 용납할 수 없을 정도로 지연되었음을 확인할 수 있었습니다.

이는 저희가 soundfury37님과 같은 소중한 고객님께 제공하고자 하는 서비스 수준이 아닙니다.

제가 직접 배송 부서와 협력하여 책을 포장하고 최우선 순위로 발송할 수 있도록 하겠습니다.

사태를 바로잡기 위해 주문 금액의 20% 환불을 제안드리고 싶습니다.

이 환불은 1-2 영업일 이내에 원래 결제 수단으로 게시될 것입니다.

저는 이것이 지난 몇 주 동안의 실망감을 되돌릴 순 없지만, 이 제스처가 고객님의 만족을 위한 저희의 노력을 보여줄 수 있기를 바랍니다.

늦어도 이번 주 말까지는 책이 도착할 예정입니다.

패키지가 발송되면 추적 번호가 포함된 배송 확인 이메일을 받으실 것입니다.

그 동안 다른 질문이나 우려 사항이 있으시면 언제든지 알려주십시오.

jsanchez@bookbarn.com 또는 1-800-555-1234로 직접 연락하실 수 있습니다.

이 문제를 알려주셔서 다시 한번 감사드립니다.

주문 처리를 최대한 빨리 진행할 수 있도록 노력하는 동안 고객님의 인내와 이해에 감사드립니다.

저희는 고객님의 비즈니스를 소중히 여기며 앞으로 더 나은 서비스를 제공하기를 기대합니다.

감사합니다.

제시 산체스 드림

고객 서비스 매니저

공유하기
카카오로 공유하기
페이스북 공유하기
트위터로 공유하기
url 복사하기
조회수 : 1472
heart
T
페이지 기반 대답
AI Chat