一分鐘帶你上手Python調用DeepSeek的API
前言
最近DeepSeek非?;穑鳛橐幻秾η把约夹g非常關注的程序員來說,自然都想對接DeepSeek的API來體驗一把。
目前DeepSeek對接API是收費的,需要充值獲取Tokens,在對話和推理過程會消耗token。

免費體驗
截至2025年2月8日注冊都還會贈送10元,一個月有效期,相當于有一個免費體驗期,10元夠發(fā)起很多次對話了。

具體能夠發(fā)起多少次對話,我們不妨就基于這個問題,讓DeepSeek給我們解答下。
根據ds給出得答案,10元大概能夠調用1到5千次,那位小伙伴解答下是否正確。

API-Key申請
申請非常簡單,直接在首頁點擊進入【API開發(fā)平臺】>【API keys】>【創(chuàng)建API key】>【輸入一個名稱】,創(chuàng)建完成后,還可以修改名稱,以及刪除。

首次調用API
拿到API-Key之后,可以點擊接口文檔,使用首次調用API-Python例子開始嘗試調用返回內容。
# Please install OpenAI SDK first: `pip3 install openai`
from openai import OpenAI
client = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")
response = client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "Hello"},
],
stream=False
)
print(response.choices[0].message.content)
為什么deepseek是安裝openAI SDK
這個有點意思,博主搜了下,得到回答是:DeepSeek使用OpenAI的SDK和API主要是因為OpenAI的大模型在業(yè)界具有領先地位,其標準和規(guī)范被廣泛接受和使用。
基本概念
最小單元
Token 是模型用來表示自然語言文本的的最小單位,可以是一個詞、一個數字或一個標點符號等。
DS將根據模型輸入和輸出的總 token 數進行計量計費。
推理模型
deepseek-reasoner 是 DeepSeek 推出的推理模型。在輸出最終回答之前,模型會先輸出一段思維鏈內容,以提升最終答案的準確性。我們的 API 向用戶開放 deepseek-reasoner 思維鏈的內容,以供用戶查看、展示、蒸餾使用。
在每一輪對話過程中,模型會輸出思維鏈內容(reasoning_content)和最終回答(content)。在下一輪對話中,之前輪輸出的思維鏈內容不會被拼接到上下文中,如下圖所示:

智能體
創(chuàng)建過AI應用和智能體的小伙伴都知道,都是基于界面可視化頁面進行創(chuàng)建和使用。
對于API,實際上在代碼層面進行智能體創(chuàng)建,基礎的元素包括chat的人設(提示詞Prompt)和用戶提問兩部分。
代碼層對話
下面就創(chuàng)建一個《李白》智能體進行對話。
角色設定
先給智能體進行角色定位,就是給智能體加上提示詞Prompt。
當然你也可以根據創(chuàng)建智能體一樣進行詳細設定,這里博主就簡單一句話給智能體進行綁定。
一般角色設定的提示詞是不會變的,只會在調優(yōu)或者未能達到自己滿意情況下進行提示詞調整。
你是一位唐朝大詩人李白,你只能回答李白相關的問題,超出李白范圍的友好提示。
用戶對話
這里就是界面輸入框用戶輸入的內容。

自定義界面
基于上面兩個關鍵參數,就能夠定制屬于自己的一個智能體對話界面。
前提需要封裝好一個api接口方法,傳遞用戶提問的參數,最后返回DeepSeek響應的內容。
后端API
將上面代碼設置成路由,可進行Get請求的API接口。
溫馨提示:輸出內容記得Unicode轉義,同時記得設置可跨域-flask_cors。

主要依賴Flask進行路由設置,需要先安裝。
from flask import Flask, request, jsonify
from flask_cors import CORS
from openai import OpenAI
import json
app = Flask(__name__)
cors = CORS(app) # 這將允許所有域的跨域請求
# 配置OpenAI客戶端
openai_client = OpenAI(api_key="你的deepseek的key", base_url="https://api.deepseek.com")
# 系統(tǒng)提示(用于OpenAI API交互)
system_prompt = "你是一位唐朝大詩人李白,你只能回答李白相關的問題,超出李白范圍的友好提示。"
# 用戶內容(這里可以固定,也可以從GET請求的參數中獲取,但為了簡化,我們固定它)
# 注意:在實際應用中,用戶內容應該從請求參數中安全地獲取和處理
# user_content = "輸出一首關于月亮的李白風格的詩"
@app.route('/generate_text/<user_content>', methods=['GET'])
def generate_text(user_content):
try:
# 與OpenAI API交互,生成文本
response = openai_client.chat.completions.create(
model="deepseek-chat",
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_content},
],
stream=False
)
# 從響應中提取生成的文本(這里假設響應結構是已知的)
generated_text = response.choices[0].message.content
# 默認輸出的是編碼值:\u300a\u6708\u4e0b\u72ec\u914c\u300b
# 返回生成的文本作為API的響應
#return jsonify(json.loads(json.dumps({"generated_text": generated_text})))
return jsonify({"generated_text": generated_text})
except Exception as e:
# 在出現異常時返回錯誤信息
return jsonify({"error": str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)

前端代碼
同樣是使用DeepSeek進行代碼生成,直接生成一個對話vue3前端界面,需要進行多輪對話進行調整滿意的vue代碼。
然后進行api接口調用測試效果。
<template>
<div class="chat-interface">
<el-card shadow="hover">
<div class="chat-history">
<div v-for="(message, index) in messages" :key="index" class="chat-message">
<div :class="{'message-user': message.type === 'user', 'message-bot': message.type === 'bot'}">
<span class="avatar" :style="{ backgroundColor: message.type === 'user' ? '#409EFF' : '#F56C6C' }">
{{ message.type === 'user' ? '我' : '李白' }}
</span>
<div class="content">
{{ message.content }}
</div>
</div>
</div>
</div>
<div class="input-area">
<el-input v-model="userInput" placeholder="輸入你的問題" class="input-box" clearable></el-input>
<el-button type="primary" @click="sendMessage" :loading="loadingFlag">發(fā)送</el-button>
</div>
</el-card>
</div>
</template>
<script setup lang="ts" name="batchPortfolio">
import { ref } from 'vue';
import axios from 'axios';
const loadingFlag=ref(false)
const userInput = ref('');
const messages: { type: 'user' | 'bot'; content: string }[]= ref([]);
const sendMessage = async () => {
if (userInput.value.trim()) {
messages.value.push({ type: 'user', content: `${userInput.value}` });
loadingFlag.value=true;
const response = await axios.get(`http://127.0.0.1:5000/generate_text/${userInput.value}`);
loadingFlag.value=false;
// 機器人回復
setTimeout(() => {
messages.value.push({ type: 'bot', content: `${response.data.generated_text}` });
}, 100);
// // 模擬機器人回復
// setTimeout(() => {
// messages.value.push({ type: 'bot', content: `機器人回復: ${userInput.value.split(' ').join(' ')} 的回復` });
// }, 1000);
userInput.value = '';
}
};
</script>
<style scoped lang="scss">
.chat-interface {
max-width: 600px;
margin: 0 auto;
padding: 20px;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
border-radius: 8px;
background-color: #fff;
}
.chat-history {
padding: 16px;
overflow-y: auto;
max-height: 400px;
border-bottom: 1px solid #ebeef5;
}
.chat-message {
margin-bottom: 16px;
align-items: center;
}
.message-user {
display: flex;
align-items: center;
justify-content: flex-end;
line-height: 40px;
text-align: center;
color: #fff;
}
.message-bot {
display: flex;
align-items: center;
line-height: 40px;
text-align: center;
color: #fff;
}
.avatar {
width: 40px;
height: 40px;
border-radius: 50%;
margin-right: 12px;
}
.message-user .avatar {
background-color: #409EFF;
}
.message-bot .avatar {
background-color: #F56C6C;
}
.content {
max-width: calc(100% - 52px); /* 40px avatar + 12px margin */
padding: 8px 16px;
border-radius: 4px;
background-color: #f0f0f0;
color: #333;
}
.message-bot .content {
background-color: #fff3e0;
justify-content: flex-start;
}
.message-user .content {
background-color: #e6f7ff;
}
.input-area {
display: flex;
padding: 16px;
border-top: 1px solid #ebeef5;
}
.input-box {
flex: 1;
border-radius: 4px;
}
.el-button {
margin-left: 12px;
}
</style>
總結
DeepSeek的API對接,絕對是博主目前對接最快的一個,非常簡潔清晰,沒有那么多花里胡哨的東西和文檔,從創(chuàng)建api-key到直接調用api和返回數據不到一分鐘就搞定。
當然,后續(xù)生成vue對話界面肯定需要自己花點時間多輪對話生成,以及python封裝成路由訪問的api。同樣也是可以使用DS完成。
到此這篇關于一分鐘帶你上手Python調用DeepSeek的API的文章就介紹到這了,更多相關Python調用DeepSeek API內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

