使用Streamlit、LangChain和Bedrock構(gòu)建一個(gè)交互式聊天機(jī)器人 原創(chuàng)
本文將幫助你使用低代碼前端、用于會(huì)話管理的LangChain以及用于生成響應(yīng)的Bedrock LLM來創(chuàng)建聊天機(jī)器人。
在不斷發(fā)展的AI領(lǐng)域,聊天機(jī)器人已成為一種不可或缺的工具,用于增強(qiáng)用戶參與度和簡化信息傳遞。本文將逐步介紹構(gòu)建交互式聊天機(jī)器人的具體過程,使用Streamlit作為前端、使用LangChain用于協(xié)調(diào)交互,以及使用基于Amazon Bedrock的Anthropic Claude模型作為大語言模型(LLM)后端。我們將深入研究前端和后端的代碼片段,并解釋使這個(gè)聊天機(jī)器人切實(shí)可行的關(guān)鍵組件。
核心組件
- Streamlit前端:Streamlit的直觀界面便于我們不用花多大的力氣就能創(chuàng)建一個(gè)對(duì)用戶友好的低代碼聊天界面。我們將探討代碼如何創(chuàng)建聊天窗口、處理用戶輸入和顯示聊天機(jī)器人的響應(yīng)。
- LangChain編排:LangChain使我們能夠管理會(huì)話流程和內(nèi)存,確保聊天機(jī)器人維護(hù)上下文并提供相關(guān)的響應(yīng)。我們將討論如何整合LangChain的ConversationSummaryBufferMemory和ConversationChain。
- Bedrock/Claude LLM后端:真正的魔力在于LLM后端。我們將看看如何利用Amazon Bedrock的claude基礎(chǔ)模型來生成上下文感知的智能響應(yīng)。
圖1. 聊天機(jī)器人體系結(jié)構(gòu)
體系結(jié)構(gòu)的概念闡述
- 用戶交互:用戶通過在Streamlit創(chuàng)建的聊天界面中輸入消息來發(fā)起對(duì)話。該消息可以是問題、請(qǐng)求或用戶希望提供的任何其他形式的輸入。
- 輸入捕獲和處理:Streamlit的聊天輸入組件捕獲用戶的消息,并將其傳遞給LangChain框架進(jìn)行進(jìn)一步處理。
- 語境化結(jié)合LangChain記憶:LangChain在保持對(duì)話的上下文方面起著至關(guān)重要的作用。它將用戶的最新輸入與存儲(chǔ)在內(nèi)存中的相關(guān)對(duì)話歷史記錄結(jié)合起來。這確保了聊天機(jī)器人擁有必要的信息,以生成有意義且符合上下文的響應(yīng)。
- 利用LLM:然后將結(jié)合的上下文發(fā)送到Bedrock/Claude LLM。這個(gè)強(qiáng)大的語言模型利用其豐富的知識(shí)以及對(duì)語言的理解來分析上下文,并生成響應(yīng),以大量的豐富信息回復(fù)用戶的輸入。
- 響應(yīng)檢索:LangChain從LLM接收生成的響應(yīng),并準(zhǔn)備將其提供給用戶。
- 響應(yīng)顯示:最后,Streamlit獲得聊天機(jī)器人的響應(yīng)后將其顯示在聊天窗口中,使其看起來好像聊天機(jī)器人正與用戶進(jìn)行自然地對(duì)話。這營造了一種直觀的、對(duì)用戶友好的體驗(yàn),鼓勵(lì)進(jìn)一步的交互。
代碼片段
前端(Streamlit)
Python
import streamlit
import chatbot_backend
from langchain.chains import ConversationChain
from langchain.memory import ConversationSummaryBufferMemory
import boto3
from langchain_aws import ChatBedrock
import pandas as pd
# 2 Set Title for Chatbot - streamlit.title("Hi, This is your Chatbott")
# 3 LangChain memory to the session cache - Session State -
if 'memory' not in streamlit.session_state:
streamlit.session_state.memory = demo.demo_memory()
# 4 Add the UI chat history to the session cache - Session State
if 'chat_history' not in streamlit.session_state:
streamlit.session_state.chat_history = []
# 5 Re-render the chat history
for message in streamlit.session_state.chat_history:
with streamlit.chat_message(message["role"]):
streamlit.markdown(message["text"])
# 6 Enter the details for chatbot input box
input_text = streamlit.chat_input("Powered by Bedrock")
if input_text:
with streamlit.chat_message("user"):
streamlit.markdown(input_text)
streamlit.session_state.chat_history.append({"role": "user", "text": input_text})
chat_response = demo.demo_conversation(input_text=input_text,
memory=streamlit.session_state.memory)
with streamlit.chat_message("assistant"):
streamlit.markdown(chat_response)
streamlit.session_state.chat_history.append({"role": "assistant", "text": chat_response})
后端(LangChain和LLM)
Python
from langchain.chains import ConversationChain
from langchain.memory import ConversationSummaryBufferMemory
import boto3
from langchain_aws import ChatBedrock
# 2a Write a function for invoking model- client connection with Bedrock with profile, model_id
def demo_chatbot():
boto3_session = boto3.Session(
# Your aws_access_key_id,
# Your aws_secret_access_key,
region_name='us-east-1'
)
llm = ChatBedrock(
model_id="anthropic.claude-3-sonnet-20240229-v1:0",
client=boto3_session.client('bedrock-runtime'),
model_kwargs={
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 20000,
"temperature": .3,
"top_p": 0.3,
"stop_sequences": ["\n\nHuman:"]
}
)
return llm
# 3 Create a Function for ConversationSummaryBufferMemory (llm and max token limit)
def demo_memory():
llm_data = demo_chatbot()
memory = ConversationSummaryBufferMemory(llm=llm_data, max_token_limit=20000)
return memory
# 4 Create a Function for Conversation Chain - Input text + Memory
def demo_conversation(input_text, memory):
llm_chain_data = demo_chatbot()
# Initialize ConversationChain with proper llm and memory
llm_conversation = ConversationChain(llm=llm_chain_data, memory=memory, verbose=True)
# Call the invoke method
full_input = f" \nHuman: {input_text}"
llm_start_time = time.time()
chat_reply = llm_conversation.invoke({"input": full_input})
llm_end_time = time.time()
llm_elapsed_time = llm_end_time - llm_start_time
memory.save_context({"input": input_text}, {"output": chat_reply.get('response', 'No Response')})
return chat_reply.get('response', 'No Response')
結(jié)論
我們?cè)谏厦嫣接懥擞肧treamlit、LangChain和強(qiáng)大的LLM后端構(gòu)建的交互式聊天機(jī)器人的基本模塊。這個(gè)基礎(chǔ)為從客戶支持自動(dòng)化到個(gè)性化學(xué)習(xí)體驗(yàn)的無限可能打開了大門。你可以隨意試驗(yàn)、改進(jìn)和部署這個(gè)聊天機(jī)器人,以滿足自己的特定需求和使用場景。
原文標(biāo)題:??Building an Interactive Chatbot With Streamlit, LangChain, and Bedrock??,作者:Karan Bansal
