0

0

使用 Amazon Titan Text Premier 模型在 Go 中构建生成式 AI 应用程序

WBOY

WBOY

发布时间:2024-09-03 14:35:06

|

967人浏览过

|

来源于dev.to

转载

将 amazon titan text premier 模型与 langchaingo 包结合使用

在本博客中,我将引导您了解如何通过 langchaingo 在 go 应用程序中使用 amazon titan text premier 模型,langchaingo 是 langchain 的 go 端口(最初是为 python 和 js/ts 编写的)。

amazon titan text premier 是 amazon titan text 系列中的高级法学硕士。它适用于各种任务,包括 rag、代理、聊天、思想链、开放式文本生成、头脑风暴、总结、代码生成、表格创建、数据格式化、释义、重写、提取和问答。 titan text premier 还针对与 amazon bedrock 的代理和知识库集成进行了优化。

将 titan text premier 与 langchaingo 结合使用

让我们从一个例子开始。

请参阅本博文中的**开始之前*部分,以完成运行示例的先决条件。这包括安装 go、配置 amazon bedrock 访问以及提供必要的 iam 权限。*

完整代码可以参考这里。运行示例:

git clone https://github.com/abhirockzz/titan-premier-bedrock-go
cd titan-premier-bedrock-go

go run basic/main.go

针对“用 100 个单词或更少的内容解释 ai”提示,我得到了以下回复,但您的情况可能有所不同:

artificial intelligence (ai) is a branch of computer science that focuses on creating intelligent machines that can think, learn, and act like humans. it uses advanced algorithms and machine learning techniques to enable computers to recognize patterns, make decisions, and solve problems. ai has the potential to revolutionize various industries, including healthcare, finance, transportation, and entertainment, by automating tasks, improving efficiency, and providing personalized experiences. however, there are also concerns about the ethical implications and potential risks associated with ai, such as job displacement, privacy, and bias.

以下是代码的快速浏览:

我们首先实例化 bedrockruntime.client:

cfg, err := config.loaddefaultconfig(context.background(), config.withregion(region))
client = bedrockruntime.newfromconfig(cfg)

我们使用它来创建 langchaingo llm.model 实例 - 请注意,我们指定的 modelid 是 titan text premier 的 modelid,即 amazon.titan-text-premier-v1:0。

llm, err := bedrock.new(bedrock.withclient(client), bedrock.withmodel(modelid))

我们创建一个 llms.messagecontent,llm 调用由 llm.generatecontent 完成。请注意,您不必考虑 titan text premier 特定请求/响应有效负载 - 这是由 langchaingo 抽象的:

    msg := []llms.messagecontent{
        {
            role: llms.chatmessagetypehuman,
            parts: []llms.contentpart{
                llms.textpart("explain ai in 100 words or less."),
            },
        },
    }

    resp, err := llm.generatecontent(context.background(), msg, llms.withmaxtokens(maxtokencountlimitfortitantextpremier))

与您的文档聊天

这也是一个很常见的场景。 langchaingo 支持多种类型,包括文本、pdf、html(甚至 notion!)。

完整代码可以参考这里。要运行此示例:

go run doc-chat/main.go

该示例使用 amazon bedrock 用户指南中的此页面作为源文档 (html),但您可以随意使用任何其他来源:

export source_url=
go run doc-chat/main.go

系统应该提示您输入问题:

loaded content from https://docs.aws.amazon.com/bedrock/latest/userguide/model-ids.html

enter your message: 

我尝试了这些问题并得到了相当准确的答案:

1. tell me the names of the supported providers
2. tell me the model id for titan text premier
3. give me the list of amazon titan family of models
4. what is the titan text premier model id for a provisioned throughput customer?

使用 Amazon Titan Text Premier 模型在 Go 中构建生成式 AI 应用程序

顺便说一下,amazon bedrock 本身也提供了“与文档聊天”功能。

让我们快速浏览一下代码。我们首先从源 url 加载内容:

func getdocs(link string) []schema.document {
    //...
    resp, err := http.get(link)
    docs, err := documentloaders.newhtml(resp.body).load(context.background())
    return docs
}

然后,我们使用简单的 for 循环开始对话:

    //...
    for {
        fmt.print("\nenter your message: ")
        input, _ := reader.readstring('\n')
        input = strings.trimspace(input)

        answer, err := chains.call(
            context.background(),
            docchainwithcustomprompt(llm),
            map[string]any{
                "input_documents": docs,
                "question":        input,
            },
            chains.withmaxtokens(maxtokencountlimitfortitantextpremier))
        //...
    }

我们使用的链是使用自定义提示创建的(基于此指南) - 我们覆盖 langchaingo 中的默认行为:

func docchainwithcustomprompt(llm *bedrock_llm.llm) chains.chain {

    ragprompttemplate := prompts.newprompttemplate(
        prompttemplatestring,
        []string{"context", "question"},
    )

    qapromptselector := chains.conditionalpromptselector{
        defaultprompt: ragprompttemplate,
    }

    prompt := qapromptselector.getprompt(llm)

    llmchain := chains.newllmchain(llm, prompt)
    return chains.newstuffdocuments(llmchain)
}

现在来看最后一个例子 - 另一个流行的用例。

rag - 检索增强生成

我之前介绍过如何在 go 应用程序中使用 rag。这次我们将使用:

  • titan text premier 作为法学硕士,
  • titan embeddings g1 作为嵌入模型,
  • 使用 pgvector 扩展将 postgresql 作为向量存储(使用 docker 在本地运行)。

启动 docker 容器:

docker run --name pgvector --rm -it -p 5432:5432 -e postgres_user=postgres -e postgres_password=postgres ankane/pgvector

通过从不同的终端登录 postgresql(使用 psql)来激活 pgvector 扩展:

# enter postgres when prompted for password
psql -h localhost -u postgres -w

create extension if not exists vector;

完整代码可以参考这里。要运行此示例:

go run rag/main.go

该示例使用 amazon bedrock studio 页面作为源文档 (html),但您可以随意使用任何其他源:

export source_url=
go run rag/main.go

您应该看到输出,并提示输入您的问题。我尝试过这些:

what is bedrock studio?
how do i enable bedrock studio?

使用 Amazon Titan Text Premier 模型在 Go 中构建生成式 AI 应用程序

像往常一样,让我们​​看看发生了什么。数据加载的方式与以前类似,对话也同样如此(for 循环):

    for {
        fmt.print("\nenter your message: ")
        question, _ := reader.readstring('\n')
        question = strings.trimspace(question)

        result, err := chains.run(
            context.background(),
            retrievalqachainwithcustomprompt(llm, vectorstores.toretriever(store, numofresults)),
            question,
            chains.withmaxtokens(maxtokencountlimitfortitantextpremier),
        )
    //....
    }

rag 部分略有不同。我们使用带有自定义提示的 retrievelqa 链(类似于 amazon bedrock 知识库使用的提示):

func retrievalQAChainWithCustomPrompt(llm *bedrock_llm.LLM, retriever vectorstores.Retriever) chains.Chain {

    ragPromptTemplate := prompts.NewPromptTemplate(
        ragPromptTemplateString,
        []string{"context", "question"},
    )

    qaPromptSelector := chains.ConditionalPromptSelector{
        DefaultPrompt: ragPromptTemplate,
    }

    prompt := qaPromptSelector.GetPrompt(llm)

    llmChain := chains.NewLLMChain(llm, prompt)
    stuffDocsChain := chains.NewStuffDocuments(llmChain)

    return chains.NewRetrievalQA(
        stuffDocsChain,
        retriever,
    )
}

结论

我介绍了 amazon titan text premier,它是 titan 系列中的多种文本生成模型之一。除了文本生成之外,amazon titan 还具有嵌入模型(文本和多模式)和图像生成。您可以通过探索 amazon bedrock 文档中的所有内容来了解​​更多信息。快乐建造!

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
js正则表达式
js正则表达式

php中文网为大家提供各种js正则表达式语法大全以及各种js正则表达式使用的方法,还有更多js正则表达式的相关文章、相关下载、相关课程,供大家免费下载体验。

512

2023.06.20

js获取当前时间
js获取当前时间

JS全称JavaScript,是一种具有函数优先的轻量级,解释型或即时编译型的编程语言;它是一种属于网络的高级脚本语言,主要用于Web,常用来为网页添加各式各样的动态功能。js怎么获取当前时间呢?php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

244

2023.07.28

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

298

2023.08.03

js是什么意思
js是什么意思

JS是JavaScript的缩写,它是一种广泛应用于网页开发的脚本语言。JavaScript是一种解释性的、基于对象和事件驱动的编程语言,通常用于为网页增加交互性和动态性。它可以在网页上实现复杂的功能和效果,如表单验证、页面元素操作、动画效果、数据交互等。

5306

2023.08.17

js删除节点的方法
js删除节点的方法

js删除节点的方法有:1、removeChild()方法,用于从父节点中移除指定的子节点,它需要两个参数,第一个参数是要删除的子节点,第二个参数是父节点;2、parentNode.removeChild()方法,可以直接通过父节点调用来删除子节点;3、remove()方法,可以直接删除节点,而无需指定父节点;4、innerHTML属性,用于删除节点的内容。

481

2023.09.01

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

212

2023.09.04

Js中concat和push的区别
Js中concat和push的区别

Js中concat和push的区别:1、concat用于将两个或多个数组合并成一个新数组,并返回这个新数组,而push用于向数组的末尾添加一个或多个元素,并返回修改后的数组的新长度;2、concat不会修改原始数组,是创建新的数组,而push会修改原数组,将新元素添加到原数组的末尾等等。本专题为大家提供concat和push相关的文章、下载、课程内容,供大家免费下载体验。

218

2023.09.14

js截取字符串的方法介绍
js截取字符串的方法介绍

JavaScript字符串截取方法,包括substring、slice、substr、charAt和split方法。这些方法可以根据具体需求,灵活地截取字符串的不同部分。在实际开发中,根据具体情况选择合适的方法进行字符串截取,能够提高代码的效率和可读性 。

219

2023.09.21

Python 自然语言处理(NLP)基础与实战
Python 自然语言处理(NLP)基础与实战

本专题系统讲解 Python 在自然语言处理(NLP)领域的基础方法与实战应用,涵盖文本预处理(分词、去停用词)、词性标注、命名实体识别、关键词提取、情感分析,以及常用 NLP 库(NLTK、spaCy)的核心用法。通过真实文本案例,帮助学习者掌握 使用 Python 进行文本分析与语言数据处理的完整流程,适用于内容分析、舆情监测与智能文本应用场景。

10

2026.01.27

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 22.3万人学习

Django 教程
Django 教程

共28课时 | 3.6万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号