import requests import json headers = { "Authorization": "Bearer YOUR_API_KEY", "Content-Type": "application/json" } data = { "model": "deepseek-r1", "messages": [{"role": "user", "content": "解释Python装饰器"}], "temperature": 0.7 } response = requests.post( "https://api.deepseek.com/chat/completions", headers=headers, json=data ) print(response.json()["choices"][0]["message"]["content"])
ava(Spring Boot)示例:
添加依赖:
配置application.properties
deepseek.api.key=YOUR_API_KEY
deepseek.api.url=https://api.deepseek.com
服务层调用:
@Service public class DeepSeekService { @Value("${deepseek.api.key}") private String apiKey; public String getResponse(String prompt) { // 使用SDK或HTTP客户端调用API } }
步骤:
安装 Ollama:
curl -fsSL https://ollama.ai/install.sh | sh
下载模型
ollama pull deepseek-r1:14b
通过 REST API 调用:
import requests response = requests.post( "http://localhost:11434/api/generate", json={"model": "deepseek-r1", "prompt": "写一个冒泡排序"} ) print(response.json()["response"])
2. 集成到 C# 项目
通过 Ollama API:
using HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:11434"); var request = new HttpRequestMessage( HttpMethod.Post, "/api/generate" ); request.Content = new StringContent( JsonConvert.SerializeObject(new { model = "deepseek-r1", prompt = "解释C#委托" }), Encoding.UTF8, "application/json" ); var response = await client.SendAsync(request); var result = await response.Content.ReadAsStringAsync();
三、深度定制化集成
Python 示例:
from langchain.llms import DeepSeek from langchain.chains import RetrievalQA from langchain.document_loaders import TextLoader # 加载本地文档 loader = TextLoader("knowledge_base.txt") docs = loader.load() # 初始化DeepSeek模型 llm = DeepSeek( model_name="deepseek-r1", api_key="YOUR_API_KEY", temperature=0.5 ) # 构建问答链 qa = RetrievalQA.from_chain_type( llm=llm, chain_type="stuff", retriever=docsearch.as_retriever() )
通过浏览器插件实现对话:
// 使用Web API调用本地Ollama服务 async function getResponse(prompt) { const response = await fetch('http://localhost:11434/api/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ model: 'deepseek-r1', prompt }) }); return (await response.json()).response; } // 在网页中展示对话 async function handleSubmit(e) { e.preventDefault(); const prompt = document.getElementById('prompt').value; const response = await getResponse(prompt); document.getElementById('chatlog').innerHTML += `
`; }
性能优化:
本地部署建议使用 NVIDIA H800/A100 GPU,启用 FP8 精度。
通过环境变量OLLAMA_CACHE_DIR
调整模型缓存路径。
优先使用缓存(cache_hit
计费更低)。
对长文本启用流式输出(stream: true
)。
遵循 DeepSeek 开源协议(需在项目中声明引用)。
敏感数据避免通过 API 传输,优先本地部署。
通过以上方式,开发者可根据项目需求选择轻量级 API 调用或深度定制化方案,快速将 DeepSeek 的 AI 能力集成到现有系统中。