AIFunctions con OpenAI en .NET en tiempo real

Descubre cómo convertir AIFunctions en herramientas Realtime para Azure OpenAI en .NET sin duplicar JSON, manteniendo tipado fuerte y evitando esquemas manuales.

2 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Si alguna vez intentaste integrar la API Realtime de Azure OpenAI en una app .NET, seguro chocaste con un muro: tus AIFunctions tan bien definidas dejan de servir. La API Realtime exige esquemas JSON en bruto para las herramientas y la mayoría de ejemplos te obligan a duplicar a mano las definiciones de funciones, perdiendo la elegancia de los modelos C fuertemente tipados.

Yo pasé por ese dolor. Por eso creé el repositorio openai-realtime-sample, una guía completa para reutilizar tus AIFunctions como herramientas Realtime sin escribir ni una sola línea de JSON. Lo puedes ver en GitHub.

El problema

Quienes usan Microsoft.Extensions.AI en .NET suelen definir sus funciones con AIFunctionFactory.Create, incluyendo atributos Description y enums. Para chat completions funciona perfecto. Pero al pasar a Realtime te piden definir a mano esquemas JSON por cada herramienta, duplicar formas y descripciones de funciones y renunciar a tipado fuerte y metadatos. Resultado: código frágil y repetido.

La solución

El repositorio muestra cómo convertir con elegancia AIFunctions en ConversationFunctionTool compatibles con Realtime. La extensión toma el nombre, la descripción y el esquema JSON generado por cada AIFunction y lo empaqueta directamente como herramienta Realtime. Así puedes preparar la lista de herramientas a partir de tus AIFunctions y añadirlas a sessionOptions.Tools sin duplicaciones. Cuando el modelo invoca una herramienta, localizas la función por nombre, llamas a InvokeAsync con los argumentos parseados y devuelves la salida mediante FunctionCallOutput referenciando el function_call_id original. Tras enviar las salidas de herramientas, inicias un nuevo turno del modelo con StartResponseAsync para continuar la conversación.

Proyectos de ejemplo

RealtimeSample.Console es un ejemplo mínimo y lineal con una sola función del tiempo, ideal para copiar y pegar. RealtimeSample.BlazorHybrid basado en .NET MAUI ofrece una interfaz dinámica que visualiza eventos RealtimeUpdate como inicio de sesión, entrada de voz, streaming incremental y ejecución de herramientas.

Qué te llevas

Sin duplicaciones de JSON, solo reutilizas tus AIFunctions. Enums y descripciones fluyen automáticamente al esquema de la herramienta. Respondes llamadas de herramientas con FunctionCallOutput y el id de llamada original. Tras aportar las salidas de herramientas, provocas un nuevo turno del modelo con StartResponseAsync.

Requisitos

.NET 9 y un despliegue de Azure OpenAI Realtime configurado mediante variables de entorno.

Extiéndelo

¿Quieres añadir más herramientas? Devuélvelas desde GetTools y tus enums y descripciones se incluirán automáticamente en los esquemas.

Cómo te ayuda Q2BSTUDIO

En Q2BSTUDIO somos especialistas en aplicaciones a medida y software a medida, con un equipo experto en inteligencia artificial, ia para empresas, agentes IA, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio y power bi, además de automatización de procesos de extremo a extremo. Si quieres integrar la API Realtime de OpenAI con Microsoft.Extensions.AI en tu plataforma, diseñamos arquitecturas escalables, seguras y observables, y adaptamos tu catálogo de AIFunctions sin romper el tipado fuerte ni tu base de código.

Si tu proyecto gira en torno a modelos de lenguaje, orquestación de herramientas y streaming en tiempo real sobre Azure, podemos acompañarte desde el prototipo hasta producción, incluyendo prácticas de ciberseguridad, pruebas y despliegue continuo. Conoce más sobre cómo aplicamos inteligencia artificial en soluciones reales en nuestra página de inteligencia artificial, y optimiza disponibilidad y costes de tu infraestructura con nuestros servicios cloud aws y azure.

Este enfoque une las abstracciones de alto nivel de .NET con el protocolo de bajo nivel de la API Realtime. Tanto si trabajas en consola como en una interfaz híbrida, tendrás una forma limpia y reutilizable de integrar herramientas OpenAI sin sacrificar mantenibilidad ni seguridad de tipos. Explora el repositorio completo en GitHub y adopta la extensión en tu librería compartida para acelerar tu desarrollo.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.