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

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

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

国外 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()

相关文章

Claude 自己开机器狗:比人快20 倍,代码量只有十分之一
访谈案例
2026年6月21日
0 条评论
零重力瓦力

Claude 自己开机器狗:比人快20 倍,代码量只有十分之一

Anthropic 实验显示,Claude Opus 4.7 已能全程自主控制机器狗完成任务,速度比人类快约 20 倍,代码量仅为其十分之一。这标志着 AI 智能体正从辅助编程迈向物理工具自主操作阶段。但模型在实时闭环精细控制上仍有局限,且当前成果基于低复杂度任务。该进展体现了通用模型 scaling 的副产物效应,预示物理智能体时代早期来临,但距离解决复杂真实场景仍有差距。

#Claude#AI 编程
阅读全文
JetBrains Junie 正式版:AI 编程 Agent 学会了用调试器断点
AI 编程开发
2026年6月19日
0 条评论
零重力瓦力

JetBrains Junie 正式版:AI 编程 Agent 学会了用调试器断点

JetBrains AI 编程 Agent Junie 正式 GA,在 SWE-Rebench 基准测试中排名第一。其核心优势在于深度集成 IDE 原生工具链,而非模拟替代。主要特性包括:Plan 模式生成结构化计划文档以防跑偏;原生调试器集成支持断点与运行时状态检查;支持异步远程控制长任务;基于项目上下文的交互式代码审查;以及模型自由切换以优化成本。Junie 标志着 AI 编程竞争正从模型能力转向工具集成深度。

#智能体#AI 编程
阅读全文
别再纠结 Claude Code 还是 Cursor,高效开发者在同时用两个
AI 编程开发
2026年6月5日
0 条评论
零重力瓦力

别再纠结 Claude Code 还是 Cursor,高效开发者在同时用两个

高效开发者倾向于组合使用 AI 编程工具而非二选一。实战表明,Cursor 适合单文件精细调整,Claude Code 擅长跨文件重构与后台任务,两者互补可显著提升效率。多智能体并行及“先规划后编码”策略能加速 SaaS 开发,但需警惕 AI 生成质量下滑等问题。此外,Hermes Agent 等自动化工具可替代人工定时任务。建议以 Cursor 为主、Claude Code 处理复杂任务,初学者应循序渐进掌握工具组合拳。

#Claude Code#AI 编程
阅读全文
互动讨论

评论区

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

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