当前位置: 首页 > news >正文

deepseek API 调用示例演示

1、工程目录结构如下2、后端设计step1: backend/main.pyimport os from pathlib import Path from datetime import datetime, timezone, timedelta from dotenv import load_dotenv from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import FileResponse from pydantic import BaseModel from openai import OpenAI # 从项目根目录下的 .env 文件中读取环境变量并将其加载到系统的环境变量中方便后续通过 os.getenv() 调用 load_dotenv() app FastAPI(titleDeepSeek文字问答系统) # 允许前端跨域访问 app.add_middleware( CORSMiddleware, allow_origins[*], allow_credentialsTrue, allow_methods[*], allow_headers[*], ) client OpenAI( api_keyos.getenv(DEEPSEEK_API_KEY), base_urlhttps://api.deepseek.com ) class ChatRequest(BaseModel): text: str def ask_deepseek(user_text: str) - str: 调用 DeepSeek API只处理文字输入。 system_prompt 你是一个智能助手。 请根据用户输入的问题进行回答。 回答要求 1. 如果用户问技术问题请尽量给出清晰、分步骤的解释。 2. 如果用户问学习或项目问题请尽量结合高职教学场景回答。 3. 如果用户问相关编程的问题请给出准确可运行的程序及所需运行环境。 4. 回答要准确、简洁、结构清楚。 user_prompt f【用户输入的问题】{user_text}请回答用户的问题。 response client.chat.completions.create( modeldeepseek-v4-flash, messages[ {role: system, content: system_prompt}, {role: user, content: user_prompt} ], streamFalse, extra_body{ thinking: {type: disabled} } ) return response.choices[0].message.content app.get(/) def home(): 访问首页时直接打开前端页面。 frontend_path Path(__file__).resolve().parent.parent / frontend / index.html return FileResponse(frontend_path) app.get(/web) def web_page(): 兼容原来的 /web 访问方式。 frontend_path Path(__file__).resolve().parent.parent / frontend / index.html return FileResponse(frontend_path) app.get(/api/chat) def chat_get_tip(): return { message: 该接口只支持 POST 请求请通过网页输入问题后点击提交。, usage: 访问 / 或 /web 打开前端页面 } app.post(/api/chat) def chat(request: ChatRequest): 接收前端文字问题并调用 DeepSeek 返回回答。 user_text request.text.strip() if not user_text: return { success: False, message: 请输入问题。 } try: answer ask_deepseek(user_text) return { success: True, user_text: user_text, answer: answer } except Exception as e: return { success: False, message: fDeepSeek调用失败{str(e)} }step2: backend/requirements.txtfastapi uvicorn openai python-dotenvstep3: 本工程下创建虚拟环境venv并安装requirements.txtpip install -r requirements.txtstep4: deepseek密钥配置创建文件 .envDEEPSEEK_API_KEY 你的deepseek密钥3、前端设计frontend/index.html!DOCTYPE html html langzh-CN head meta charsetUTF-8 titleDeepSeek问答系统/title style body { margin: 0; padding: 0; background: #f5f7fb; font-family: Microsoft YaHei, sans-serif; } .container { width: 760px; margin: 40px auto; background: #fff; border-radius: 16px; padding: 28px; box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08); } h1 { text-align: center; color: #222; } textarea { width: 100%; height: 150px; border: 1px solid #dcdfe6; border-radius: 10px; padding: 12px; font-size: 16px; box-sizing: border-box; outline: none; } textarea:focus { border-color: #409eff; } button { width: 100%; margin-top: 22px; padding: 13px; background: #2563eb; color: white; border: none; border-radius: 10px; font-size: 17px; cursor: pointer; } button:hover { background: #1d4ed8; } button:disabled { background: #9ca3af; cursor: not-allowed; } .result { margin-top: 24px; background: #f8fafc; border-radius: 12px; padding: 18px; border: 1px solid #e5e7eb; white-space: pre-wrap; line-height: 1.8; min-height: 180px; } .tip { font-size: 14px; color: #6b7280; margin-top: 8px; } /style /head body div classcontainer h1基于DeepSeek API的问答系统/h1 textarea idquestion placeholder请输入问题.../textarea div classtip仅支持文字输入。/div button idsubmitBtn onclicksubmitQuestion()提交提问/button div classresult idresult等待提问.../div /div script const API_URL /api/chat; const submitBtn document.getElementById(submitBtn); const resultDiv document.getElementById(result); async function submitQuestion() { const question document.getElementById(question).value.trim(); if (!question) { alert(请先输入问题。); return; } submitBtn.disabled true; submitBtn.innerText 正在回答...; resultDiv.innerText 正在调用 DeepSeek...; try { const response await fetch(API_URL, { method: POST, headers: { Content-Type: application/json }, body: JSON.stringify({ text: question }) }); if (!response.ok) throw new Error(服务器响应异常状态码 response.status); const data await response.json(); if (!data.success) { resultDiv.innerText 请求失败\n data.message; } else { resultDiv.innerText 【用户输入】\n data.user_text \n\n【DeepSeek回答】\n data.answer; } } catch (error) { resultDiv.innerText 请求失败\n error.message; } finally { submitBtn.disabled false; submitBtn.innerText 提交提问; } } /script /body /html4、启动后端uvicorn main:app --host 0.0.0.0 --port 8000 --reload5、前端访问http://127.0.0.1:8000/
http://www.rkmt.cn/news/1382083.html

相关文章:

  • ATtiny85 PWM音频播放与低功耗设计实战:从WAV到嵌入式发声装置
  • 广州名表回收避坑攻略!2026内行首选添价收,新手变现不亏钱 - 薛定谔的梨花猫
  • 内容方短剧平台开发|自有版权入驻 分账结算独立后台
  • 如何免费获取百度文库文档:终极浏览器脚本解决方案
  • 2026 不限专业能考的数学专业证书
  • CANN 环境检查报告
  • 【Lovable前端开发实战】:20年专家亲授5个让团队抢着用的可维护性编码心法
  • 用HDLbits的Lemmings游戏四部曲,手把手教你搞定复杂状态机设计(附完整Verilog代码)
  • DIY盖革计数器物联网监测系统:从硬件到Web的全栈实现
  • 如何快速上手REFramework:RE引擎游戏Mod开发终极指南
  • 掌握Umi-OCR:5分钟上手开源免费离线文字识别工具
  • 基于C#实现(WinForm)P2P聊天程序
  • 氨基-聚乙二醇20-羧基 NH2-PEG20-COOH 产品使用指南
  • Flowframes完整指南:3步将普通视频升级为丝滑慢动作
  • AhMyth性能优化:减少资源占用与提升响应速度
  • 2026年西安家庭防水补漏靠谱经营主体3家选型参考深度分析报告 - 冠盾建筑修缮
  • ESP32+Edge Impulse实战:零基础实现嵌入式物体分类与部署
  • Get Data from Steam / SteamDB高级技巧:自定义配置与批量数据处理指南
  • 思源宋体TTF字体终极配置指南:7种字重免费商用完全教程
  • OpenAI 总裁:我正努力回忆“古法编程”是什么感觉。网友:怀念但早被 AI 惯坏了
  • 歌手胡彦斌居然也在 vibe coding 了,而是随地大小修 bug 的那种。网友:来抢程序员饭碗了吗?
  • 正视孩童情绪波动,耐心陪伴平稳疏导
  • Hermes Agent 框架如何对接 Taotoken 作为自定义模型供应商并配置环境变量
  • Sora 2 AVI格式支持深度解析(工程师内部备忘录首次公开:H.264/AVC封装层绕过方案与时间戳对齐漏洞修复)
  • 交流电方向检测原理与实验:从相位差到光伏并网计量
  • 余生黄金回收——2026年5月烟台黄金变现全攻略,本地十年老店教你不踩坑 - 润富黄金珠宝行
  • Taotoken用量看板功能详解,助你洞察团队AI资源消耗模式
  • 如何在浏览器中高效处理加密音乐文件:开源解密工具完全指南
  • IoTSharp多租户架构:实现SaaS物联网平台的企业级解决方案
  • 如何快速理解iOS Auto Layout错误:WTF Auto Layout? 5分钟入门教程