openai_service.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import json
  2. from typing import List
  3. from fastapi import HTTPException
  4. from openai import OpenAI
  5. from config.settings import OPENAI_API_KEY
  6. from models.chat import Message
  7. from models.user import User
  8. from services.data_service import data_bg_loaded
  9. from logging import getLogger
  10. from services.openai_service.openai_tools import tools_list, tools
  11. # Initialize OpenAI client
  12. openai_client = OpenAI(api_key=OPENAI_API_KEY)
  13. logger = getLogger(__name__)
  14. async def generate_completion(messages_array: List[dict], user: User) -> str:
  15. """Generate OpenAI chat completion"""
  16. if not OPENAI_API_KEY:
  17. logger.error("Error: OpenAI API key is not configured.")
  18. raise HTTPException(status_code=500, detail="OpenAI API key not configured on server.")
  19. data_for_prompt = [
  20. f'{{"pregunta": "{item.get("q", "")}", "respuesta": "{item.get("ans", "")}"}}'
  21. for item in data_bg_loaded
  22. ]
  23. data_string = "\n".join(data_for_prompt)
  24. preprompt = f"""
  25. Eres un asistente de el bar klein, tu nombre es camilo klein, usas emojis para responder.
  26. y ser carismatico con los cliente.
  27. tus responsabilidades son:
  28. - Responder preguntas sobre el menu de el bar klein
  29. - bromear con los usuarios sobre distintos temas pero siempre redirigir la conversacion al bar klein
  30. - Proporcionar información sobre el menú de el bar klein
  31. - Proporcionar recomendaciones sobre el menú de el bar klein
  32. - Proporcionar información sobre la comida de el bar klein
  33. - No puedes tomar pedidos de clientes, solo informar
  34. - puedes recibir feedback de los clientes, y usar la herramienta feedback para enviar el feedback
  35. - respuestas cortas estilo app de mensajeria
  36. - si el usuario te pregunta por tu nombre, di que eres camilo klein
  37. para esto usaras los siguientes datos:
  38. {data_string}
  39. """
  40. processed_messages: List[dict] = [{"role": "system", "content": preprompt}]
  41. processed_messages.append(
  42. {"role": "user", "content": json.dumps(messages_array)}
  43. )
  44. try:
  45. completion = openai_client.chat.completions.create(
  46. model="gpt-4o-mini",
  47. messages=processed_messages, # type: ignore (OpenAI lib expects list of specific dicts)
  48. temperature=0.3,
  49. tools=tools_list,
  50. tool_choice="auto",
  51. )
  52. calls = completion.choices[0].message.tool_calls
  53. if calls:
  54. logger.info(f"Tool calls: {calls}")
  55. for call in calls:
  56. if call.function.name in tools:
  57. tool_function = tools[call.function.name]
  58. tool_args = json.loads(call.function.arguments)
  59. logger.info(f"Calling tool: {call.function.name} with args: {tool_args}")
  60. tool_response = tool_function(name=user.name, email=user.email, **tool_args)
  61. logger.info(f"Tool response: {tool_response}")
  62. completion.choices[0].message.content = tool_response
  63. else:
  64. logger.warning(f"Tool {call.function.name} not found in tools dictionary.")
  65. response_content = completion.choices[0].message.content
  66. return response_content if response_content else "-1"
  67. except Exception as e:
  68. logger.error(f"Error calling OpenAI: {e}")
  69. raise HTTPException(status_code=500, detail="Error al procesar tu solicitud con OpenAI.")