llm_backend.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import logging
  2. from typing import List
  3. from openai import OpenAI, Stream
  4. from openai.types.chat import ChatCompletionChunk, ChatCompletion
  5. class LLMBackend:
  6. """
  7. openai chat 接口封装
  8. """
  9. def __init__(self, base_url: str, api_key) -> None:
  10. self.base_url = base_url + "/" if base_url else None
  11. self.api_key = api_key
  12. self.client = OpenAI(base_url=self.base_url, api_key=self.api_key)
  13. def run(
  14. self,
  15. messages: List,
  16. model: str,
  17. tools: List = None,
  18. tool_choice="auto",
  19. stream=False,
  20. stream_options=None,
  21. extra_body=None,
  22. temperature=None,
  23. top_p=None,
  24. response_format=None,
  25. ) -> ChatCompletion | Stream[ChatCompletionChunk]:
  26. chat_params = {
  27. "messages": messages,
  28. "model": model,
  29. "stream": stream,
  30. }
  31. if extra_body:
  32. model_params = extra_body.get("model_params")
  33. if model_params:
  34. if "n" in model_params:
  35. raise ValueError("n is not allowed in model_params")
  36. chat_params.update(model_params)
  37. stream_options_params = extra_body.get("stream_options")
  38. if stream_options_params:
  39. chat_params["stream_options"] = {
  40. "include_usage": bool(stream_options_params["include_usage"])
  41. }
  42. if stream_options:
  43. if isinstance(stream_options, dict):
  44. if "include_usage" in stream_options:
  45. chat_params["stream_options"] = {
  46. "include_usage": bool(stream_options["include_usage"])
  47. }
  48. if temperature:
  49. chat_params["temperature"] = temperature
  50. if top_p:
  51. chat_params["top_p"] = top_p
  52. if tools:
  53. chat_params["tools"] = tools
  54. chat_params["tool_choice"] = tool_choice if tool_choice else "auto"
  55. if (
  56. isinstance(response_format, dict)
  57. and response_format.get("type") == "json_object"
  58. ):
  59. chat_params["response_format"] = {"type": "json_object"}
  60. for message in chat_params["messages"]:
  61. if "content" not in message:
  62. message["content"] = ""
  63. logging.info("chat_params: %s", chat_params)
  64. response = self.client.chat.completions.create(**chat_params)
  65. logging.info("chat_response: %s", response)
  66. return response