You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
8 Hrs
11 Min
14 Seg

¿Cómo usar la API REST de Azure OpenAI?

6/21
Resources

How to use the Azure OpenAI Service REST API?

Advances in artificial intelligence, particularly with models such as OpenAI's GPT models, have opened up a range of possibilities for developers interested in integrating these technologies into their applications. Through Azure OpenAI Service, it is possible to access these models through the REST API or using the SDK available for Python and C#. Next, we will address how to employ these tools to consume GPT models effectively.

What are the elements required to consume the REST API?

To interact with GPT models using the Azure OpenAI Service REST API, three key pieces of information are essential:

  • Endpoint: This is the point to which requests will be sent. It can be found in the OpenAI Studio.
  • API Key: The API key allows authenticating requests to the service. Like the endpoint, it is obtained from the Azure OpenAI Studio.
  • Deployed Model: It is crucial to have deployed a model in Azure to be able to query on it. In the OpenAI Studio, within the "Deployments" section, all the available models and their names are listed.

How to create a POST request with Postman?

To make a REST API request, Postman is an ideal tool thanks to its ability to parse and test APIs. Follow these basic steps:

  1. Create a new POST request in Postman.
  2. Query Azure OpenAI Studio to get the endpoint and API key.
  3. Configure the request body in JSON format, specifying the messages that will define the model output. For this example, a simple query will be used, "How many sides does a coin have?"
  4. Include query parameters, such as temperature and cap, which determine the randomness and amplitude of the responses generated by the model.
  5. Finally, when you send the configured request, you will receive a response in JSON format with the information and evaluation of the input and output provided by the model.

How to interact with the Python or C# SDK?

The Azure OpenAI Service SDK makes it easy for you to programmatically integrate the models into your applications. The "view code" section in the OpenAI Studio provides code samples that illustrate how to initiate queries or send prompts to a particular model.

How to configure the SDK for a successful query?

  1. Make sure you have an up-to-date version of the SDK compatible with your environment.
  2. Copy the lines of code suggested by OpenAI Studio into your Jupyter notebook or other development environment.
  3. Define the necessary constants:
    • API base or endpoint
    • Model to use
    • API key, which is recommended to be handled in a safe way, typically using environment variables, although for this example it will be inserted manually.
  4. Execute the code to obtain a completion from the deployed model and analyze the generated response, which will include a severity assessment to categorize the content.

Conclusion

These tools will not only allow you to creatively and effectively integrate GPT models into innovative applications, but will also ensure that the generated content is properly categorized in terms of security and thematic sensitivity. Whether through Postman and the REST API or through the SDK, the invitation is to explore and leverage the potential of Azure OpenAI Service to take your projects to the next level. Go ahead, the world of AI is waiting to be discovered by you!

Contributions 12

Questions 5

Sort by:

Want to see more contributions, questions and answers from the community?

Pueden solucionar el error del sdk instalando la ultima version de OpenAI 1.8.0 y ejecutar esta otra forma de API REST.

<import osfrom openai import AzureOpenAI client = AzureOpenAI(  azure\_endpoint = "TU END POINT",   api\_key= "2TU APPI KEY",   api\_version="2023-05-15") response = client.chat.completions.create(    model="gpt35", # model = "deployment\_name".    messages=\[        {"role": "system", "content": "You are an AI assistant that helps people find information."},        {"role": "assistant", "content": "How can I help you?"},        {"role": "user", "content": "What is the capital of Spain?"}    ]) print(response.choices\[0].message.content)>
Después de aprender a utilizar y gestionar los modelos de lenguaje a través de la plataforma de OpenAI Studio, ahora exploraremos cómo consumir estos modelos a través de la API REST y el SDK disponibles. Consumo a través de la API REST: Para consumir los modelos mediante la API REST, necesitamos 3 elementos clave: Endpoint: La URL a la que enviaremos las llamadas. API Key: La clave de autenticación para acceder a la API. Nombre del modelo: El modelo específico que queremos utilizar. Podemos consultar estos datos en el portal de Azure y en la sección de "Deployment" de OpenAI Studio. Utilizaremos Postman para hacer una llamada POST a la API REST: Configuraremos el endpoint y la API Key en la solicitud. En el cuerpo de la solicitud, especificaremos la configuración del mensaje, como la descripción del usuario y los parámetros de temperatura y top\_p. La respuesta de la API incluirá información sobre la clasificación y el nivel de severidad del contenido generado. Consumo a través del SDK: El SDK de Azure OpenAI Service está disponible para Python y C#. Usaremos un notebook de Jupyter para ejecutar el código del SDK. Necesitaremos los mismos 3 elementos clave: endpoint, API Key y nombre del modelo. Copiaremos el código de ejemplo proporcionado en OpenAI Studio y lo ejecutaremos en el notebook. Ajustaremos el código para incluir la API Key directamente en el script, en lugar de utilizarla desde variables de entorno. Al ejecutar el código, obtendremos una respuesta del modelo, junto con la clasificación y el nivel de severidad del contenido generado. Tanto el consumo a través de la API REST como del SDK nos permiten interactuar programáticamente con los modelos de lenguaje desplegados en Azure OpenAI Service. Esto nos brinda la flexibilidad de integrar estos modelos en nuestras propias aplicaciones y realizar validaciones y pruebas de su comportamiento.
Despues de batallar un rato y hacerlo funcionar utilizando un codigo que me parecio algo complejo, vi el del compañero Andres Estefano, formatearlo un poco y salio muy bien Solo agregue el comando para installar y actualizar el paquete de openai al inicio ```js !pip install --upgrade openai import os from openai import AzureOpenAI client = AzureOpenAI(azure_endpoint = "https://tuendpoint.openai.azure.com/", api_key= "tuapikey", api_version="2024-02-15-preview") response = client.chat.completions.create( model="gpt35", # model = "deployment_name". messages=[ {"role": "system", "content": "You are an AI assistant that helps people find information."}, {"role": "assistant", "content": "How can I help you?"}, {"role": "user", "content": "What is the capital of Spain?"} ]) print(response.choices[0].message.content) ```Saludos
Para ver el **Endpoint completo**: 1. Selecciona "**View code**" 2. Selecciona "**cURL**" (previamente dice Python). 3. Veras el **endpoint** completo. ![](https://static.platzi.com/media/user_upload/Sumarizaci%C3%B3n%20y%20Q%26A%20%2814%29-e875f255-b742-452d-8113-df2dbd0ede2b.jpg)
tengo un concern de seguridad, para aquellos lenguajes en los cuales no existe un SDK, y se daba consumir por medio de api rest, en cuanto a la key enviarla por parametro de la url, entiendo que va por medio de https, pero enviarlo por url no se que tan seguro sea, considero que lo mejor seria enviarlo por header.
Para los que tienen problema al no ver el endpoint dentro de la pantalla que mostro la profe, puede verlo cambiandolo a curl, la url completa, en mi caso la region donde tengo el recurso es east us
Buen día, ¿Qué tan viable es utilizar **Bot Composer** para orquestar la ejecución del chatbot? Además, ¿cuál es la mejor práctica para generar **KPIs de medición** en términos de **eficiencia, eficacia y calidad de respuesta** según la interacción del usuario, y cómo se pueden visualizar estos datos en **Power BI**? Agradezco su orientación.
profe buenas tarde, por medio de que aplicacion entro al sdk, para hacer consulta a los modelos
Aqui un ejemplo en c# que me funcionó muy bien. `using Azure;` `using Azure.AI.OpenAI;` `using OpenAI;` `using OpenAI.Chat;` `using static System.Environment;` `//string keyFromEnvironment = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY");` `AzureOpenAIClient azureClient = new(` ` new Uri("https://openaitestlaproff.openai.azure.com/"),` ` new AzureKeyCredential("APIKEY"));` `ChatClient chatClient = azureClient.GetChatClient("gptnamemodel");` `ChatCompletion completion = chatClient.CompleteChat(` ` [` ` // System messages represent instructions or other guidance about how the assistant should behave` ` new SystemChatMessage("Hola.. quiero que tomes el rol de analista deportivo."),` ` // User messages represent user input, whether historical or the most recen tinput` ` new UserChatMessage("Hi, can you help me?"),` ` // Assistant messages in a request represent conversation history for responses` ` new AssistantChatMessage("Arrr! Of course, me hearty! What can I do for ye?"),` ` new UserChatMessage("¿como crees que va a quedar el partido entre colombia y argentina?"),` ` ]);` `Console.WriteLine($"{completion.Role}: {completion.Content[0].Text}");` `Console.Read();`
Buenas tardes, aqui pueden encontrar un ejemplo de conexión con C# mas claro. <https://www.nuget.org/packages/Azure.AI.OpenAI>
Saludos, tengo problemas con la llamad en Postman, estoy recibiendo el mensaje de "**Unsoported data type**". Adjunto incluyo un Print screen. El API-Key esta correcto por que si lo remuevo me devuelve error 401 "Access Denied". ![](https://static.platzi.com/media/user_upload/image-2aa396bb-7595-4637-a02c-b86ac6d81eb9.jpg) Probe el código de Python y responde bien. Otra pregunta, como puedo desplegar en formato Json la respuesta de la llamada para que se pueda ver de forma legible y no en una solo linea como muestro en la imagen ![](https://static.platzi.com/media/user_upload/image-7a3878cb-789a-4870-8ac1-202f2f0295e5.jpg) Gracias.

Uff listo migrado, que opinan?

<import openai
import os
from dotenv import load_dotenv
load_dotenv()

# Note: The openai-python library support for Azure OpenAI is in preview.
# Note: This code sample requires OpenAI Python library version 0.28.1.

openai_api_key = os.getenv("OPENAI_API_KEY")
resource_name = os.getenv("RESORUCE_NAME")
resource_engine = os.getenv("RESOURCE_ENGINE")
model_api_version = os.getenv("VERSION_MODELO")
url_base = f"https://{resource_name}.openai.azure.com/"

openai.api_type = "azure"
openai.api_base = url_base
openai.api_version = model_api_version
openai.api_key = openai_api_key

message_text = [{"role": "system",
                 "content": "You are an AI assistant that helps people find information."}]

completion = await openai.ChatCompletion.acreate(
    model="gpt-3.5-turbo",
    engine=resource_engine,
    messages=message_text,
    temperature=0.7,
    max_tokens=800,
    top_p=0.95,
    frequency_penalty=0,
    presence_penalty=0,
    stop=None
)>