openai_service.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from typing import Dict, Any, List, Optional
  2. class OpenAICompatibleService:
  3. def __init__(self, http_client):
  4. self.http_client = http_client
  5. def chat_completion(self, chat_id: str, messages: List[Dict[str, Any]],
  6. stream: bool = False, model: str = "model",
  7. extra_body: Dict = None) -> Dict[str, Any]:
  8. endpoint = f"/api/v1/chats_openai/{chat_id}/chat/completions"
  9. data = {
  10. "model": model,
  11. "messages": messages,
  12. "stream": stream
  13. }
  14. if extra_body is not None:
  15. data["extra_body"] = extra_body
  16. response = self.http_client.post(endpoint, json_data=data)
  17. if response.get("code") == 0:
  18. return response.get("data", response)
  19. else:
  20. raise Exception(f"聊天完成失败: {response.get('message', '未知错误')}")
  21. def agent_completion(self, agent_id: str, messages: List[Dict[str, Any]],
  22. stream: bool = False, model: str = "model",
  23. session_id: str = None) -> Dict[str, Any]:
  24. endpoint = f"/api/v1/agents_openai/{agent_id}/chat/completions"
  25. data = {
  26. "model": model,
  27. "messages": messages,
  28. "stream": stream
  29. }
  30. if session_id is not None:
  31. data["session_id"] = session_id
  32. response = self.http_client.post(endpoint, json=data)
  33. if response.get("code") == 0:
  34. return response.get("data", response)
  35. else:
  36. raise Exception(f"代理完成失败: {response.get('message', '未知错误')}")