Anthropic Claude 메시지 API - Amazon Bedrock

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

Anthropic Claude 메시지 API

이 섹션에서는를 사용하기 위한 추론 파라미터 및 코드 예제를 제공합니다.Anthropic Claude 메시지 API.

Anthropic Claude 메시지 API 개요

메시지를 사용하여 채팅 봇 또는 가상 어시스턴트 애플리케이션을 API 생성할 수 있습니다. 는 사용자와 간의 대화 교환을 API 관리합니다.Anthropic Claude 모델(보조).

작은 정보

이 주제에서는를 사용하는 방법을 보여줍니다.Anthropic Claude 기본 추론 작업(InvokeModel 또는 InvokeModelWithResponseStream)이 API 포함된 메시지. 그러나를 사용하는 것이 좋습니다.Converse API 애플리케이션에서 메시지를 구현합니다. .Converse API는 메시지를 지원하는 모든 모델에서 작동하는 통합된 파라미터 세트를 제공합니다. 자세한 내용은 와 대화 수행 Converse API 작업 단원을 참조하십시오.

Anthropic 는 Claude 모델을 교육하여 교대 사용자 및 보조 대화형 교대로 작동하도록 합니다. 새 메시지를 만들 때 메시지 파라미터로 이전 대화 턴을 지정합니다. 그러면 모델이 대화에서 다음번 메시지를 생성합니다.

각 입력 메시지는 역할 및 콘텐츠가 있는 객체여야 합니다. 단일 사용자 역할 메시지를 지정하거나 여러 사용자 및 어시스턴트 메시지를 포함할 수 있습니다. 첫 번째 메시지는 항상 사용자 역할을 사용해야 합니다.

의 응답을 미리 채우는 기술을 사용하는 경우 Claude (최종 어시스턴트 역할을 사용하여 Claude의 응답 시작 부분에 메시지 작성) Claude 는 중단한 위치에서 픽업하여 응답합니다. 이 기술을 사용하면 Claude 는 여전히 어시스턴트 역할과 함께 응답을 반환합니다.

최종 메시지에서 어시스턴트 역할을 사용하는 경우, 응답 콘텐츠는 해당 메시지의 콘텐츠에서 즉시 이어집니다. 이를 사용하여 모델 응답의 일부를 제한할 수 있습니다.

단일 사용자 메시지가 포함된 예제:

[{"role": "user", "content": "Hello, Claude"}]

여러 대화 턴이 있는 예제:

[ {"role": "user", "content": "Hello there."}, {"role": "assistant", "content": "Hi, I'm Claude. How can I help you?"}, {"role": "user", "content": "Can you explain LLMs in plain English?"}, ]

Claude에서 부분적으로 채워진 응답의 예제:

[ {"role": "user", "content": "Please describe yourself using only JSON"}, {"role": "assistant", "content": "Here is my JSON description:\n{"}, ]

각 입력 메시지 콘텐츠는 단일 문자열 또는 콘텐츠 블록 배열일 수 있으며, 여기서 각 블록에는 특정한 유형이 있습니다. 문자열을 사용하는 것은 "text" 유형의 콘텐츠 블록 한 개 배열에 대한 간편 구문입니다. 다음 입력 메시지는 동일합니다.

{"role": "user", "content": "Hello, Claude"}
{"role": "user", "content": [{"type": "text", "text": "Hello, Claude"}]}

에 대한 프롬프트 생성에 대한 자세한 내용은 Anthropic Claude 모델,의 프롬프트 소개를 참조하세요. Anthropic Claude . 메시지 로 마이그레이션하려는 기존 텍스트 완료 프롬프트가 있는 경우 텍스트 완료에서 마이그레이션을 API참조하세요. https://docs.anthropic.com/claude/reference/migrating-from-text-completions-to-messages

시스템 프롬프트

요청에 시스템 프롬프트를 포함할 수도 있습니다. 시스템 프롬프트를 사용하면에 컨텍스트 및 지침을 제공할 수 있습니다.Anthropic Claude특정 목표 또는 역할 지정과 같은 . 다음 예제와 같이 system 필드에 시스템 프롬프트를 지정합니다.

"system": "You are Claude, an AI assistant created by Anthropic to be helpful, harmless, and honest. Your goal is to provide informative and substantive responses to queries while avoiding potential harms."

자세한 내용은의 시스템 프롬프트를 참조하세요.Anthropic .

멀티모달 프롬프트

멀티모달 프롬프트는 여러 양식(이미지 및 텍스트)를 단일 프롬프트에 결합합니다. content 입력 필드에 양식을 지정합니다. 다음 예제는에 질문하는 방법을 보여줍니다.Anthropic Claude 제공된 이미지의 내용을 설명합니다. 예제 코드는 멀티모달 코드 예제 항목을 참조하세요.

{ "anthropic_version": "bedrock-2023-05-31", "max_tokens": 1024, "messages": [ { "role": "user", "content": [ { "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": "iVBORw..." } }, { "type": "text", "text": "What's in these images?" } ] } ] }
참고

content 필드에 적용되는 제한은 다음과 같습니다.

  • 최대 20개의 이미지를 포함시킬 수 있습니다. 각 이미지의 크기, 높이, 너비는 각각 3.75MB, 8,000px, 8,000px 이하여야 합니다.

  • 최대 5개 문서를 포함시킬 수 있습니다. 각 문서의 크기는 4.5MB 이하여야 합니다.

  • roleuser인 경우에만 이미지와 문서를 포함시킬 수 있습니다.

요청에 포함하는 각 이미지는 토큰 사용량에 포함됩니다. 자세한 내용은의 이미지 비용을 참조하세요.Anthropic .

도구 사용(함수 직접 호출)

With Anthropic Claude 3개 모델, 모델이 메시지에 응답하는 데 사용할 수 있는 도구를 지정할 수 있습니다. 예를 들어, 라디오 방송국에서 가장 인기 있는 노래를 가져오는 도구를 지정할 수 있습니다. 사용자가 에서 가장 인기 있는 노래는 무엇입니까WZPZ?라는 메시지를 전달하면 모델은 지정한 도구가 질문에 답하는 데 도움이 될 수 있다고 판단합니다. 응답에서 모델은 사용자에게 해당 도구를 실행해 달라고 요청합니다. 사용자가 도구를 실행하고 도구 결과를 모델에 전달하면 원래 메시지에 대한 응답이 생성됩니다. 자세한 내용은의 도구 사용(함수 호출)을 참조하세요.Anthropic Claude .

작은 정보

를 사용하는 것이 좋습니다.Converse API 도구 사용을 애플리케이션에 통합하는 데 사용됩니다. 자세한 내용은 도구를 사용하여 Amazon Bedrock 모델 응답 완성 단원을 참조하십시오.

tools 필드에서 모델이 사용할 수 있게 하려는 도구를 지정합니다. 다음 예제는 라디오 방송국에서 가장 인기 있는 노래를 가져오는 도구입니다.

[ { "name": "top_song", "description": "Get the most popular song played on a radio station.", "input_schema": { "type": "object", "properties": { "sign": { "type": "string", "description": "The call sign for the radio station for which you want the most popular song. Example calls signs are WZPZ and WKRP." } }, "required": [ "sign" ] } } ]

모델에 메시지에 대한 응답을 생성하는 도구가 필요한 경우, 요청된 도구에 대한 정보와 도구에 대한 입력이 메시지 content 필드에 반환됩니다. 모델은 tool_use에 대한 응답의 중지 이유도 설정합니다.

{ "id": "msg_bdrk_01USsY5m3XRUF4FCppHP8KBx", "type": "message", "role": "assistant", "model": "claude-3-sonnet-20240229", "stop_sequence": null, "usage": { "input_tokens": 375, "output_tokens": 36 }, "content": [ { "type": "tool_use", "id": "toolu_bdrk_01SnXQc6YVWD8Dom5jz7KhHy", "name": "top_song", "input": { "sign": "WZPZ" } } ], "stop_reason": "tool_use" }

코드에서 사용자가 도구를 대신하여 도구를 직접 호출합니다. 그런 다음 사용자 메시지의 도구 결과(tool_result)를 모델에 전달합니다.

{ "role": "user", "content": [ { "type": "tool_result", "tool_use_id": "toolu_bdrk_01SnXQc6YVWD8Dom5jz7KhHy", "content": "Elemental Hotel" } ] }

응답에서 모델은 도구 결과를 사용하여 원본 메시지에 대한 응답을 생성합니다.

{ "id": "msg_bdrk_012AaqvTiKuUSc6WadhUkDLP", "type": "message", "role": "assistant", "model": "claude-3-sonnet-20240229", "content": [ { "type": "text", "text": "According to the tool, the most popular song played on radio station WZPZ is \"Elemental Hotel\"." } ], "stop_reason": "end_turn" }

컴퓨터 사용(베타)

컴퓨터 사용은 새로운 Anthropic Claude 모델 기능(베타)은 Claude 3.5 Sonnet v2에서만 사용할 수 있습니다. 컴퓨터를 사용하면 Claude 는 기본 GUI 작업을 통해 작업을 자동화하는 데 도움이 됩니다.

주의

컴퓨터 사용 기능은 AWS 서비스 약관에 정의된 대로 '베타 서비스'로 사용할 수 있습니다. 여기에는 와의 계약 AWS 및 AWS 서비스 약관과 해당 모델가 적용됩니다EULA. 컴퓨터 사용은 표준 API 기능 또는 채팅 인터페이스와 구별되는 고유한 위험을 API 초래한다는 점에 유의하세요. 컴퓨터 사용을 사용하여 인터넷과 상호 작용API할 때 이러한 위험이 높아집니다. 위험을 최소화하려면 다음과 같은 예방 조치를 취하는 것이 좋습니다.

  • 전용 가상 머신 또는 컨테이너에서 컴퓨터 사용 기능을 최소한의 권한으로 작동하여 직접 시스템 공격 또는 사고를 방지합니다.

  • 정보 도용을 방지하려면 민감한 계정 또는 데이터에 대한 컴퓨터 사용 API 액세스 권한을 부여하지 마십시오.

  • 컴퓨터는 API의 인터넷 액세스를 필수 도메인으로 제한하여 악성 콘텐츠에 대한 노출을 줄입니다.

  • 적절한 감독이 이루어질 수 있도록, 민감한 작업(예: 의미 있는 실제 결과로 이어질 수 있는 의사 결정)과 긍정적인 동의가 필요한 모든 작업(예: 쿠키 허용, 금융 거래 실행 또는 서비스 약관 동의)에 대해 사람을 루프에 관여시킵니다.

활성화하는 모든 콘텐츠 Claude 를 보거나 액세스하면 잠재적으로 지침을 재정의하거나 Claude 실수를 하거나 의도하지 않은 작업을 수행하기 위해. 격리와 같은 적절한 예방 조치 취하기 Claude 신속한 주입과 관련된 위험을 방지하는 등 민감한 표면에서가 필수적임. 자체 제품에서 컴퓨터 사용 기능을 설정하는 데 필요한 권한을 활성화하거나 요청하기 전에 최종 사용자에게 관련 위험을 알리고 필요한 경우 동의를 얻으시기 바랍니다.

컴퓨터 사용은 사용자가 사용할 수 있도록 사전 정의된 여러 컴퓨터 사용 도구(computer_20241022, bash_20241022text_editor_20241022)를 API 제공합니다. 그런 다음 “지난 회의의 메모가 포함된 이메일을 Ben에게 전송해 줘” 같은 프롬프트와 스크린샷(필요한 경우)과 같은 프롬프트를 작성할 수 있습니다. 응답에는 JSON 형식의 tool_use 작업 목록이 포함됩니다(예: scroll_down, left_button_press, screenshot). 코드는 컴퓨터 작업을 실행하고 Claude 스크린샷에 출력 표시(요청 시).

도구 파라미터가 다형성 도구 유형을 허용하도록 업데이트되었습니다. 이를 구분하기 위해 새 tool.type 속성이 추가됩니다. type은 선택 사항이며, 생략된 경우 도구는 사용자 지정 도구로 간주됩니다(이전에 유일하게 지원된 도구 유형). 또한 해당 열거형 값이 computer-use-2024-10-22인 새 파라미터 anthropic_beta가 추가되었습니다. 이 파라미터와 열거형으로 이루어진 요청만 새 컴퓨터 사용 도구를 사용할 수 있습니다. 이렇게 지정할 수 있습니다. "anthropic_beta": ["computer-use-2024-10-22"]

자세한 내용은의 컴퓨터 사용(베타)을 참조하세요.Anthropic .

다음은 Firefox 아이콘이 있는 바탕 화면의 스크린샷이 요청에 포함되어 있다고 가정한 응답 예제입니다.

{ "id": "msg_123", "type": "message", "role": "assistant", "model": "anthropic.claude-3-5-sonnet-20241022-v2:0", "content": [ { "type": "text", "text": "I see the Firefox icon. Let me click on it and then navigate to a weather website." }, { "type": "tool_use", "id": "toolu_123", "name": "computer", "input": { "action": "mouse_move", "coordinate": [ 708, 736 ] } }, { "type": "tool_use", "id": "toolu_234", "name": "computer", "input": { "action": "left_click" } } ], "stop_reason": "tool_use", "stop_sequence": null, "usage": { "input_tokens": 3391, "output_tokens": 132 } }

지원되는 모델

다음과 API 함께 메시지를 사용할 수 있습니다.Anthropic Claude 모델.

  • Anthropic Claude Instant v1.2

  • Anthropic Claude 2 v2

  • Anthropic Claude 2 v2.1

  • Anthropic Claude 3 Sonnet

  • Anthropic Claude 3.5 Sonnet

  • Anthropic Claude 3.5 Sonnet v2

  • Anthropic Claude 3 Haiku

  • Anthropic Claude 3 Opus

요청 및 응답

요청 본문은 InvokeModel 또는에 대한 요청 body 필드에 전달됩니다InvokeModelWithResponseStream. 요청에서 전송할 수 있는 페이로드의 최대 크기는 20MB입니다.

자세한 내용은 https://docs.anthropic.com/claude/reference/messages_post를 참조하세요.

Request

Anthropic Claude 에는 메시지 추론 호출에 대한 다음과 같은 추론 파라미터가 있습니다.

{ "anthropic_version": "bedrock-2023-05-31", "anthropic_beta": ["computer-use-2024-10-22"] "max_tokens": int, "system": string, "messages": [ { "role": string, "content": [ { "type": "image", "source": { "type": "base64", "media_type": "image/jpeg", "data": "content image bytes" } }, { "type": "text", "text": "content text" } ] } ], "temperature": float, "top_p": float, "top_k": int, "tools": [ { "type": "custom", "name": string, "description": string, "input_schema": json }, { "type": "computer_20241022", "name": "computer", "display_height_px": int, "display_width_px": int, "display_number": 0 int }, { "type": "bash_20241022", "name": "bash" }, { "type": "text_editor_20241022", "name": "str_replace_editor" } ], "tool_choice": { "type" : string, "name" : string, }, "stop_sequences": [string] }

다음은 필수 파라미터입니다.

  • anthropic_version – (필수) Anthropic 버전입니다. 값은 bedrock-2023-05-31여야 합니다.

  • anthropic_beta – (컴퓨터를 사용하는 경우 필수API) 사용할 anthropic 베타입니다. 컴퓨터를 사용하려면 API값이 여야 합니다computer-use-2024-10-22.

  • max_tokens – (필수) 중지하기 전에 생성할 최대 토큰 수입니다.

    참고로 Anthropic Claude 모델은 값에 도달하기 전에 토큰 생성을 중지할 수 있습니다max_tokens. Different Anthropic Claude 모델마다이 파라미터의 최대값이 다릅니다. 자세한 내용은 모델 비교를 참조하세요.

  • messages - (필수) 입력 메시지입니다.

    • role - 대화 턴의 역할입니다. 유효 값은 userassistant입니다.

    • content - (필수) 대화 턴의 콘텐츠입니다.

      • type – (필수) 콘텐츠의 유형입니다. 유효 값은 imagetext입니다.

        image를 지정하는 경우, 이미지 소스도 다음 형식으로 지정해야 합니다.

        source - (필수) 대화 턴의 콘텐츠입니다.

        • type – (필수) 이미지의 인코딩 유형입니다. base64를 지정할 수 있습니다.

        • media_type – (필수) 이미지의 유형입니다. 다음 이미지 형식을 지정할 수 있습니다.

          • image/jpeg

          • image/png

          • image/webp

          • image/gif

        • data - (필수) 이미지의 base64 인코딩 이미지 바이트입니다. 최대 이미지 크기는 3.75MB입니다. 이미지의 최대 높이와 너비는 8,000픽셀입니다.

        text 속성을 지정한 경우 text에서도 프롬프트를 지정해야 합니다.

다음 파라미터는 선택 사항입니다.

  • system – (선택 사항) 요청에 대한 시스템 프롬프트입니다.

    시스템 프롬프트는에 컨텍스트와 지침을 제공하는 방법입니다.Anthropic Claude특정 목표 또는 역할 지정과 같은 . 자세한 내용은 의 시스템 프롬프트를 참조하세요.Anthropic .

    참고

    에서 시스템 프롬프트를 사용할 수 있습니다.Anthropic Claude 버전 2.1 이상.

  • stop_sequences – (선택 사항) 모델 생성을 중지하는 사용자 지정 텍스트 시퀀스입니다.Anthropic Claude 모델은 일반적으로 턴을 자연스럽게 완료하면 중지되며,이 경우 stop_reason 응답 필드의 값은 입니다end_turn. 사용자 지정 텍스트 문자열이 표시될 때 모델 생성을 중지하려면 stop_sequences 파라미터를 사용할 수 있습니다. 모델이 사용자 지정 텍스트 문자열 중 하나를 발견하면 stop_reason 응답 필드의 값은 stop_sequence이고 stop_sequence의 값에는 일치하는 중지 시퀀스가 포함됩니다.

    항목의 최대 수는 8,191입니다.

  • temperature – (선택 사항) 응답에 주입되는 무작위성의 양입니다.

    기본값 최소 Maximum

    1

    0

    1

  • top_p – (선택 사항) Nucleus 샘플링을 사용합니다.

    핵 샘플링에서 Anthropic Claude 는 각 후속 토큰의 모든 옵션에 대한 누적 분포를 확률 내림차순으로 계산하고에서 지정한 특정 확률에 도달하면 잘라냅니다top_p. temperature 또는 top_p를 변경해야 하지만, 둘 다 변경해서는 안 됩니다.

    기본값 최소 Maximum

    0.999

    0

    1

  • top_k – (선택 사항) 각 후속 토큰에 대해 상위 K개 옵션에서만 샘플을 추출합니다.

    top_k를 사용하여 롱 테일 낮은 확률 응답을 제거합니다.

    기본값 최소 Maximum

    기본 설정은 비활성화입니다.

    0

    500

  • tools - (선택 사항) 모델이 사용할 수 있는 도구의 정의입니다.

    참고

    가 필요합니다.Anthropic Claude 3 모델.

    요청에 tools를 포함하면 모델이 모델의 해당 도구 사용을 나타내는 tool_use 콘텐츠 블록을 반환할 수 있습니다. 그런 다음 모델에서 생성된 도구 입력을 사용하여 이러한 도구를 실행한 다음, 선택적으로 tool_result 콘텐츠 블록을 사용하여 결과를 모델로 반환할 수 있습니다.

    다음 도구 유형을 전달할 수 있습니다.

    사용자 지정(Custom)

    사용자 지정 도구의 정의입니다.

    • (선택 사항) type - 도구의 유형입니다. 정의된 경우 custom 값을 사용합니다.

    • name - 도구의 이름입니다.

    • description - (선택 사항이지만 강력히 권장됨) 도구에 대한 설명입니다.

    • input_schema JSON – 도구의 스키마입니다.

    컴퓨터

    컴퓨터에서 사용하는 컴퓨터 도구의 정의는를 사용합니다API.

    • type – 값은 computer_20241022여야 합니다.

    • name - 값은 computer여야 합니다.

    • (필수) display_height_px - 모델이 제어하는 디스플레이의 높이를 픽셀 단위로 표시합니다.

      기본값 최소 Maximum

      없음

      1

      최대 없음

    • (필수) display_width_px - 모델이 제어하는 디스플레이의 너비를 픽셀 단위로 표시합니다.

      기본값 최소 Maximum

      없음

      1

      최대 없음

    • (선택 사항) display_number – 제어할 디스플레이 번호입니다(X11 환경만 해당). 지정된 경우 도구 정의에 디스플레이 번호가 제공됩니다.

      기본값 최소 Maximum

      없음

      0

      N

    bash

    컴퓨터에서 사용하는 bash 도구의 정의는를 사용합니다API.

    • (선택 사항) type - 값은 bash_20241022여야 합니다.

    • name - 값은 bash 도구여야 합니다.

    text editor

    컴퓨터에서 사용하는 텍스트 편집기 도구의 정의는를 사용합니다API.

    • (선택 사항) type - 값은 text_editor_20241022여야 합니다.

    • name - 값은 str_replace_editor 도구여야 합니다.

  • tool_choice – (선택 사항) 모델이 제공된 도구를 사용하는 방법을 지정합니다. 모델은 특정 도구 또는 사용 가능한 도구를 사용하거나 자체적으로 결정할 수 있습니다.

    참고

    가 필요합니다.Anthropic Claude 3 모델.

    • type - 도구 선택 유형입니다. 가능한 값은 any(사용 가능한 도구 사용), auto(모델이 결정), tool(지정된 도구 사용)입니다.

    • name – (선택 사항) 사용할 도구의 이름입니다. type 필드에 tool을 지정하는 경우 필수입니다.

Response

.Anthropic Claude 모델은 메시지 추론 호출에 대해 다음 필드를 반환합니다.

{ "id": string, "model": string, "type" : "message", "role" : "assistant", "content": [ { "type": string, "text": string } ], "stop_reason": string, "stop_sequence": string, "tool_use" : { "type": string, "id" : string, "input" : json }, "usage": { "input_tokens": integer, "output_tokens": integer } }
  • id - 응답의 고유 식별자입니다. ID의 형식과 길이는 시간이 지남에 따라 변경될 수 있습니다.

  • 모델 -의 ID Anthropic Claude 요청을 수행한 모델입니다.

  • stop_reason – 이유 Anthropic Claude 가 응답 생성을 중지했습니다.

    • end_turn - 모델이 자연 중단점에 도달했습니다.

    • max_tokens - 생성된 텍스트가 max_tokens 입력 필드 값을 초과하거나 모델이 지원하는 최대 토큰 수를 초과했습니다.

    • stop_sequence – 모델이 stop_sequences 입력 필드에 지정한 중지 시퀀스 중 하나를 생성했습니다.

  • stop_sequence – 생성을 종료한 중지 시퀀스입니다.

  • type - 응답 유형입니다. 이 값은 항상 message입니다.

  • role - 생성된 메시지의 대화 역할입니다. 이 값은 항상 assistant입니다.

  • content - 모델에서 생성된 콘텐츠입니다. 배열로 반환됩니다. texttool_use 같은 두 가지 유형의 연결이 있습니다.

    • text - 텍스트 응답입니다.

      • type - 이 값은 text입니다. 콘텐츠 유형입니다.

      • text – 콘텐츠의 텍스트입니다.

    • tool_use - 모델에 도구 사용을 요청합니다.

      • type – 이 값은 text입니다. 콘텐츠의 유형입니다.

      • id - 모델이 사용을 요청하는 도구의 ID입니다.

      • input - 도구에 전달할 입력 파라미터입니다.

  • usage - 요청에서 제공한 토큰 수와 응답에서 생성된 모델의 토큰 수에 대한 컨테이너입니다.

    • input_tokens - 요청의 입력 토큰 수입니다.

    • output_tokens - 모델에서 응답으로 생성한 토큰 수입니다.

    • stop_sequence – 모델이 stop_sequences 입력 필드에 지정한 중지 시퀀스 중 하나를 생성했습니다.

코드 예제

다음 코드 예제에서는 메시지를 사용하는 방법을 보여줍니다API.

메시지 코드 예제

이 예제에서는 미리 채워진 어시스턴트 메시지와 함께 단일 턴 사용자 메시지와 사용자 턴을에 보내는 방법을 보여줍니다.Anthropic Claude 3 Sonnet 모델.

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to generate a message with Anthropic Claude (on demand). """ import boto3 import json import logging from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def generate_message(bedrock_runtime, model_id, system_prompt, messages, max_tokens): body=json.dumps( { "anthropic_version": "bedrock-2023-05-31", "max_tokens": max_tokens, "system": system_prompt, "messages": messages } ) response = bedrock_runtime.invoke_model(body=body, modelId=model_id) response_body = json.loads(response.get('body').read()) return response_body def main(): """ Entrypoint for Anthropic Claude message example. """ try: bedrock_runtime = boto3.client(service_name='bedrock-runtime') model_id = 'anthropic.claude-3-sonnet-20240229-v1:0' system_prompt = "Please respond only with emoji." max_tokens = 1000 # Prompt with user turn only. user_message = {"role": "user", "content": "Hello World"} messages = [user_message] response = generate_message (bedrock_runtime, model_id, system_prompt, messages, max_tokens) print("User turn only.") print(json.dumps(response, indent=4)) # Prompt with both user turn and prefilled assistant response. #Anthropic Claude continues by using the prefilled assistant text. assistant_message = {"role": "assistant", "content": "<emoji>"} messages = [user_message, assistant_message] response = generate_message(bedrock_runtime, model_id,system_prompt, messages, max_tokens) print("User turn and prefilled assistant response.") print(json.dumps(response, indent=4)) except ClientError as err: message=err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) if __name__ == "__main__": main()

멀티모달 코드 예제

다음 예제에서는 멀티모달 메시지의 이미지와 프롬프트 텍스트를에 전달하는 방법을 보여줍니다.Anthropic Claude 3 Sonnet 모델.

를 사용한 멀티모달 프롬프트 InvokeModel

다음 예제에서는에 멀티모달 프롬프트를 보내는 방법을 보여줍니다.Anthropic Claude 3 Sonnet 를 사용합니다InvokeModel.

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to run a multimodal prompt with Anthropic Claude (on demand) and InvokeModel. """ import json import logging import base64 import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def run_multi_modal_prompt(bedrock_runtime, model_id, messages, max_tokens): """ Invokes a model with a multimodal prompt. Args: bedrock_runtime: The Amazon Bedrock boto3 client. model_id (str): The model ID to use. messages (JSON) : The messages to send to the model. max_tokens (int) : The maximum number of tokens to generate. Returns: None. """ body = json.dumps( { "anthropic_version": "bedrock-2023-05-31", "max_tokens": max_tokens, "messages": messages } ) response = bedrock_runtime.invoke_model( body=body, modelId=model_id) response_body = json.loads(response.get('body').read()) return response_body def main(): """ Entrypoint for Anthropic Claude multimodal prompt example. """ try: bedrock_runtime = boto3.client(service_name='bedrock-runtime') model_id = 'anthropic.claude-3-sonnet-20240229-v1:0' max_tokens = 1000 input_image = "/path/to/image" input_text = "What's in this image?" # Read reference image from file and encode as base64 strings. with open(input_image, "rb") as image_file: content_image = base64.b64encode(image_file.read()).decode('utf8') message = {"role": "user", "content": [ {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": content_image}}, {"type": "text", "text": input_text} ]} messages = [message] response = run_multi_modal_prompt( bedrock_runtime, model_id, messages, max_tokens) print(json.dumps(response, indent=4)) except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) if __name__ == "__main__": main()

를 사용하여 멀티모달 프롬프트 스트리밍 InvokeModelWithResponseStream

다음 예제에서는 로 전송된 멀티모달 프롬프트에서 응답을 스트리밍하는 방법을 보여줍니다.Anthropic Claude 3 Sonnet 를 사용합니다InvokeModelWithResponseStream.

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Shows how to stream the response from Anthropic Claude Sonnet (on demand) for a multimodal request. """ import json import base64 import logging import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) def stream_multi_modal_prompt(bedrock_runtime, model_id, input_text, image, max_tokens): """ Streams the response from a multimodal prompt. Args: bedrock_runtime: The Amazon Bedrock boto3 client. model_id (str): The model ID to use. input_text (str) : The prompt text image (str) : The path to an image that you want in the prompt. max_tokens (int) : The maximum number of tokens to generate. Returns: None. """ with open(image, "rb") as image_file: encoded_string = base64.b64encode(image_file.read()) body = json.dumps({ "anthropic_version": "bedrock-2023-05-31", "max_tokens": max_tokens, "messages": [ { "role": "user", "content": [ {"type": "text", "text": input_text}, {"type": "image", "source": {"type": "base64", "media_type": "image/jpeg", "data": encoded_string.decode('utf-8')}} ] } ] }) response = bedrock_runtime.invoke_model_with_response_stream( body=body, modelId=model_id) for event in response.get("body"): chunk = json.loads(event["chunk"]["bytes"]) if chunk['type'] == 'message_delta': print(f"\nStop reason: {chunk['delta']['stop_reason']}") print(f"Stop sequence: {chunk['delta']['stop_sequence']}") print(f"Output tokens: {chunk['usage']['output_tokens']}") if chunk['type'] == 'content_block_delta': if chunk['delta']['type'] == 'text_delta': print(chunk['delta']['text'], end="") def main(): """ Entrypoint for Anthropic Claude Sonnet multimodal prompt example. """ model_id = "anthropic.claude-3-sonnet-20240229-v1:0" input_text = "What can you tell me about this image?" image = "/path/to/image" max_tokens = 100 try: bedrock_runtime = boto3.client('bedrock-runtime') stream_multi_modal_prompt( bedrock_runtime, model_id, input_text, image, max_tokens) except ClientError as err: message = err.response["Error"]["Message"] logger.error("A client error occurred: %s", message) print("A client error occured: " + format(message)) if __name__ == "__main__": main()