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

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

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

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

相关文章

Windsurf 2.0 拆解:Devin 被塞进编辑器,氛围编程终于有了“调度中心”
AI 编程开发
2026年6月2日
0 条评论
零重力瓦力

Windsurf 2.0 拆解:Devin 被塞进编辑器,氛围编程终于有了“调度中心”

Cognition 发布 Windsurf 2.0,深度整合 Devin 实现本地思考与云端执行分工。新版推出 Agent Command Center 支持多智能体可视化管理,搭载自研 SWE-1.5 模型大幅提升代码定位与编辑速度,并引入 Spaces 容器解决上下文延续问题。Pro 版调整为日配额制且包含 Devin 功能。相比 Cursor 3,Windsurf 2.0 凭借自研模型与云端执行能力,更适合处理陌生代码库及长任务自动化场景。

#智能体#AI 编程
阅读全文
Claude Opus 4.8 震撼发布,多智能体协同让开发效率翻倍
AI 新闻资讯
2026年6月1日
0 条评论
小创

Claude Opus 4.8 震撼发布,多智能体协同让开发效率翻倍

Anthropic 发布 Claude Opus 4.8,在基准测试中超越 ChatGPT 5.5,重夺编程领域领先地位。新版本核心亮点为动态工作流与 Ultracode 模式,通过多智能体协同大幅提升复杂任务开发效率,同时幻觉率降至四分之一。得益于算力扩充,其性能提升且价格下调,快速模式费用降至三分之一。建议开发者日常使用常规上下文模式并调高努力程度,大项目再开至最大。此外,AI 时代专注力仍是拉开差距的关键。

#Claude#AI 编程
阅读全文
告别套壳与适配:2026 开发者主流 LLM 聚合网关选型指南
AI 编程开发
2026年5月29日
0 条评论
零重力瓦力

告别套壳与适配:2026 开发者主流 LLM 聚合网关选型指南

针对 AI 应用开发中多模型适配难题,LLM 聚合 API 平台通过统一接口有效降低维护成本。海外平台如 OpenRouter、Portkey 生态完善且兼容性强。国内平台如硅基流动、阿里云百炼侧重合规与本土模型支持。自建方案 LiteLLM、One API 则适合追求自主可控与极致性价比的团队。开发者应根据业务阶段、预算及合规要求灵活选型,生产环境推荐采用“自建网关+多渠道分流”的混搭架构,以兼顾成本、稳定性与灵活性。

#模型 API
阅读全文
互动讨论

评论区

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

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