Un servicio API con capacidades de IA construido con Azure Functions, LangGraph y PostgreSQL que proporciona gestión inteligente de flujo de conversación y validación de respuestas para la aplicación Interview GPT.
- ¿Qué es Interview GPT AI API?
- Características Principales
- Arquitectura del Sistema
- Guía de Instalación
- Documentación de la API
- Arquitectura Técnica
- Despliegue en Producción
- Contribuciones
- Autores
Interview GPT es un proyecto compuesto por tres repositorios:
- AI API: EL-BID/Interview-GPT-AI-API
- Backend: EL-BID/Interview-GPT-backend
- Interfaz Web (UI): EL-BID/Interview-GPT-UI
Interview GPT AI API es un servicio con capacidades de IA diseñado para proporcionar capacidades de entrevistas conversacionales inteligentes para la aplicación Interview GPT. El sistema aprovecha las capacidades de IA para proporcionar:
- Flujo de Entrevista Inteligente: Proceso de entrevista automatizado con preguntas conscientes del contexto usando LangGraph
- Validación de Respuestas: Validación impulsada por IA para asegurar respuestas completas y relevantes
- Soporte Multiidioma: Las entrevistas se pueden realizar en múltiples idiomas con detección dinámica de idioma
- Persistencia de Conversación: Sistema de checkpoints basado en PostgreSQL para gestión del estado de conversación
- Manejo de Filtros de Contenido: Filtrado automático de contenido y reformulación de mensajes para interacciones apropiadas
- Gestión de Entrevistas: Gestión completa del ciclo de vida de entrevistas con checkpoints
La plataforma está construida con una arquitectura de microservicios usando Azure Functions.
- Flujo de Conversación Inteligente: Flujo de trabajo basado en LangGraph con preguntas de seguimiento automatizadas
- Validación de Respuestas: Evaluación de completitud y validación de contexto impulsada por IA
- Soporte Multiidioma: Detección dinámica de idioma y mantenimiento consistente del idioma
- Persistencia de Conversación: Checkpoints de PostgreSQL para recuperación de conversación y gestión de estado
- Manejo de Filtros de Contenido: Detección automática y reformulación de contenido inapropiado
- Gestión de Entrevistas: Ciclo de vida completo de entrevistas con gestión de checkpoints
- Backend: Azure Functions con Python
- IA/ML: Azure OpenAI con LangGraph para flujo de conversación inteligente
- Base de Datos: PostgreSQL con agrupación de conexiones asíncronas para persistencia de datos
- Gestión de Estado: Checkpoints de LangGraph para persistencia del estado de conversación
- Filtrado de Contenido: Filtrado de contenido con capacidades de reformulación automática
- Python 3.8 o superior
- Azure Functions Core Tools para desarrollo local
- PostgreSQL base de datos (versión 12 o superior)
- Azure OpenAI servicio con acceso API apropiado
Crea un archivo .env en la raíz del proyecto con las siguientes variables:
# Configuración de Azure OpenAI
AZURE_OPEN_AI_ENDPOINT=tu_endpoint_azure_openai
AZURE_OPENAI_API_KEY=tu_clave_api_azure_openai
AZURE_OPENAI_API_VERSION=2024-02-15-preview
AZURE_OPENAI_API_INSTANCE_NAME=tu_nombre_instancia
AZURE_OPENAI_API_BASE_PATH=tu_ruta_base
AZURE_DEPLOYMENT_NAME=tu_nombre_despliegue
# Configuración de Base de Datos PostgreSQL
POSTGRES_USER=tu_usuario_db
POSTGRES_PASSWORD=tu_contraseña_db
POSTGRES_HOST=tu_host_db
POSTGRES_PORT=5432
POSTGRES_DB=tu_nombre_base_datos
POSTGRES_SSLMODE=prefergit clone <url-del-repositorio>
cd interview-gpt-ai-api
pip install -r requirements.txtfunc startLa API estará disponible en http://localhost:7071.
Ejecuta una conversación de entrevista inteligente usando flujo de trabajo LangGraph con validación automatizada de respuestas y preguntas de seguimiento.
Cuerpo de la Solicitud:
{
"thread_id": "string (requerido)",
"question": {
"question": "string",
"context": "string",
"question_number": 1,
"total_questions": 5
},
"user_data": {
"user_name": "string"
},
"user_response": "string",
"description": "string (opcional)",
"language": "string (por defecto: 'es')"
}Respuesta:
{
"status": "success|error",
"thread_id": "string",
"is_complete": "boolean|string",
"validation_result": "string",
"current_question": {
"question": "string",
"context": "string",
"question_number": 1,
"total_questions": 5
},
"messages": [
{
"role": "user|assistant",
"content": "string"
}
]
}Características:
- Flujo de conversación inteligente basado en LangGraph
- Validación de respuestas y verificación de completitud impulsada por IA
- Soporte multiidioma con detección dinámica
- Preguntas de seguimiento conscientes del contexto
- Manejo de filtros de contenido con reformulación automática
- Persistencia de estado de conversación con checkpoints
Recupera checkpoints de entrevista para un hilo específico, permitiendo recuperación de conversación y gestión de estado para entrevistas LangGraph.
Parámetros de Consulta:
thread_id(requerido): El identificador del hilo de entrevista
Respuesta:
{
"status": "success|error",
"thread_id": "string",
"checkpoints": [
{
"id": "string",
"timestamp": "string",
"is_complete": "boolean",
"current_question": {
"question": "string",
"context": "string",
"question_number": 1,
"total_questions": 5
},
"messages": [
{
"role": "user|assistant",
"content": "string"
}
]
}
],
"last_checkpoint": "object"
}Genera texto de IA basado en diferentes tipos de prompts según el caso de uso. Este endpoint es versátil y se utiliza en múltiples escenarios:
Cuerpo de la Solicitud:
{
"prompt": "string (varía según el caso de uso)",
"temperature": 0.7
}Casos de Uso:
-
Generación de Resultado Final (User Side):
- Recibe el prompt del administrador concatenado con el historial completo de la entrevista
- Genera el texto indicado por el admin (reporte, reseña, análisis, etc.) una vez que finaliza la entrevista
- Utiliza toda la información recopilada durante la conversación
-
Mejora de Texto Generado (User Side):
- Recibe directamente un input del usuario para mejorar el texto previamente generado
- Utiliza IA para refinar y mejorar el resultado anterior
- Permite iteraciones y mejoras continuas del documento
-
Mejora del Prompt del Admin (Admin Side):
- Recibe el prompt original del administrador
- Utiliza IA para hacer el prompt más claro, específico y efectivo
- Ayuda a optimizar las instrucciones para mejores resultados
Respuesta: Stream de eventos enviados por servidor con el texto generado o mejorado por IA según el caso de uso específico.
Este endpoint permite a los usuarios hacer preguntas sobre entrevistas completadas y obtener respuestas contextuales basadas en la información de todas las entrevistas proporcionada.
Cuerpo de la Solicitud:
{
"inputUser": "string",
"systemMessage": "string (opcional)",
"interviewData": "object",
"messageHistory": [
{
"role": "user|assistant",
"content": "string"
}
],
"temperature": 0.7
}Respuesta: Stream de eventos enviados por servidor con respuestas de IA contextuales basadas en datos de entrevista.
Caso de Uso:
- Panel de administración para analizar resultados de entrevistas
- Interfaz de chat para discutir hallazgos de entrevistas
- Preguntas y respuestas contextuales sobre respuestas específicas de entrevistas
- Análisis de seguimiento y generación de insights
- Chat contextual que utiliza la información completa de todas las entrevistas para proporcionar respuestas informadas
El sistema de entrevista implementa un flujo de trabajo basado en LangGraph:
Nodos:
- validate_response: Analiza la completitud de la conversación y cobertura del contexto
- interviewer: Genera preguntas de seguimiento inteligentes basadas en el contexto
- farewell: Maneja la finalización de la conversación y gestión de transiciones
Flujo:
START → validate_response → [condicional] → interviewer/farewell → END
Gestión de Estado:
- InterviewState: Rastrea el estado de la conversación, preguntas y resultados de validación
- Checkpoints: Persistencia de PostgreSQL para recuperación de conversación
- Historial de Mensajes: Mantenimiento completo del contexto de conversación
El sistema utiliza PostgreSQL con agrupación de conexiones asíncronas:
- Agrupación de Conexiones: AsyncConnectionPool con 20 conexiones máximas
- Checkpointer: AsyncPostgresSaver para persistencia de estado de LangGraph
La API implementa mecanismos de filtrado de contenido en casos donde Azure OpenAI detecta contenido inapropiado incorrectamente:
- Detección Automática: Identifica contenido inapropiado usando filtros de Azure OpenAI
- Reformulación de Mensajes: Reformula automáticamente contenido problemático que realmente no es inapropiado
- Adaptación de Prompt del Sistema: Ajusta las instrucciones del sistema cuando es necesario
- Lógica de Reintento: Múltiples intentos con diferentes enfoques para manejo de contenido
# Construir y desplegar en Azure Functions
func azure functionapp publish <nombre-función-app># Iniciar servidor de desarrollo local
func start
# Probar endpoints
curl -X POST http://localhost:7071/api/interview_chat \
-H "Content-Type: application/json" \
-d '{"thread_id": "test-123", "question": {...}}'Gracias por tu interés en mejorar Interview GPT AI API.
Actualmente no aceptamos pull requests directos a este repositorio. Sin embargo, si deseas explorar el código, desarrollar nuevas funcionalidades o proponer mejoras, te animamos a crear tu propia versión del proyecto (mediante fork o clonación).
Si tienes sugerencias, detectaste algún error o deseas compartir una propuesta de mejora, no dudes en escribirnos a:
techlab@iadb.org
Estaremos encantados de conocer tus ideas y colaborar en su desarrollo.
Alejandra Pérez Ortega
Jhoselyn Pajuelo Villanueva
Ignacio Cerrato
José Daniel Zárate
An AI-powered API service built with Azure Functions, LangGraph, and PostgreSQL that provides intelligent conversation flow management and response validation for the Interview GPT application.
- What is Interview GPT AI API?
- Key Features
- System Architecture
- Installation Guide
- API Documentation
- Technical Architecture
- Production Deployment
- Contributions
- Authors
Interview GPT AI API is an AI-powered service designed to provide intelligent conversational interview capabilities for the Interview GPT application. The system leverages AI capabilities to provide:
- Intelligent Interview Flow: Automated interview process with context-aware questioning using LangGraph
- Response Validation: AI-powered validation to ensure complete and relevant responses
- Multi-language Support: Interviews can be conducted in multiple languages with dynamic language detection
- Conversation Persistence: PostgreSQL-based checkpoint system for conversation state management
- Content Filter Handling: Automatic content filtering and message rephrasing for appropriate interactions
- Streaming Responses: Real-time streaming for AI chat interactions
- Interview Management: Complete interview lifecycle management with checkpoints
The platform is built with a microservices architecture using Azure Functions, providing scalability and reliability for production environments.
- Intelligent Conversation Flow: LangGraph-based workflow with automated follow-up questions
- Response Validation: AI-powered completeness assessment and context validation
- Multi-language Support: Dynamic language detection and consistent language maintenance
- Conversation Persistence: PostgreSQL checkpoints for conversation recovery and state management
- Content Filter Handling: Automatic detection and rephrasing of inappropriate content
- Streaming Responses: Real-time server-sent events for AI chat interactions
- Interview Management: Complete interview lifecycle with checkpoint management
- Error Handling: Comprehensive error handling with graceful degradation
- Monitoring and Logging: Structured logging and performance monitoring
- Backend: Azure Functions with Python for serverless computing
- AI/ML: Azure OpenAI with LangGraph for intelligent conversation flow
- Database: PostgreSQL with async connection pooling for data persistence
- Streaming: Server-sent events for real-time response delivery
- State Management: LangGraph checkpoints for conversation state persistence
- Content Filtering: Advanced content filtering with automatic rephrasing capabilities
- Python 3.8 or higher
- Azure Functions Core Tools for local development
- PostgreSQL database (version 12 or higher)
- Azure OpenAI service with appropriate API access
- Git 2.34 or higher (for repository cloning)
Create a .env file in the project root with the following variables:
# Azure OpenAI Configuration
AZURE_OPEN_AI_ENDPOINT=your_azure_openai_endpoint
AZURE_OPENAI_API_KEY=your_azure_openai_api_key
AZURE_OPENAI_API_VERSION=2024-02-15-preview
AZURE_OPENAI_API_INSTANCE_NAME=your_instance_name
AZURE_OPENAI_API_BASE_PATH=your_base_path
AZURE_DEPLOYMENT_NAME=your_deployment_name
# PostgreSQL Database Configuration
POSTGRES_USER=your_db_user
POSTGRES_PASSWORD=your_db_password
POSTGRES_HOST=your_db_host
POSTGRES_PORT=5432
POSTGRES_DB=your_database_name
POSTGRES_SSLMODE=prefergit clone <repository-url>
cd interview-gpt-ai-api
pip install -r requirements.txtfunc startThe API will be available at http://localhost:7071.
Executes an intelligent interview conversation using LangGraph workflow with automated response validation and follow-up questions.
Request Body:
{
"thread_id": "string (required)",
"question": {
"question": "string",
"context": "string",
"question_number": 1,
"total_questions": 5
},
"user_data": {
"user_name": "string"
},
"user_response": "string",
"description": "string (optional)",
"language": "string (default: 'es')"
}Response:
{
"status": "success|error",
"thread_id": "string",
"is_complete": "boolean|string",
"validation_result": "string",
"current_question": {
"question": "string",
"context": "string",
"question_number": 1,
"total_questions": 5
},
"messages": [
{
"role": "user|assistant",
"content": "string"
}
]
}Features:
- LangGraph-based intelligent conversation flow
- AI-powered response validation and completion checking
- Multi-language support with dynamic detection
- Context-aware follow-up questions
- Content filter handling with automatic rephrasing
- Conversation state persistence with checkpoints
Retrieves interview checkpoints for a specific thread, enabling conversation recovery and state management for LangGraph interviews.
Query Parameters:
thread_id(required): The interview thread identifier
Response:
{
"status": "success|error",
"thread_id": "string",
"checkpoints": [
{
"id": "string",
"timestamp": "string",
"is_complete": "boolean",
"current_question": {
"question": "string",
"context": "string",
"question_number": 1,
"total_questions": 5
},
"messages": [
{
"role": "user|assistant",
"content": "string"
}
]
}
],
"last_checkpoint": "object"
}Generates AI text based on different types of prompts according to the use case. This endpoint is versatile and is used in multiple scenarios:
Request Body:
{
"prompt": "string (varies according to use case)",
"temperature": 0.7
}Use Cases:
-
Final Result Generation (User Side):
- Receives the administrator's prompt concatenated with the complete interview history
- Generates the text indicated by the admin (report, review, analysis, etc.) once the interview is completed
- Uses all information collected during the conversation
-
Generated Text Improvement (User Side):
- Receives direct input from the user to improve previously generated text
- Uses AI to refine and improve the previous result
- Allows continuous iterations and improvements of the document
-
Admin Prompt Improvement (Admin Side):
- Receives the original administrator's prompt
- Uses AI to make the prompt clearer, more specific and effective
- Helps optimize instructions for better results
Response: Server-sent events stream with AI-generated or improved text according to the specific use case.
Enables AI-powered chat about interview data with context awareness. This endpoint allows users to ask questions about completed interviews and get contextual responses.
Request Body:
{
"inputUser": "string",
"systemMessage": "string (opcional)",
"interviewData": "object",
"messageHistory": [
{
"role": "user|assistant",
"content": "string"
}
],
"temperature": 0.7
}Response: Server-sent events stream with contextual AI responses based on interview data.
Use Case:
- Admin panel for analyzing interview results
- Chat interface for discussing interview findings
- Contextual Q&A about specific interview responses
- Follow-up analysis and insights generation
- Chat contextual that utilizes the complete information of all interviews to provide informed responses
The interview system implements a LangGraph-based workflow:
Nodes:
- validate_response: Analyzes conversation completeness and context coverage
- interviewer: Generates intelligent follow-up questions based on context
- farewell: Handles conversation completion and transition management
Flow:
START → validate_response → [conditional] → interviewer/farewell → END
State Management:
- InterviewState: Tracks conversation state, questions, and validation results
- Checkpoints: PostgreSQL persistence for conversation recovery
- Message History: Complete conversation context maintenance
The system utilizes PostgreSQL with async connection pooling:
- Connection Pool: AsyncConnectionPool with 20 maximum connections
- Checkpointer: AsyncPostgresSaver for LangGraph state persistence
- Row Factory: dict_row for simplified data access
- SSL Mode: Configurable SSL connection settings for security
The API implements content filtering mechanisms where the Azure OpenAI API detect an innapropiate content incorrectly:
- Automatic Detection: Identifies inappropriate content using Azure OpenAI filters
- Message Rephrasing: Automatically reformulates problematic content that is not really innapropiate
- System Prompt Adaptation: Adjusts system instructions when needed
- Retry Logic: Multiple attempts with different approaches for content handling
# Build and deploy to Azure Functions
func azure functionapp publish <function-app-name># Start local development server
func start
# Test endpoints
curl -X POST http://localhost:7071/api/interview_chat \
-H "Content-Type: application/json" \
-d '{"thread_id": "test-123", "question": {...}}'- Structured Logging: JSON-formatted logs for easy parsing and analysis
- Performance Metrics: Response time and throughput monitoring
- Error Tracking: Detailed error logging with context information
- Health Checks: Endpoint availability monitoring for production environments
Thank you for your interest in improving Interview GPT AI API.
Currently, we do not accept direct pull requests to this repository. However, if you wish to explore the code, develop new features, or propose improvements, we encourage you to create your own version of the project (through fork or cloning).
If you have suggestions, detect any errors, or wish to share improvement proposals, please do not hesitate to contact us at:
techlab@iadb.org
We will be delighted to learn about your ideas and collaborate on their development.
Alejandra Pérez Ortega
Jhoselyn Pajuelo Villanueva
Ignacio Cerrato
José Daniel Zárate
This project is licensed under the MIT License. See the LICENSE file for more details.
Copyright © [2025]. Inter-American Development Bank ("IDB"). Authorized Use.
The procedures and results obtained based on the execution of this software are those programmed by the developers and do not necessarily reflect the views of the IDB, its Board of Executive Directors or the countries it represents.
Copyright © [2025]. Banco Interamericano de Desarrollo ("BID"). Uso Autorizado.
Los procedimientos y resultados obtenidos con la ejecución de este software son los programados por los desarrolladores y no reflejan necesariamente las opiniones del BID, su Directorio Ejecutivo ni los países que representa.
Copyright © [2025]. Inter-American Development Bank ("IDB"). The Support and Usage Documentation is licensed under the Creative Commons License CC-BY 4.0 license. The opinions expressed in the Support and Usage Documentation are those of its authors and do not necessarily reflect the opinions of the IDB, its Board of Executive Directors, or the countries it represents.
Copyright © [2025]. Banco Interamericano de Desarrollo (BID). La Documentación de Soporte y Uso está licenciada bajo la licencia Creative Commons CC-BY 4.0. Las opiniones expresadas en la Documentación de Soporte y Uso son las de sus autores y no reflejan necesariamente las opiniones del BID, su Directorio Ejecutivo ni los países que representa.
The Software may include features which use, are powered by, or are an artificial intelligence system (“AI-Powered Services”), and as a result, the services provided via the Software may not be completely error-free or up to date. Additionally, the User acknowledges that due to the incorporation of AI-Powered Services in the Software, the Software may not dynamically (in “real time”) retrieve information and that, consequently, the output provided to the User may not account for events, updates, or other facts that have occurred or become available after the Software was trained. Accordingly, the User acknowledges that the use of the Software, and that any actions taken or reliance on such products, are at the User’s own risk, and the User acknowledges that the User must independently verify any information provided by the Software.
El Software puede incluir funciones que utilizan, están impulsadas por o son un sistema de inteligencia artificial (“Servicios Impulsados por IA”) y, como resultado, los servicios proporcionados a través del Software pueden no estar completamente libres de errores ni actualizados. Además, el Usuario reconoce que, debido a la incorporación de Servicios Impulsados por IA en el Software, este puede no recuperar información dinámicamente (en “tiempo real”) y que, en consecuencia, la información proporcionada al Usuario puede no reflejar eventos, actualizaciones u otros hechos que hayan ocurrido o estén disponibles después del entrenamiento del Software. En consecuencia, el Usuario reconoce que el uso del Software, y que cualquier acción realizada o la confianza depositada en dichos productos, se realiza bajo su propio riesgo, y reconoce que debe verificar de forma independiente cualquier información proporcionada por el Software.