deepseek_service.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. """
  2. DeepSeek AI 服务
  3. """
  4. import httpx
  5. import json
  6. from typing import AsyncGenerator
  7. from utils.config import settings
  8. from utils.logger import logger
  9. class DeepSeekService:
  10. def __init__(self):
  11. self.api_key = settings.deepseek.api_key
  12. self.api_url = settings.deepseek.api_url
  13. self.base_url = f"{self.api_url}/v1"
  14. async def chat(self, messages: list, model: str = "deepseek-chat") -> str:
  15. """同步聊天"""
  16. headers = {
  17. "Authorization": f"Bearer {self.api_key}",
  18. "Content-Type": "application/json"
  19. }
  20. data = {
  21. "model": model,
  22. "messages": messages,
  23. "temperature": 0.7
  24. }
  25. try:
  26. async with httpx.AsyncClient(timeout=120.0) as client:
  27. response = await client.post(
  28. f"{self.base_url}/chat/completions",
  29. headers=headers,
  30. json=data
  31. )
  32. response.raise_for_status()
  33. result = response.json()
  34. return result['choices'][0]['message']['content']
  35. except Exception as e:
  36. logger.error(f"DeepSeek API 调用失败: {e}")
  37. raise
  38. async def stream_chat(self, messages: list, model: str = "deepseek-chat") -> AsyncGenerator[str, None]:
  39. """流式聊天"""
  40. headers = {
  41. "Authorization": f"Bearer {self.api_key}",
  42. "Content-Type": "application/json"
  43. }
  44. data = {
  45. "model": model,
  46. "messages": messages,
  47. "temperature": 0.7,
  48. "stream": True
  49. }
  50. try:
  51. async with httpx.AsyncClient(timeout=120.0) as client:
  52. async with client.stream(
  53. "POST",
  54. f"{self.base_url}/chat/completions",
  55. headers=headers,
  56. json=data
  57. ) as response:
  58. response.raise_for_status()
  59. async for line in response.aiter_lines():
  60. if line.startswith("data: "):
  61. data_str = line[6:]
  62. if data_str == "[DONE]":
  63. break
  64. try:
  65. data_json = json.loads(data_str)
  66. if 'choices' in data_json and len(data_json['choices']) > 0:
  67. delta = data_json['choices'][0].get('delta', {})
  68. content = delta.get('content', '')
  69. if content:
  70. yield content
  71. except json.JSONDecodeError:
  72. continue
  73. except Exception as e:
  74. logger.error(f"DeepSeek 流式 API 调用失败: {e}")
  75. raise
  76. # 全局实例
  77. deepseek_service = DeepSeekService()