| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 |
- import json
- from typing import List
- from fastapi import HTTPException
- from openai import OpenAI
- from config.settings import OPENAI_API_KEY
- from models.chat import Message
- from models.user import User
- from services.data_service import data_bg_loaded
- from logging import getLogger
- from services.openai_service.openai_tools import tools_list, tools
- # Initialize OpenAI client
- openai_client = OpenAI(api_key=OPENAI_API_KEY)
- logger = getLogger(__name__)
- async def generate_completion(messages_array: List[dict], user: User) -> str:
- """Generate OpenAI chat completion"""
- if not OPENAI_API_KEY:
- logger.error("Error: OpenAI API key is not configured.")
- raise HTTPException(status_code=500, detail="OpenAI API key not configured on server.")
- data_for_prompt = [
- f'{{"pregunta": "{item.get("q", "")}", "respuesta": "{item.get("ans", "")}"}}'
- for item in data_bg_loaded
- ]
- data_string = "\n".join(data_for_prompt)
- preprompt = f"""
- Eres un asistente de el bar klein, tu nombre es camilo klein, usas emojis para responder.
- y ser carismatico con los cliente.
- tus responsabilidades son:
- - Responder preguntas sobre el menu de el bar klein
- - bromear con los usuarios sobre distintos temas pero siempre redirigir la conversacion al bar klein
- - Proporcionar información sobre el menú de el bar klein
- - Proporcionar recomendaciones sobre el menú de el bar klein
- - Proporcionar información sobre la comida de el bar klein
- - No puedes tomar pedidos de clientes, solo informar
- - puedes recibir feedback de los clientes, y usar la herramienta feedback para enviar el feedback
- - respuestas cortas estilo app de mensajeria
- - si el usuario te pregunta por tu nombre, di que eres camilo klein
- para esto usaras los siguientes datos:
- {data_string}
- """
- processed_messages: List[dict] = [{"role": "system", "content": preprompt}]
- processed_messages.append(
- {"role": "user", "content": json.dumps(messages_array)}
- )
- try:
- completion = openai_client.chat.completions.create(
- model="gpt-4o-mini",
- messages=processed_messages, # type: ignore (OpenAI lib expects list of specific dicts)
- temperature=0.3,
- tools=tools_list,
- tool_choice="auto",
- )
- calls = completion.choices[0].message.tool_calls
- if calls:
- logger.info(f"Tool calls: {calls}")
- for call in calls:
- if call.function.name in tools:
- tool_function = tools[call.function.name]
- tool_args = json.loads(call.function.arguments)
- logger.info(f"Calling tool: {call.function.name} with args: {tool_args}")
- tool_response = tool_function(name=user.name, email=user.email, **tool_args)
- logger.info(f"Tool response: {tool_response}")
- completion.choices[0].message.content = tool_response
- else:
- logger.warning(f"Tool {call.function.name} not found in tools dictionary.")
- response_content = completion.choices[0].message.content
- return response_content if response_content else "-1"
- except Exception as e:
- logger.error(f"Error calling OpenAI: {e}")
- raise HTTPException(status_code=500, detail="Error al procesar tu solicitud con OpenAI.")
|