利用streamlit结合langchain_aws实现claud3的页面交互

测试使用的代码如下

复制代码
import streamlit as st
from langchain_aws import ChatBedrock

def chat_with_model(prompt, model_id):
    llm = ChatBedrock(credentials_profile_name="default", model_id=model_id, region_name="us-east-1")
    res = llm.invoke(prompt)
    return res.content

# Streamlit app
st.title("LangChain AWS Chat Interface")

# Sidebar for model selection
models = {
    "Claude-3 Sonnet": "anthropic.claude-3-sonnet-20240229-v1:0",
    "titan": "amazon.titan-text-express-v1",
    "Claude-3 haiku": "anthropic.claude-3-haiku-20240307-v1:0"
}

model_choice = st.sidebar.selectbox("Select a Model", list(models.keys()))
model_id = models[model_choice]

# Text area for user input
prompt = st.text_area("Enter your prompt here:", "")

if st.button("Send"):
    if prompt:
        response = chat_with_model(prompt, model_id)
        st.write(f"模型返回的结果:\n{response}")
    else:
        st.write("Please enter a prompt.")

运行代码

streamlit run app.py

运行结果如下

为了实现更友好的界面,修改源码如下

复制代码
import streamlit as st
from langchain_aws import ChatBedrock

# 定义与模型交互的函数
def chat_with_model(prompt, model_id, history):
    llm = ChatBedrock(credentials_profile_name="default", model_id=model_id, region_name="us-east-1")
    full_prompt = "\n".join(history + [prompt])
    res = llm.invoke(full_prompt)
    return res.content

# 初始化 Streamlit 应用
st.set_page_config(page_title="Bedrock Client", layout="wide")
st.title("Bedrock Client")

# 定义 CSS 样式
st.markdown(
    """
    <style>
    .sidebar .sidebar-content {
        background-color: #f0f0f5;
    }
    .main .block-container {
        padding: 2rem;
    }
    .chat-history {
        max-height: 400px;
        overflow-y: auto;
        padding: 1rem;
        background-color: #ffffff;
        border: 1px solid #ddd;
        border-radius: 8px;
        margin-bottom: 1rem;
    }
    .chat-input {
        width: 100%;
        padding: 1rem;
        border: 1px solid #ddd;
        border-radius: 8px;
    }
    </style>
    """,
    unsafe_allow_html=True
)

# 模型字典
models = {
    "Claude-3 Sonnet": "anthropic.claude-3-sonnet-20240229-v1:0",
    "titan": "amazon.titan-text-express-v1",
    "Claude-3 haiku": "anthropic.claude-3-haiku-20240307-v1:0"
}

# 侧边栏选择模型
st.sidebar.header("选择模型")
model_choice = st.sidebar.selectbox("Select a Model", list(models.keys()))
model_id = models[model_choice]

# 检查 session_state 中是否有对话历史记录
if "history" not in st.session_state:
    st.session_state.history = []

# 主界面布局
st.sidebar.title("会话")
st.sidebar.button("新建对话", on_click=lambda: st.session_state.update({"history": []}))
st.sidebar.markdown(f"**当前会话** ({len(st.session_state.history) // 2} 条对话)")

# 显示对话历史记录
st.markdown("### 对话记录")
chat_history_container = st.container()
with chat_history_container:
    if st.session_state.history:
        for message in st.session_state.history:
            st.markdown(f"<div class='chat-history'>{message}</div>", unsafe_allow_html=True)
    else:
        st.markdown("<div class='chat-history'>暂无对话记录</div>", unsafe_allow_html=True)

# 输入区域和发送按钮
prompt = st.text_input("Enter your prompt here:", "", key="input", placeholder="输入消息,Shift + Enter 换行 / 触发补全,触发命令", label_visibility="collapsed")

if st.button("发送"):
    if prompt:
        response = chat_with_model(prompt, model_id, st.session_state.history)
        st.session_state.history.append(f"User: {prompt}")
        st.session_state.history.append(f"Model: {response}")
        st.experimental_rerun()  # 刷新页面以显示新对话
    else:
        st.write("Please enter a prompt.")

运行之后界面如下所示

相关推荐
JavaPub-rodert5 小时前
LangChain 从入门到 Agent 实战:用 Python 搭建一个真正能调用工具和知识库的 AI 助手
人工智能·python·langchain
烬羽8 小时前
让大模型输出 JSON:从"正则剥 markdown"到"让它调个工具",一条可靠性升级之路
langchain·llm·openai
yyt3630458419 小时前
KLineChartQuant:GLSL 的精度问题及 RTC 解法
前端·vue.js·react.js·交互·图形渲染·webgl·数据可视化
Dream-Y.ocean11 小时前
基于具身交互智能数字人,我用Flask搭了一个AI教学平台:课代表AI全流程实战
人工智能·flask·交互
励志不掉头发的内向程序员12 小时前
【LibreCAD 2D架构】从鼠标点击到图形创建:RS_ActionDrawLine交互流程与状态机解析
开发语言·c++·qt·学习·系统架构·计算机外设·交互
Htr_12 小时前
Reflexio 使用指南:让 AI 智能体从每次交互中持续学习
人工智能·学习·交互
夫子39614 小时前
【第三部分:第一个 Agent 应用】12. 使用状态机开发一个可控 Agent
langchain·llm·agent
旖旎夜光15 小时前
【LangChain实战】LangChain 学习笔记(二):结构化输出、流式传输与消息管理
人工智能·笔记·python·学习·ai·langchain
Maiko Star16 小时前
[LangChain Agent] 03 ReAct 框架:思考→行动→观察
langchain
智购科技无人售货机工厂店1 天前
2026自动售货机大屏交互设计原则:从信息层级到视觉动线的工程实践~YH
运维·python·单片机·嵌入式硬件·自动化·交互