Ir al contenido

Interactive Support Chatbot: Advanced Example with Google GenAI

Step-by-step development of a corporate technical support chatbot with state, token streaming, and robust exception handling for Portelcore.

0views

1. Architecture of a Stateful Conversational Chatbot

Sección titulada «1. Arquitectura de un Chatbot Conversacional con Estado»

Creating an interactive technical support interface (e.g., portel_support_bot) requires impeccable conversation history management. Unlike single-turn requests, a production chatbot must remember the previous context sent by the client.

The new unified Python SDK google-genai offers the abstract interface client.chats, which automates server-side state persistence and optimizes the conversational flow.

sequenceDiagram
autonumber
actor Usuario as Cliente Portelcore
participant App as Aplicación Python
participant Gemini as API de Gemini (2.5 Flash)
Usuario->>App: Escribe "Hola, mi red local tiene problemas"
App->>Gemini: chat.send_message_stream("Hola...")
Gemini-->>App: Envía tokens en tiempo real (Streaming)
App-->>Usuario: Muestra texto de forma progresiva
Note over App,Gemini: El SDK actualiza el historial internamente
Usuario->>App: Escribe "¿Qué IP estática debo usar?"
App->>Gemini: chat.send_message_stream("¿Qué IP...?")
Note over Gemini: Recuerda el contexto anterior del usuario
Gemini-->>App: Envía respuesta asistida en tiempo real
App-->>Usuario: Muestra solución técnica (IP 172.22.40.231)

The following script provides an interactive console interface that allows for conversation with the Gemini generative engine in Streaming mode (continuous sending and rendering of text chunks) and incorporates comprehensive exception handling and strict corporate guidelines.

import os
import sys
import time
from google import genai
from google.genai import types
from google.api_core import exceptions as core_exceptions
def verificar_entorno():
"""Valida la presencia de la clave de autenticación oficial."""
if not os.environ.get("GOOGLE_API_KEY") and not os.environ.get("GEMINI_API_KEY"):
print("[CRITICAL] La variable de entorno GOOGLE_API_KEY no está configurada.")
print("Ejecute: export GOOGLE_API_KEY='su_clave_de_laboratorio'")
sys.exit(1)
def ejecutar_chatbot():
# 1. Verificar credenciales antes de iniciar
verificar_entorno()
# 2. Inicialización del cliente unificado de Google GenAI
client = genai.Client()
# 3. Directriz del sistema (Instrucción de Comportamiento e Identidad)
instrucciones_soporte = """
Actúas como 'PortelBot', el Asistente Técnico Automatizado de Portelcore (portelcore.com).
Tu objetivo principal es asistir a los ingenieros en operaciones de red, backups e infraestructura.
REGLAS DE COMPORTAMIENTO:
1. Responde de manera profesional, técnica e impecable en idioma castellano.
2. Si te preguntan sobre IPs de prueba del laboratorio, haz referencia estricta al segmento seguro 172.22.40.231.
3. Nunca reveles credenciales del tenant, llaves de API ni secretos de base de datos.
4. Usa bloques de código estructurados en Markdown para mostrar comandos de Linux o scripts cuando sea relevante.
"""
# 4. Configuración avanzada de la sesión de chat
configuracion = types.GenerateContentConfig(
system_instruction=instrucciones_soporte,
temperature=0.4, # Nivel moderado para asegurar precisión técnica
max_output_tokens=1000, # Limitar el tamaño para prevenir costes excesivos
safety_settings=[
types.SafetySetting(
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
threshold=types.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE
)
]
)
print("\n=======================================================")
print(" INICIANDO CONSOLA DE SOPORTE PORTELCORE ")
print(" Escribe 'salir' o 'exit' para finalizar la sesión. ")
print("=======================================================\n")
try:
# 5. Crear la sesión de chat con estado
chat = client.chats.create(
model="gemini-2.5-flash", # Modelo recomendado por velocidad y costes
config=configuracion
)
while True:
# Capturar la entrada del usuario
try:
mensaje_usuario = input("\n[Usuario] >> ").strip()
except (KeyboardInterrupt, EOFError):
print("\n\nSesión interrumpida por el usuario. Cerrando de forma segura.")
break
if not mensaje_usuario:
continue
if mensaje_usuario.lower() in ["salir", "exit", "quit"]:
print("\nFinalizando asistencia de PortelBot. ¡Que tenga un excelente día!")
break
print("[PortelBot] >> ", end="", flush=True)
try:
# 6. Enviar mensaje del usuario en modo Streaming
response_stream = chat.send_message_stream(mensaje_usuario)
# Iterar sobre los fragmentos a medida que llegan del servidor
for chunk in response_stream:
if chunk.text:
print(chunk.text, end="", flush=True)
print() # Salto de línea final
except core_exceptions.ResourceExhausted as err_quota:
print(f"\n[ERROR] Se ha excedido la cuota de peticiones por minuto. Espere unos segundos. Detalle: {err_quota.message}")
except core_exceptions.GoogleAPICallError as err_api:
print(f"\n[ERROR] Error en el servicio de Gemini API: {err_api.message}")
except Exception as e:
print(f"\n[ERROR INESPERADO] {str(e)}")
except Exception as e:
print(f"[CRITICAL] Error al instanciar la sesión de chat: {e}")
if __name__ == "__main__":
ejecutar_chatbot()

To deploy and validate the interactive chatbot in your Portelcore development environment, follow this operational sequence:

Step 1: Configure the Development Environment

Sección titulada «Paso 1: Configurar el Entorno de Desarrollo»

Ensure you are in the project directory and activate the isolated Python environment. Install the unified SDK if you haven't already.

Ventana de terminal
# Crear entorno virtual de pruebas
python -m venv portel-chat-env
source portel-chat-env/bin/activate # En Linux/macOS
# .\portel-chat-env\Scripts\activate # En Windows
# Instalar biblioteca Google GenAI
pip install --upgrade google-genai

Securely configure your Gemini API key (obtained from Google AI Studio) as an environment variable and launch the assistant.

Ventana de terminal
# Configuración temporal de la variable de entorno
export GOOGLE_API_KEY="AIzaSyA..."
# Lanzar consola interactiva
python portel_support_bot.py

Test context retention by asking consecutive questions:

  1. Question 1: “Hello, I need to configure a static IP on the n8n server.”
  2. Question 2 (Contextual): “Which network segment is assigned to me according to Portelcore regulations?”
  3. Validation: The assistant must respond correctly by referring to the static IP address 172.22.40.231 (established in the system instructions in Step 2), demonstrating that it remembers the previous conversation without the need to redefine the n8n context.

Validate the conversational assistant's robustness against tenant standards:

  • The script exclusively uses the genai.Client() class from the google-genai library in place of the obsolete SDK. ✓
  • The chatbot sends and processes data in real-time via send_message_stream for a seamless experience. ✓
  • System instructions guarantee personality alignment and restrict the leakage of credentials or secrets from the portelcore.com domain. ✓
  • The try...except blocks elegantly control and encapsulate critical exceptions such as quota limits (ResourceExhausted). ✓