最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python使用Flask結(jié)合DeepSeek開發(fā)(實(shí)現(xiàn)代碼)

 更新時(shí)間:2025年02月15日 13:45:57   作者:程序員Rocky  
文章介紹了如何使用ollama部署DeepSeek大模型,并通過Python Flask和SSE技術(shù)實(shí)現(xiàn)一個(gè)簡單的對話應(yīng)用,代碼實(shí)現(xiàn)了模型的調(diào)用和結(jié)果展示,并討論了SSE不支持POST請求的問題及解決方案,感興趣的朋友一起看看吧

一、背景

        我之前關(guān)于DeepSeek使用ollama部署的文章大家可以把DeepSeek大模型部署起來。那么ollama還提供了可以調(diào)用對應(yīng)部署模型的API接口。我們可以基于這些接口,做自己的二次開發(fā)。使用python+flask+ollama就可以進(jìn)行模型對話調(diào)用。并且前端采用SSE的技術(shù),后端向前端推送推理結(jié)果進(jìn)行展示,可以實(shí)現(xiàn)屬于自己的大模型對話產(chǎn)品。

二、代碼實(shí)現(xiàn)

1、ollama運(yùn)行deepseek-r1:1.5b模型

docker run -d -v ollama:/root/.ollama -p 11434:11434 --name ollama ollama/ollama
docker exec -it ollama ollama run deepseek-r1:1.5b

2、python+flask代碼

import json
from flask import Flask, request, Response
from ollama import Client
app = Flask(__name__)
# ollama客戶端
ollma_url = "http://localhost:11434"   # localhost可以換成你部署ollama主機(jī)的ip、遠(yuǎn)程ip
ollama_client = Client(host=ollma_url )
# 模型名稱
model_name = "deepseek-r1:1.5b"
@app.route('/stream', methods=['POST', 'GET'])
def post_example():
    def generate():
        try:
            # 調(diào)用ollama客戶端,傳入模型名稱、提問信息
            response_generator = ollama_client.generate(model_name, prompt=question, stream=True)
            for part in response_generator:
                response_text = part.response
                # 按照 SSE 規(guī)范格式化數(shù)據(jù)
                data = f"data: {json.dumps({'response': response_text})}\n\n"
                print(data)
                yield data
        except Exception as e:
            error_data = f"data: {json.dumps({'error': str(e)})}\n\n"
            yield error_data
    # 接收問題, 調(diào)用模型, 使用SSE推送推理結(jié)果給前端
    question = request.args.get('question')
    resp = Response(generate(), mimetype='text/event-stream')
    # 設(shè)置響應(yīng)頭
    resp.headers['Cache-Control'] = 'no-cache'
    resp.headers['Connection'] = 'keep-alive'
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp
if __name__ == '__main__':
    app.run(debug=True, port=8080)

3、前端代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ask Ollama via SSE</title>
</head>
<body>
    <input type="text" id="questionInput" placeholder="請輸入你的問題">
    <button id="askButton">提問</button>
    <pre id="answerContainer"></p>
    <script>
        const questionInput = document.getElementById('questionInput');
        const askButton = document.getElementById('askButton');
        const answerContainer = document.getElementById('answerContainer');
        askButton.addEventListener('click', async () => {
            const question = questionInput.value;
            if (!question) {
                alert('請輸入問題');
                return;
            }
            const eventSource = new EventSource(`http://localhost:8080/stream?question=${encodeURIComponent(question)}`);
            eventSource.onmessage = function (event) {
                const data = JSON.parse(event.data);
                const response = data.response;
                if (response) {
                    const p = document.createElement('span');
                    p.textContent = response;
                    answerContainer.appendChild(p);
                }
            };
            eventSource.onerror = function (error) {
                console.error('EventSource failed:', error);
                eventSource.close();
            };
        });
    </script>
</body>
</html>

4、運(yùn)行結(jié)果

        頁面雖然不是很美觀,但是一個(gè)基本原理的demo已經(jīng)搞定。剩下的就是優(yōu)化界面、優(yōu)化鏈接異常等相關(guān)邏輯。

5、SSE默認(rèn)不支持POST請求

        SSE默認(rèn)不支持POST請求,可以找前端的一些npm包有人進(jìn)行了封裝,可以發(fā)送POST請求。以上的實(shí)例為了方便采用了GET請求

三、總結(jié)

        有了ollama就行docker服務(wù)一樣,提供了API接口,部署的模型就是類似docker已經(jīng)運(yùn)行的容器。 通過ollama接口,可以調(diào)用運(yùn)行的模型的各種能力!

到此這篇關(guān)于Python使用Flask結(jié)合DeepSeek開發(fā)的文章就介紹到這了,更多相關(guān)Python DeepSeek開發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

周口市| 桂平市| 乌拉特后旗| 定兴县| 东阿县| 鄂州市| 山东省| 利津县| 丰原市| 福鼎市| 博客| 万荣县| 漳平市| 沁阳市| 鄂托克前旗| 资兴市| 长汀县| 开封市| 西乡县| 阜宁县| 朝阳县| 蒙山县| 元朗区| 绿春县| 台湾省| 梁河县| 二连浩特市| 洪洞县| 山阴县| 绥宁县| 高雄县| 上犹县| 庆城县| 肇源县| 望城县| 抚顺县| 柳州市| 嘉兴市| 香港| 山阳县| 修文县|