iT邦幫忙

2025 iThome 鐵人賽

DAY 3
0

前言

現今在使用 ai 應用生態最完整肯定是 python,所以我大部分的應用大概會用 python 完成,
如果有機會可以隨後考慮其他程式語言完成(有時間的話😅)

在我們開始前有些東西要設定一下

設定 aws SDK 和 Credential(題外)

aws SDK(這部分比較和主題無關不會可以看,會可以跳過)

我建議安裝 aws cli 進行設定好讓我們取得 credential 連結左就擺在這了

以 mac 為例 我們其實可以用 homebrew 安裝

brew install awscli

安裝完成後我們可以繼續了

使用指令

aws configure sso

接下來登入自己的 aws 帳號取得 admin_permission_set 的 credential
把個別的項目輸入

設定 aws 環境變數

一樣可以在 aws admin_permission_set 取得,並在自己的 terminal 設定環境變數

export AWS_ACCESS_KEY_ID=your-access-key
export AWS_SECRET_ACCESS_KEY=your-secret-key
export AWS_DEFAULT_REGION=us-east-1

python 開始

筆者使用 uv 作為我的 package Manager 也是可以用 pip 這部分看個人習慣

開始我的專案 在個人 project 目錄下輸入指令

uv init

專案結構

.
├── main.py
├── pyproject.toml
└── README.md

1 directory, 3 files

安裝 boto3

uv add boto3

當然如果習慣用 pip 的可以用

pip install boto3
pip install botocore

建立簡單文字生成應用

main.py

我們一開始的檔案長這樣


def main():
    print("Hello from project!")


if __name__ == "__main__":
    main()

我們要開始建立一個 class 生存文字應用 我們稱之為 BedrockTextGenerator


class BedrockTextGenerator:
  def __init__(self, region_name='ap-northeast-1')

def main():
    print("Hello from project!")


if __name__ == "__main__":
    main()

我們會用到的

import boto3
import json
from botocore.exceptions import ClientError

所以一開始我們寫 code 會長這樣

import boto3
import json
from botocore.exceptions import ClientError

class BedrockTextGenerator:
  def __init__(self, region_name='ap-northeast-1')
    """
    這裡是初始化的 Bedrock 用戶端
    """
    self.bedrock_runtime = boto3.client(region_name=region_name)


def main():
    print("Hello from testb!")


if __name__ == "__main__":
    main()

接著我們要用 claude 的 foundation model 生成文字 我們 method 就叫做 generate_text_claude

def generate_text_claude(self, prompt, max_tokens=1000):
    """
    使用Claude模型生成文字
    """
    try:
        # 構建請求體
        body = {
            "prompt": f"\n\nHuman: {prompt}\n\nAssistant:",
            "max_tokens_to_sample": max_tokens,
            "temperature": 0.7,
            "top_p": 0.9
        }
        
        # 發送請求到Bedrock
        response = self.bedrock_runtime.invoke_model(
            body=json.dumps(body),
            modelId='anthropic.claude-v2',  # Claude模型ID
            accept='application/json',
            contentType='application/json'
        )
        
        # 解析回應
        response_body = json.loads(response.get('body').read())
        generated_text = response_body.get('completion', '')
        
        return generated_text.strip()
        
    except ClientError as e:
        print(f"發生錯誤: {e}")
        return None

所以完成長這樣

import boto3
import json
from botocore.exceptions import ClientError

class BedrockTextGenerator:
  def __init__(self, region_name='ap-northeast-1')
    """
    這裡是初始化的 Bedrock 用戶端
    """
    self.bedrock_runtime = boto3.client(region_name=region_name)

  def generate_text_claude(self, prompt, max_tokens=1000):
        """
        使用Claude模型生成文字
        """
        try:
            # 構建請求體
            body = {
                "prompt": f"\n\nHuman: {prompt}\n\nAssistant:",
                "max_tokens_to_sample": max_tokens,
                "temperature": 0.7,
                "top_p": 0.9
            }
            
            # 發送請求到Bedrock
            response = self.bedrock_runtime.invoke_model(
                body=json.dumps(body),
                modelId='anthropic.claude-v2',  # Claude模型ID
                accept='application/json',
                contentType='application/json'
            )
            
            # 解析回應
            response_body = json.loads(response.get('body').read())
            generated_text = response_body.get('completion', '')
            
            return generated_text.strip()
            
        except ClientError as e:
            print(f"發生錯誤: {e}")
            return None


def main():
    print("Hello from testb!")


if __name__ == "__main__":
    main()

這樣我們的 class 就做完了

開始嘗試

def main():
    # 初始化生成器
    generator = BedrockTextGenerator()
    
    # 測試提示
    prompt = "幫我隨便寫啥,約200字"
    
    print("=== 使用Claude模型 ===")
    claude_result = generator.generate_text_claude(prompt)
    if claude_result:
        print(claude_result)

所以完整的程式碼如下

import boto3
import json
from botocore.exceptions import ClientError

class BedrockTextGenerator:
  def __init__(self, region_name='ap-northeast-1')
    """
    這裡是初始化的 Bedrock 用戶端
    """
    self.bedrock_runtime = boto3.client(region_name=region_name)

  def generate_text_claude(self, prompt, max_tokens=1000):
        """
        使用Claude模型生成文字
        """
        try:
            # 構建請求體
            body = {
                "prompt": f"\n\nHuman: {prompt}\n\nAssistant:",
                "max_tokens_to_sample": max_tokens,
                "temperature": 0.7,
                "top_p": 0.9
            }
            
            # 發送請求到Bedrock
            response = self.bedrock_runtime.invoke_model(
                body=json.dumps(body),
                modelId='anthropic.claude-v2',  # Claude模型ID
                accept='application/json',
                contentType='application/json'
            )
            
            # 解析回應
            response_body = json.loads(response.get('body').read())
            generated_text = response_body.get('completion', '')
            
            return generated_text.strip()
            
        except ClientError as e:
            print(f"發生錯誤: {e}")
            return None


def main():
    # 初始化生成器
    generator = BedrockTextGenerator()
    
    # 測試提示
    prompt = "幫我隨便寫啥,約200字"
    
    print("=== 使用Claude模型 ===")
    claude_result = generator.generate_text_claude(prompt)
    if claude_result:
        print(claude_result)

if __name__ == "__main__":
    main()

打完收工


上一篇
Amazon Bedrock基礎:Foundation Models簡介
系列文
從零開始的AWS AI之路:用Bedrock與SageMaker打造智慧應用的30天實戰3
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言