如何结合 Ollama 和 DeepSeek-R1 创建一个本地聊天机器人

无需联网,用 Ollama 本地运行 DeepSeek-R1 模型,搭配 Python + Gradio/Streamlit 快速搭建离线聊天机器人。支持流式响应、多轮对话与界面交互,兼顾隐私安全与开发实践价值,附完整可运行代码。

发布于2025年1月31日 05:59
编辑零重力瓦力
评论0
阅读96

国外 AI 技术达人 Mervin Praison (Mervin 个人技术网站)分享了一个使用 Ollama 和 DeepSeek-R1 创建本地 AI 聊天机器人的方法。通过这一方案,无需联网即可与 DeepSeek-R1 机器人进行对话,让它为你撰写各类文章,同时确保隐私信息的安全性。此外,这个示例还为大家提供了一个学习如何使用 Python 开发大语言模型应用的实践机会。

完整源代码

安装聊天机器人用到的 Python 库文件

pip install -U ollama chainlit streamlit gradio

聊天机器人主程序

import ollama

# Create streaming completion
completion = ollama.chat(
    model="deepseek-r1:latest",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Why sky is blue?"}
    ],
)

# Access message content directly from response
response = completion['message']['content']

print(response)

Streaming(Python 3.5 加入的标准库,是对序列操作的一种抽象和延迟计算的方式)

import ollama

# Create streaming completion
completion = ollama.chat(
    model="deepseek-r1:latest",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Why sky is blue?"}
    ],
    stream=True  # Enable streaming
)

# Print the response as it comes in
for chunk in completion:
    if 'message' in chunk and 'content' in chunk['message']:
        content = chunk['message']['content']
        print(content, end='', flush=True)

Gradio(一个用于创建机器学习模型交互式界面的Python 库)

import ollama
import gradio as gr

def chat_with_ollama(message, history):
    # Initialize empty string for streaming response
    response = ""
    
    # Convert history to messages format
    messages = [
        {"role": "system", "content": "You are a helpful assistant."}
    ]
    
    # Add history messages
    for h in history:
        messages.append({"role": "user", "content": h[0]})
        if h[1]:  # Only add assistant message if it exists
            messages.append({"role": "assistant", "content": h[1]})
    
    # Add current message
    messages.append({"role": "user", "content": message})
    
    completion = ollama.chat(
        model="deepseek-r1:latest",
        messages=messages,
        stream=True  # Enable streaming
    )
    
    # Stream the response
    for chunk in completion:
        if 'message' in chunk and 'content' in chunk['message']:
            content = chunk['message']['content']
            # Handle  and  tags
            content = content.replace("", "Thinking...").replace("", "\n\n Answer:")
            response += content
            yield response

# Create Gradio interface with Chatbot
with gr.Blocks() as demo:
    chatbot = gr.Chatbot()
    msg = gr.Textbox(placeholder="Enter your message here...")
    clear = gr.Button("Clear")

    def user(user_message, history):
        return "", history + [[user_message, None]]

    def bot(history):
        history[-1][1] = ""
        for chunk in chat_with_ollama(history[-1][0], history[:-1]):
            history[-1][1] = chunk
            yield history

    msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
        bot, chatbot, chatbot
    )
    clear.click(lambda: None, None, chatbot, queue=False)

if __name__ == "__main__":
    demo.launch()

Streamlit(一个专门针对机器学习和数据科学团队的应用开发框架)

import streamlit as st
import ollama

# Set page title
st.title("Chat with Ollama")

# Initialize chat history in session state if it doesn't exist
if "messages" not in st.session_state:
    st.session_state.messages = [
        {"role": "system", "content": "You are a helpful assistant."}
    ]

# Display chat input
user_input = st.chat_input("Your message:")

# Display chat history and handle new inputs
for message in st.session_state.messages:
    if message["role"] != "system":
        with st.chat_message(message["role"]):
            st.write(message["content"])

if user_input:
    # Display user message
    with st.chat_message("user"):
        st.write(user_input)
    
    # Add user message to history
    st.session_state.messages.append({"role": "user", "content": user_input})
    
    # Get streaming response
    with st.chat_message("assistant"):
        message_placeholder = st.empty()
        full_response = ""
        
        completion = ollama.chat(
            model="deepseek-r1:latest",
            messages=st.session_state.messages,
            stream=True
        )
        
        # Process the streaming response
        for chunk in completion:
            if 'message' in chunk and 'content' in chunk['message']:
                content = chunk['message']['content']
                full_response += content
                message_placeholder.write(full_response + "▌")
        
        message_placeholder.write(full_response)
    
    # Add assistant response to history
    st.session_state.messages.append({"role": "assistant", "content": full_response})

Chainlit(一个开源的异步 Python 框架)

import chainlit as cl
import ollama
import json

@cl.on_message
async def main(message: cl.Message):
    # Create a message dictionary instead of using Message objects directly
    messages = [{'role': 'user', 'content': str(message.content)}]
    
    # Create a message first
    msg = cl.Message(content="")
    await msg.send()

    # Create a stream with ollama
    stream = ollama.chat(
        model='deepseek-r1:latest',  # Use a model you have installed
        messages=messages,
        stream=True,
    )

    # Stream the response token by token
    for chunk in stream:
        if token := chunk['message']['content']:
            await msg.stream_token(token)
    
    # Update the message one final time
    await msg.update()

@cl.on_chat_start
async def start():
    await cl.Message(content="Hello! How can I help you today?").send()

相关文章

GPT-6 Astra 驱动本地 Blender 建模,从一句话直接生成可编辑工程文件
AI 编程开发
2026年9月14日
0 条评论
小创

GPT-6 Astra 驱动本地 Blender 建模,从一句话直接生成可编辑工程文件

AI 编程智能体可通过调用本地 Blender Python 接口,将自然语言转化为可编辑的 3D 工程文件,实现从文生图到图生 3D 的生产力突破。该模式支持渐进式迭代与技能固化,解决了传统生成模型不可二次编辑的痛点。但受限于无实时视口反馈,智能体在复杂拓扑与空间对齐上仍存盲区,需依赖视觉回检闭环规避风险。未来演进方向为接入多模态感知系统,以实现更精准的 3D 内容创作。

#AI工具#智能体#3D建模
阅读全文
Superpowers 让 26 款 AI 编程工具学会规范工程,28 万星智能体工作流实战
AI 编程开发
2026年9月14日
0 条评论
小创

Superpowers 让 26 款 AI 编程工具学会规范工程,28 万星智能体工作流实战

开源项目 Superpowers 通过强制工程化约束,解决 AI 编程工具输出混乱问题。该框架适配 26 款主流工具,内置 7 步标准工作流与模块化技能库,强制执行需求澄清、Git 分支隔离及测试驱动开发,将 AI 编码从自由生成转变为严谨的软件工程生命周期管理。虽能显著提升代码稳定性与可维护性,但子代理驱动模式会导致 API Token 消耗激增,大型项目需注意调用成本。

#智能体#vibe编程#开源
阅读全文
Codex 驱动本地 Blender 渲染 3D 场景,三轮提示词沉淀智能体技能
AI 编程开发
2026年9月14日
0 条评论
小创

Codex 驱动本地 Blender 渲染 3D 场景,三轮提示词沉淀智能体技能

独立研究员 Simon Willison 演示了利用 GPT-6 Astra 驱动本地 Blender 完成高质量 3D 场景渲染。该 Coding Agent 通过 Python API 执行无头渲染,具备视觉反思能力,可在三轮对话内将简单模型迭代至电影级画质,并将流程固化为可复用技能。此模式输出完整工程文件,支持二次编辑,重构了 3D 内容生产范式。尽管在复杂有机体建模上仍有局限,但标志着 AI 正作为技术美术精准调用工业软件生态。

#智能体#AI工具#3D
阅读全文
互动讨论

评论区

围绕《如何结合 Ollama 和 DeepSeek-R1 创建一个本地聊天机器人》展开交流,未登录用户可浏览评论,登录后可参与讨论。

评论数
0
登录后参与评论
支持发表观点与回复一级评论,互动后将同步到消息中心。
登录后评论
暂无评论,欢迎成为第一个参与讨论的人。