LLM_API.py 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. """LLM API 模块
  2. 职责:
  3. 1. 管理与大语言模型的API交互
  4. 2. 处理流式响应
  5. 3. 实现自动重试机制
  6. 4. 处理工具调用检测
  7. """
  8. import json
  9. import time
  10. import requests
  11. from typing import Dict, Optional, Generator
  12. from ..Config.DefaultConfig import DefaultConfig
  13. class LLMAPI:
  14. """大语言模型API封装类"""
  15. def __init__(self, config: Optional[Dict] = None):
  16. """初始化LLM API
  17. 参数:
  18. config: 用户提供的配置字典,会与默认配置合并
  19. """
  20. self.config = DefaultConfig.merge_config(config)['llm_api']
  21. self.session = requests.Session()
  22. def _make_request_headers(self) -> Dict[str, str]:
  23. """生成请求头"""
  24. return {
  25. "Content-Type": "application/json",
  26. "Authorization": f"Bearer {self.config['provider']['api_key']}"
  27. }
  28. def _build_request_data(self, messages: list, tools: Optional[list] = None) -> Dict:
  29. """构建请求数据"""
  30. data = {
  31. "model": self.config['provider']['model_name'],
  32. "messages": messages,
  33. "temperature": self.config['provider']['model_settings']['temperature'],
  34. "max_tokens": self.config['provider']['max_tokens'],
  35. "stream": self.config['stream']
  36. }
  37. if tools and self.config['provider']['model_type']['is_function_call']:
  38. data["tools"] = tools
  39. data["tool_choice"] = "auto"
  40. return data
  41. def _handle_stream_response(self, response) -> Generator[str, None, None]:
  42. """处理流式响应"""
  43. for chunk in response.iter_lines():
  44. if chunk:
  45. decoded = chunk.decode('utf-8')
  46. if decoded.startswith("data: "):
  47. data = decoded[6:]
  48. if data != "[DONE]":
  49. try:
  50. json_data = json.loads(data)
  51. yield json_data
  52. except json.JSONDecodeError:
  53. continue
  54. def call(
  55. self,
  56. messages: list,
  57. tools: Optional[list] = None,
  58. retry_count: int = 0
  59. ) -> Generator[Dict, None, None]:
  60. """调用LLM API
  61. 参数:
  62. messages: 消息列表
  63. tools: 可选工具列表
  64. retry_count: 当前重试次数
  65. 返回:
  66. 生成器,产生流式响应或完整响应
  67. """
  68. url = self.config['provider']['api_url']
  69. headers = self._make_request_headers()
  70. data = self._build_request_data(messages, tools)
  71. try:
  72. response = self.session.post(
  73. url,
  74. headers=headers,
  75. json=data,
  76. stream=self.config['stream'],
  77. timeout=self.config['request_timeout']
  78. )
  79. response.raise_for_status()
  80. if self.config['stream']:
  81. return self._handle_stream_response(response)
  82. else:
  83. return [response.json()]
  84. except requests.exceptions.RequestException as e:
  85. if retry_count < self.config['retry']['times']:
  86. time.sleep(self.config['retry']['delay'])
  87. return self.call(messages, tools, retry_count + 1)
  88. raise Exception(f"API调用失败: {str(e)}")
  89. def detect_tool_call(self, response: Dict) -> Optional[Dict]:
  90. """检测工具调用
  91. 参数:
  92. response: API响应字典
  93. 返回:
  94. 如果检测到工具调用则返回工具信息,否则返回 None
  95. """
  96. if not self.config['provider']['model_type']['is_function_call']:
  97. return None
  98. if "choices" in response and len(response["choices"]) > 0:
  99. choice = response["choices"][0]
  100. if "tool_calls" in choice["delta"]:
  101. return choice["delta"]["tool_calls"]
  102. if "tool_calls" in choice["message"]:
  103. return choice["message"]["tool_calls"]
  104. return None