首頁 後端開發 Golang 使用 Mistral AI 透過 Go 建立生成式 AI 應用程式

使用 Mistral AI 透過 Go 建立生成式 AI 應用程式

Aug 09, 2024 pm 01:13 PM

了解如何透過適用於 Go 的 AWS 開發工具包在 Amazon Bedrock 上使用 Mistral AI

Mistral AI 提供的模型在效能、成本等方面具有不同的特徵:

  • Mistral 7B - Mistral AI 發布的第一個密集模型,非常適合實驗、客製化和快速迭代。
  • Mixtral 8x7B - 專家模型的稀疏混合。
  • Mistral Large - 非常適合需要大量推理能力或高度專業化的複雜任務(合成文字產生、程式碼產生、RAG 或代理)。

讓我們逐步了解如何透過 Go 在 Amazon Bedrock 上使用這些 Mistral AI 模型,並在此過程中更好地了解其提示令牌。

米斯特拉爾人工智慧入門

讓我們從使用 Mistral 7B 的簡單範例開始。

請參閱本部落格文章中的**開始之前*部分,以完成運行範例的先決條件。這包括安裝 Go、配置 Amazon Bedrock 存取以及提供必要的 IAM 權限。 *

完整程式碼可以參考這裡

運行範例:

1

2

3

4

git clone https://github.com/abhirockzz/mistral-bedrock-go

cd mistral-bedrock-go

 

go run basic/main.go

登入後複製

根據您的情況,回應可能(或可能不會)略有不同:

1

2

3

4

5

6

request payload:

 {"prompt":"\u003cs\u003e[INST] Hello, what's your name? [/INST]"}

response payload:

 {"outputs":[{"text":" Hello! I don't have a name. I'm just an artificial intelligence designed to help answer questions and provide information. How can I assist you today?","stop_reason":"stop"}]}

response string:

  Hello! I don't have a name. I'm just an artificial intelligence designed to help answer questions and provide information. How can I assist you today?

登入後複製

完整程式碼可以參考這裡。

我們先建立 JSON 有效負載 - 它被建模為結構 (MistralRequest)。另外,請注意模型 ID milistral.mistral-7b-instruct-v0:2

1

2

3

4

5

6

7

8

9

10

const modelID7BInstruct = "mistral.mistral-7b-instruct-v0:2"

const promptFormat = "<s>[INST] %s [/INST]"

 

func main() {

    msg := "Hello, what's your name?"

 

    payload := MistralRequest{

        Prompt: fmt.Sprintf(promptFormat, msg),

    }

//...

登入後複製

Mistral 有特定的提示格式,其中:

  • 字串的開頭標記
  • 使用者角色的文字位於 [INST]...[/INST] 標記內
  • 外面的文字是輔助角色

在上面的輸出日誌中,查看 如何顯示令牌被解釋

這是具有所需屬性的 MistralRequest 結構:

1

2

3

4

5

6

7

8

type MistralRequest struct {

    Prompt        string   `json:"prompt"`

    MaxTokens     int      `json:"max_tokens,omitempty"`

    Temperature   float64  `json:"temperature,omitempty"`

    TopP          float64  `json:"top_p,omitempty"`

    TopK          int      `json:"top_k,omitempty"`

    StopSequences []string `json:"stop,omitempty"`

}

登入後複製

InvokeModel 用來呼叫模型。 JSON 回應將轉換為結構體 (MistralResponse),並從中提取文字回應。

1

2

3

4

5

6

7

8

9

10

11

output, err := brc.InvokeModel(context.Background(), &bedrockruntime.InvokeModelInput{

    Body:        payloadBytes,

    ModelId:     aws.String(modelID7BInstruct),

    ContentType: aws.String("application/json"),

})

 

var resp MistralResponse

 

err = json.Unmarshal(output.Body, &resp)

 

fmt.Println("response string:\n", resp.Outputs[0].Text)

登入後複製

聊天範例

繼續進行簡單的對話互動。這就是 Mistral 所說的多回合提示,我們將加上 這是字串結尾標記。

運行範例:

1

go run chat/main.go

登入後複製

這是我的互動:

Use Mistral AI to build generative AI applications with Go

完整程式碼可以參考這裡

出於本範例的目的,程式碼本身過於簡化。但是,重要的部分是如何使用標記來格式化提示。請注意,我們在此範例中使用 Mixtral 8X7B (mistral.mixtral-8x7b-instruct-v0:1)。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

const userMessageFormat = "[INST] %s [/INST]"

const modelID8X7BInstruct = "mistral.mixtral-8x7b-instruct-v0:1"

const bos = "<s>"

const eos = "</s>"

 

var verbose *bool

 

func main() {

    reader := bufio.NewReader(os.Stdin)

 

    first := true

    var msg string

 

    for {

        fmt.Print("\nEnter your message: ")

 

        input, _ := reader.ReadString('\n')

        input = strings.TrimSpace(input)

 

        if first {

            msg = bos + fmt.Sprintf(userMessageFormat, input)

        } else {

            msg = msg + fmt.Sprintf(userMessageFormat, input)

        }

 

        payload := MistralRequest{

            Prompt: msg,

        }

 

        response, err := send(payload)

 

        fmt.Println("[Assistant]:", response)

 

        msg = msg + response + eos + " "

 

        first = false

    }

}

登入後複製

字串開始 (bos) 標記僅在對話開始時需要一次,而eos (字串結束) 標記結束單一對話交換(用戶和助理)。

與串流媒體聊天

如果您讀過我以前的博客,我總是喜歡包含一個「串流媒體」範例,因為:

  1. 從客戶端應用程式的角度來看,它提供了更好的體驗
  2. 忽略 InvokeModelWithResponseStream 函數(InvokeModel 的非同步對應函數)是一個常見錯誤
  3. 部分模型負載反應可能很有趣(有時也很棘手)

完整程式碼可以參考這裡

讓我們試試這個。此範例使用 Mistral Large - 只需將模型 ID 變更為 milistral.mistral-large-2402-v1:0。運行範例:

1

go run chat-streaming/main.go

登入後複製

注意 InvokeModelWithResponseStream(而不是 Invoke)的用法:

1

2

3

4

5

6

output, err := brc.InvokeModelWithResponseStream(context.Background(), &bedrockruntime.InvokeModelWithResponseStreamInput{

    Body:        payloadBytes,

    ModelId:     aws.String(modelID7BInstruct),

    ContentType: aws.String("application/json"),

})

//...

登入後複製

為了處理它的輸出,我們使用:

1

2

3

4

5

//...

resp, err := processStreamingOutput(output, func(ctx context.Context, part []byte) error {

    fmt.Print(string(part))

    return nil

})

登入後複製

以下是 processStreamingOutput 函數的一些內容 - 您可以在此處查看程式碼。需要理解的重要一點是如何將部分響應收集在一起以產生最終輸出 (MistralResponse)。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

func processStreamingOutput(output *bedrockruntime.InvokeModelWithResponseStreamOutput, handler StreamingOutputHandler) (MistralResponse, error) {

 

    var combinedResult string

 

    resp := MistralResponse{}

    op := Outputs{}

 

    for event := range output.GetStream().Events() {

        switch v := event.(type) {

        case *types.ResponseStreamMemberChunk:

 

            var pr MistralResponse

 

            err := json.NewDecoder(bytes.NewReader(v.Value.Bytes)).Decode(&pr)

            if err != nil {

                return resp, err

            }

 

            handler(context.Background(), []byte(pr.Outputs[0].Text))

 

            combinedResult += pr.Outputs[0].Text

            op.StopReason = pr.Outputs[0].StopReason

    //...

    }

 

    op.Text = combinedResult

    resp.Outputs = []Outputs{op}

 

    return resp, nil

}

登入後複製

結論

請記住 - 使用大型語言模型(如 Mistral、Meta Llama、Claude 等)建立 AI/ML 應用程式並不意味著您必須使用 Python。 Amazon Bedrock 等託管平台使用多種程式語言(包括 Go!)的靈活 API 提供對這些強大模型的存取。由於 AWS 開發工具包支持,您可以使用您選擇的程式語言與 Amazon Bedrock 集成,並建立生成式 AI 解決方案。

您可以透過瀏覽 Mistral 官方文件以及 Amazon Bedrock 使用者指南來了解更多資訊。快樂建造!

以上是使用 Mistral AI 透過 Go 建立生成式 AI 應用程式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱門文章標籤

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Go語言包導入:帶下劃線和不帶下劃線的區別是什麼? Go語言包導入:帶下劃線和不帶下劃線的區別是什麼? Mar 03, 2025 pm 05:17 PM

Go語言包導入:帶下劃線和不帶下劃線的區別是什麼?

Beego框架中NewFlash()函數如何實現頁面間短暫信息傳遞? Beego框架中NewFlash()函數如何實現頁面間短暫信息傳遞? Mar 03, 2025 pm 05:22 PM

Beego框架中NewFlash()函數如何實現頁面間短暫信息傳遞?

Go語言中如何將MySQL查詢結果List轉換為自定義結構體切片? Go語言中如何將MySQL查詢結果List轉換為自定義結構體切片? Mar 03, 2025 pm 05:18 PM

Go語言中如何將MySQL查詢結果List轉換為自定義結構體切片?

如何編寫模擬對象和存根以進行測試? 如何編寫模擬對象和存根以進行測試? Mar 10, 2025 pm 05:38 PM

如何編寫模擬對象和存根以進行測試?

如何定義GO中仿製藥的自定義類型約束? 如何定義GO中仿製藥的自定義類型約束? Mar 10, 2025 pm 03:20 PM

如何定義GO中仿製藥的自定義類型約束?

您如何在GO中編寫單元測試? 您如何在GO中編寫單元測試? Mar 21, 2025 pm 06:34 PM

您如何在GO中編寫單元測試?

Go語言如何便捷地寫入文件? Go語言如何便捷地寫入文件? Mar 03, 2025 pm 05:15 PM

Go語言如何便捷地寫入文件?

如何使用跟踪工具了解GO應用程序的執行流? 如何使用跟踪工具了解GO應用程序的執行流? Mar 10, 2025 pm 05:36 PM

如何使用跟踪工具了解GO應用程序的執行流?

See all articles