Ollama 本地开源大模型聊天应用

如果您也和我一样准备春招,只为TOP20大厂,欢迎加我微信shunwuyu,一起交流面经,一起屡败屡战。

前言

如果您想在localhost部署并运行开源大模型,可以试试Ollama。本文我们将使用Ollama部署,并通过API的方式调用大模型。

安装

Ollama提供了python和js两种开发包,对前端开发者挺友好的,用它!

复制代码
pip install ollama

npm install ollama

应用场景

  • 聊天接口

  • 多模态

模型

我们可以通过 library (ollama.com) 查看Ollama支持的模型清单,有gemmallama2mistralmixtral等,非常的丰富。

比如我们要使用的开源模型是llama2, 我们可以使用如下代码下载(首次)并运行模型

bash 复制代码
# 拉取模型
ollama pull llama2
# 运行模型
ollama run llama2

接口

如果我们使用过openai的一些接口, 那么就了解文本补全、聊天、嵌入等。ollama提供了REST API来提供了请求接口。

  • 生成式接口
python 复制代码
curl http://localhost:11434/api/generate -d '{
  "model": "llama2",
  "prompt":"Why is the sky blue?"
}'
  • 聊天接口
python 复制代码
curl http://localhost:11434/api/chat -d '{
  "model": "mistral",
  "messages": [
    { "role": "user", "content": "why is the sky blue?" }
  ]
}'
  • 嵌入
python 复制代码
curl http://localhost:11434/api/embeddings -d '{
  "model": "all-minilm",
  "prompt": "Here is an article about llamas..."
}'

实战

我们将结合StreamlitOllama,开发一个聊天应用。

Streamlit是一款Web开发框架,适用于python快速完成一些大模型、数学科学计算的UI开发。

我们还会用到 Build a ChatGPT-like App | Streamlit 代码快速构建类chatgpt应用。

python 复制代码
# 引入streamlit UI库
import streamlit as st
# 引入 ollama
import ollama
# 获取ollama的模型列表
model_list = ollama.list()
# 设置默认模型名字为 llama2:7b-chat
if "model_name" not in st.session_state:
    st.session_state["model_name"] = "llama2:7b-chat"
# 初始化聊天信息数组
if "messages" not in st.session_state:
    st.session_state.messages = []
# 设置边栏
with st.sidebar:
    # 侧边栏的标题
    st.subheader("Settings")
    # 下拉框   选择模型, 默认选中llama2
    option = st.selectbox(
        'Select a model',
        [model['name'] for model in model_list['models']])
    st.write('You selected:', option)
    st.session_state["model_name"] = option
# 页面标题  与llama聊天
st.title(f"Chat with {st.session_state['model_name']}")
# 遍历聊天数组
for message in st.session_state.messages:
    # 根据角色
    with st.chat_message(message["role"]):
        # 输出内容
        st.markdown(message["content"])

if prompt := st.chat_input("What is up?"):
    
    st.session_state.messages.append({"role": "user", "content": prompt})
    
    with st.chat_message("user"):
        st.markdown(prompt)
    
    with st.chat_message("assistant"):
        # 大模型返回后就清空输入框
        message_placeholder = st.empty()
        full_response = ""
        for chunk in ollama.chat(
            model=st.session_state["model_name"],
            messages=[
                {"role": m["role"], "content": m["content"]}
                for m in st.session_state.messages
            ],
            # 逐渐打出
            stream=True,
        ):
            if 'message' in chunk and 'content' in chunk['message']:
                full_response += (chunk['message']['content'] or "")
                message_placeholder.markdown(full_response + "▌")
        message_placeholder.markdown(full_response)
    st.session_state.messages.append({"role": "assistant", "content": full_response})
  • 拉取模型

ollama pull

除了llama2, 我们再拉取下orca-mini

  • 列出当前所有模型

ollama list

  • 运行streamlit

streamlit run app.py

总结

  • Ollama在本地部署开源大模型,真心方便且靠谱。 我在红米老爷机上运行了, 可以。
  • 结合streamlit 快速将Web搭建了出来。

参考资料

相关推荐
香蕉可乐荷包蛋18 分钟前
Python面试问题
开发语言·python·面试
界面开发小八哥32 分钟前
智能Python开发工具PyCharm v2025.1——AI层级功能重磅升级
ide·人工智能·python·pycharm·开发工具
Blossom.1181 小时前
可解释人工智能(XAI):让机器决策透明化
人工智能·驱动开发·深度学习·目标检测·机器学习·aigc·硬件架构
康斯坦丁师傅1 小时前
深夜突袭,阿里Qwen3登顶全球开源王座!暴击DeepSeek-R1
aigc·openai
啊阿狸不会拉杆1 小时前
人工智能数学基础(一):人工智能与数学
人工智能·python·算法
蹦蹦跳跳真可爱5891 小时前
Python----卷积神经网络(卷积为什么能识别图像)
人工智能·python·深度学习·神经网络·计算机视觉·cnn
geovindu1 小时前
PyCharm 2023升级2024 版本
ide·python·pycharm
roc-ever2 小时前
用Python做有趣的AI项目5:AI 画画机器人(图像风格迁移)
人工智能·python·深度学习
不爱学英文的码字机器2 小时前
数字孪生的浪潮:从虚拟镜像到现实世界的 IT 变革
大数据·python
小白—人工智能2 小时前
数据可视化 —— 直方图
python·信息可视化·数据可视化