| タイトル | 著者 | 日付 |
|---|---|---|
Golangを使用したGenaiアプリケーションの開発 | ハイムトラン | 25/03/2024 |
私たちが生産でよく見られるのは、Go、Java、.Netで書かれた言語のさまざまなものですが、現在PythonとJavaScriptにGenai(生成の人工知能)アプリの構築に関する学習資料の大部分があります。このワークショップでは、Langchain、Streamlit、Reactなどのフレームワークを使用せずに、いくつかの基本的な例を実装することで、Amazon Bedrockを開始する方法を示しています。
例は次のとおりです。
基本的な概念を本当に理解し、マスターするのに役立つ新しいフレームワークを学ぶことなく、基本的なプログラミングの概念のみを使用してこれらの機能を実装します。
建築

このサンプルアプリケーションは、すでにセットアップされていることを前提としています
たとえば、 /bedrock/constants.goの変数を置き換えてください
const BEDROCK_REGION = ""
const AOSS_REGION = ""
const KNOWLEDGE_BASE_REGION = ""
const KNOWLEDGE_BASE_ID = ""
const KNOWLEDGE_BASE_MODEL_ID = ""
const KNOWLEDGE_BASE_NUMBER_OF_RESULT = 6
const AOSS_ENDPOINT = ""
const AOSS_NOTE_APP_INDEX_NAME = "" プロジェクト構造
| - - static
| - - aoss - index. html
| -- aoss - query. html
| -- claude - haiku. html
| -- image. html
| -- retrieve. html
| -- retrieve - generate. html
| -- bedrock
| -- aoss. go
| -- bedrock. go
| -- constants. go
| -- knowledge - based. go
| -- main. go
| -- go . mod
| -- go . summain.go HTTPサーバーとルートリクエストをハンドラーに実装します。 Bedrock.goとAoss.goは、Amazon BedrockとAmazon Opensearch ServerLess(AOSS)を呼び出す機能です。静的フォルダーには、JavaScriptを使用した単純なフロントエンドが含まれています。
重要
AOSSを使用するには、OpenSearchコレクションを作成し、Constants.goでURLエンドポイントを提供する必要があります。さらに、実行時間環境のAOSSでデータアクセスをセットアップする必要があります(EC2プロファイル、ECS TAKSロール、ラムダロール、.ETC)
この公式文書に従ってGolangをインストールし、次のようにApplicationNを実行します
重要
GOバージョン1.21.5をインストールしてください
cd developing - genai - applications - with - golang
go run main . go 最初に、Amazon Bedrock Claude3 API形式に従っていくつかのデータ構造を作成することは良いことです
type Content struct {
Type string `json:"type"`
Text string `json:"text"`
}
type Message struct {
Role string `json:"role"`
Content [] Content `json:"content"`
}
type Body struct {
MaxTokensToSample int `json:"max_tokens"`
Temperature float64 `json:"temperature,omitempty"`
AnthropicVersion string `json:"anthropic_version"`
Messages [] Message `json:"messages"`
}
// list of messages
messages := [] Message {{
Role : "user" ,
Content : [] Content {{ Type : "text" , Text : promt }},
}}
// form request body
payload := Body {
MaxTokensToSample : 2048 ,
Temperature : 0.9 ,
AnthropicVersion : "bedrock-2023-05-31" ,
Messages : messages ,
}次に、ペイロードをバイトに変換し、Bedrockクライアントを呼び出します
payload := Body {
MaxTokensToSample : 2048 ,
Temperature : 0.9 ,
AnthropicVersion : "bedrock-2023-05-31" ,
Messages : messages ,
}
// marshal payload to bytes
payloadBytes , err := json . Marshal ( payload )
if err != nil {
fmt . Println ( err )
return
}
// create request to bedrock
output , error := BedrockClient . InvokeModelWithResponseStream (
context . Background (),
& bedrockruntime. InvokeModelWithResponseStreamInput {
Body : payloadBytes ,
ModelId : aws . String ( "anthropic.claude-3-haiku-20240307-v1:0" ),
ContentType : aws . String ( "application/json" ),
Accept : aws . String ( "application/json" ),
},
)
if error != nil {
fmt . Println ( error )
return
}最後に、ストリーミングレプソンを解析し、テキストにデコードします。 HTTPサーバーにデプロイするときは、クライアントへの各応答をストリーミングするためにコードを少し変更する必要があります。たとえば、ここに
output , error := BedrockClient . InvokeModelWithResponseStream (
context . Background (),
& bedrockruntime. InvokeModelWithResponseStreamInput {
Body : payloadBytes ,
ModelId : aws . String ( "anthropic.claude-3-haiku-20240307-v1:0" ),
ContentType : aws . String ( "application/json" ),
Accept : aws . String ( "application/json" ),
},
)
if error != nil {
fmt . Println ( error )
return
}
// parse response stream
for event := range output . GetStream (). Events () {
switch v := event .( type ) {
case * types. ResponseStreamMemberChunk :
//fmt.Println("payload", string(v.Value.Bytes))
var resp ResponseClaude3
err := json . NewDecoder ( bytes . NewReader ( v . Value . Bytes )). Decode ( & resp )
if err != nil {
fmt . Println ( err )
}
fmt . Println ( resp . Delta . Text )
case * types. UnknownUnionMember :
fmt . Println ( "unknown tag:" , v . Tag )
default :
fmt . Println ( "union is nil or unknown type" )
}
}このワークショップは、アプリケーションを展開するための詳細な段階的な段階ではありません。代わりに、全体的なアーキテクチャと展開オプションを提供します。 Amazon ECSにアプリケーションを展開するのはStraightFowardです。

dockerfile
# syntax = docker / dockerfile : 1
# Build the application from source
FROM golang : 1.21 . 5 AS build - stage
WORKDIR / app
COPY go . mod go . sum . /
RUN go mod download
COPY * . go . /
COPY bedrock . / bedrock
RUN CGO_ENABLED = 0 GOOS = linux go build - o / genaiapp
# Run the tests in the container
FROM build - stage AS run - test - stage
# Deploy the application binary into a lean image
FROM gcr . io / distroless / base - debian11 AS build - release - stage
WORKDIR /
COPY -- from = build - stage / genai - go - app / genaiapp
COPY static . / static
EXPOSE 3000
USER nonroot : nonroot
ENTRYPOINT [ "/genaiapp" ]ECSタスクロール
タスクの役割には許可が必要です
これがタスクの役割に添付されているIAMポリシーのサンプルです
{
"Version" : " 2012-10-17 " ,
"Statement" : [
{
"Action" : [
" bedrock:InvokeModel " ,
" bedrock:InvokeModelWithResponseStream " ,
" bedrock:InvokeAgent "
],
"Resource" : [
" arn:aws:bedrock:<REGION>::foundation-model/anthropic.claude-3-haiku-20240307-v1:0 " ,
" arn:aws:bedrock:<REGION>::foundation-model/amazon.titan-embed-text-v1 "
],
"Effect" : " Allow "
},
{
"Action" : [ " s3:GetObject " , " s3:PutObject " ],
"Resource" : [
" arn:aws:s3:::<BUCKET_NAME> " ,
" arn:aws:s3:::<BUCKET_NAME>/* "
],
"Effect" : " Allow "
},
{
"Action" : " aoss:APIAccessAll " ,
"Resource" : [
" arn:aws:aoss:<REGION>:<ACCOUNT_ID>:collection/<COLLECTION_ID> "
],
"Effect" : " Allow "
}
]
}AOSSデータアクセスポリシー
タスクロールがAOSSコレクションにアクセスできるようにするには、コレクションのアクセスポリシーを更新する必要があります。