Azure OpenAI v1 엔드포인트와 함께 OpenAI SDK를 사용하여 Python, C#, JavaScript, Java 또는 Go에서 모델 유추 애플리케이션을 빌드합니다. 이 예제에서는 새 애플리케이션에 대해 응답 API를 사용하고 메시지 기반 인터페이스를 계속 사용하는 애플리케이션에 대한 채팅 완료를 보여 줍니다.
필수 구성 요소
- Azure 구독입니다. 없다면 무료로 하나 만드세요.
- 모델 배포를 사용하는 Azure OpenAI 리소스입니다
gpt-5-mini. - Azure OpenAI 리소스 엔드포인트(예:
https://YOUR-RESOURCE-NAME.openai.azure.com.) - Microsoft Entra ID 인증의 경우 유추를 실행할 수 있는 권한이 있는 ID입니다. 역할 옵션은 Microsoft Entra ID 인증 구성을 참조하세요.
- API 키 인증의 경우 Azure OpenAI 리소스 키입니다. Microsoft Entra ID 프로덕션 애플리케이션에 권장됩니다.
- 선택한 언어에 대해 지원되는 언어 런타임 및 패키지 관리자입니다.
모든 요청의 값은 model Azure 모델 배포 이름입니다. 예제에서는 배포에 다른 이름이 있는 경우 해당 이름을 바 gpt-5-mini꿉니다.
소스 코드 | 패키지(Package) | API 표면
예제는 2.12.0, OpenAI 1.21.0 및 .NET 8로 테스트 Azure.Identity 되었습니다. 또한 OpenAI 패키지는 .NET Standard 2.0 이상 .NET 버전을 대상으로 합니다.
패키지 설치
OpenAI 및 Azure ID 패키지를 설치합니다.
dotnet add package OpenAI
dotnet add package Azure.Identity
이 명령은 두 패키지 참조를 프로젝트에 추가합니다.
Microsoft Entra ID 사용하여 응답 만들기
DefaultAzureCredential API 키를 저장하지 않고 사용하고 BearerTokenPolicy 인증합니다.
using Azure.Identity;
using OpenAI.Responses;
using System.ClientModel.Primitives;
#pragma warning disable OPENAI001
var endpoint = new Uri(
"https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/");
var tokenPolicy = new BearerTokenPolicy(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
var openAIClient = new ResponsesClient(
tokenPolicy,
new ResponsesClientOptions { Endpoint = endpoint });
var response = await openAIClient.CreateResponseAsync(
"gpt-5-mini",
"Explain the purpose of an API in one sentence.");
Console.WriteLine(response.Value.GetOutputText());
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
참조: ResponsesClient
API 키를 사용하여 응답 만들기
API 키는 프로덕션 사용에 권장되지 않습니다. 키를 소스 코드에 AZURE_OPENAI_API_KEY 배치하는 대신 환경 변수에 저장합니다.
export AZURE_OPENAI_API_KEY="<your-api-key>"
그런 다음 클라이언트를 만들고 다음을 요청합니다.
using OpenAI.Responses;
using System.ClientModel;
#pragma warning disable OPENAI001
var endpoint = new Uri(
"https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/");
var apiKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")
?? throw new InvalidOperationException("AZURE_OPENAI_API_KEY is required.");
var openAIClient = new ResponsesClient(
new ApiKeyCredential(apiKey),
new ResponsesClientOptions { Endpoint = endpoint });
var response = await openAIClient.CreateResponseAsync(
"gpt-5-mini",
"Explain the purpose of an API in one sentence.");
Console.WriteLine(response.Value.GetOutputText());
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
채팅 완료 사용
새 애플리케이션의 경우 응답 API를 사용합니다. 메시지 기반 인터페이스가 필요하거나 기존 애플리케이션을 유지 관리하는 경우 채팅 완료를 사용합니다.
using Azure.Identity;
using OpenAI;
using OpenAI.Chat;
using System.ClientModel.Primitives;
#pragma warning disable OPENAI001
var endpoint = new Uri(
"https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/");
var tokenPolicy = new BearerTokenPolicy(
new DefaultAzureCredential(),
"https://ai.azure.com/.default");
var openAIClient = new ChatClient(
model: "gpt-5-mini",
authenticationPolicy: tokenPolicy,
options: new OpenAIClientOptions { Endpoint = endpoint });
var completion = await openAIClient.CompleteChatAsync([
new SystemChatMessage("You are a helpful assistant."),
new UserChatMessage("Explain the purpose of an API.")
]);
Console.WriteLine(completion.Value.Content[0].Text);
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
참조: ChatClient
응답을 스트리밍하기
모델에서 생성할 때 텍스트 델타 업데이트를 호출 CreateResponseStreamingAsync 하고 처리합니다.
using OpenAI.Responses;
using System.ClientModel;
#pragma warning disable OPENAI001
var endpoint = new Uri(
"https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/");
var apiKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")
?? throw new InvalidOperationException("AZURE_OPENAI_API_KEY is required.");
var openAIClient = new ResponsesClient(
new ApiKeyCredential(apiKey),
new ResponsesClientOptions { Endpoint = endpoint });
// Stream text as the model generates it.
var updates = openAIClient.CreateResponseStreamingAsync(
"gpt-5-mini",
"Explain the purpose of an API in one sentence.");
await foreach (var update in updates)
{
if (update is StreamingResponseOutputTextDeltaUpdate delta)
{
Console.Write(delta.Delta);
}
}
다음 스트리밍 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
참조: CreateResponseStreamingAsync
오류 처리 및 다시 시도
클라이언트는 지수 백오프를 사용하여 HTTP 408, 429, 500, 502, 503 및 504 응답을 자동으로 다시 시도합니다. 다른 동작이 필요한 경우 클라이언트 옵션을 통해 재시도 정책을 구성합니다. Catch ClientResultException 하여 실패한 요청에 대한 HTTP 상태 및 오류 세부 정보를 검사합니다.
진단의 경우 작업에서 반환된 ClientResult<T> 내용을 유지하고 원시 응답 헤더를 검사합니다. 실패한 작업은 .를 통해 ClientResultException상태 정보를 노출합니다.
더 많은 SDK 예제
소스 코드 | 패키지 | REST API 참조 | Go API 참조
예제에는 Go 1.25 이상이 필요합니다. 3.44.0 및 github.com/openai/openai-go/v3 1.14.0으로 테스트 azidentity 되었습니다.
모듈 설치
OpenAI 및 Azure ID 모듈을 설치합니다.
go get github.com/openai/openai-go/v3
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
/v3 이 접미사는 Go 모듈의 현재 주 버전을 식별하기 때문에 필요합니다.
Microsoft Entra ID 사용하여 응답 만들기
API 키를 저장하지 않고 인증하려면 Azure 인증 옵션을 사용합니다DefaultAzureCredential.
package main
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/azure"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)
func main() {
credential, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil { panic(err) }
endpoint := "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openaiClient := openai.NewClient(
option.WithBaseURL(endpoint),
azure.WithTokenCredential(credential, azure.WithTokenCredentialScopes(
[]string{"https://ai.azure.com/.default"})))
response, err := openaiClient.Responses.New(context.Background(), responses.ResponseNewParams{
Model: openai.ChatModel("gpt-5-mini"),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(
"Explain the purpose of an API in one sentence.")},
})
if err != nil { panic(err) }
fmt.Println(response.OutputText())
}
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
참조: ResponseService.New 및 WithTokenCredentialScopes
API 키를 사용하여 응답 만들기
API 키는 프로덕션 사용에 권장되지 않습니다. 키를 소스 코드에 AZURE_OPENAI_API_KEY 배치하는 대신 환경 변수에 저장합니다.
export AZURE_OPENAI_API_KEY="<your-api-key>"
그런 다음 클라이언트를 만들고 다음을 요청합니다.
package main
import (
"context"
"fmt"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)
func main() {
apiKey := os.Getenv("AZURE_OPENAI_API_KEY")
if apiKey == "" { panic("AZURE_OPENAI_API_KEY is required") }
endpoint := "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openaiClient := openai.NewClient(
option.WithBaseURL(endpoint),
option.WithAPIKey(apiKey))
response, err := openaiClient.Responses.New(context.Background(), responses.ResponseNewParams{
Model: openai.ChatModel("gpt-5-mini"),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(
"Explain the purpose of an API in one sentence.")},
})
if err != nil { panic(err) }
fmt.Println(response.OutputText())
}
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
참조: Responses.New
채팅 완료 사용
새 애플리케이션의 경우 응답 API를 사용합니다. 메시지 기반 인터페이스가 필요하거나 기존 애플리케이션을 유지 관리하는 경우 채팅 완료를 사용합니다.
package main
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/azure"
"github.com/openai/openai-go/v3/option"
)
func main() {
credential, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil { panic(err) }
endpoint := "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openaiClient := openai.NewClient(
option.WithBaseURL(endpoint),
azure.WithTokenCredential(credential, azure.WithTokenCredentialScopes(
[]string{"https://ai.azure.com/.default"})))
completion, err := openaiClient.Chat.Completions.New(context.Background(),
openai.ChatCompletionNewParams{
Model: openai.ChatModel("gpt-5-mini"),
Messages: []openai.ChatCompletionMessageParamUnion{
openai.DeveloperMessage("You are a helpful assistant."),
openai.UserMessage("Explain the purpose of an API.")}})
if err != nil { panic(err) }
fmt.Println(completion.Choices[0].Message.Content)
}
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
응답을 스트리밍하기
모델에서 생성할 때 텍스트 델타 이벤트를 호출 Responses.NewStreaming하고 처리합니다.
package main
import (
"context"
"fmt"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)
func main() {
endpoint := "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openaiClient := openai.NewClient(option.WithBaseURL(endpoint),
option.WithAPIKey(os.Getenv("AZURE_OPENAI_API_KEY")))
// Stream text as the model generates it.
stream := openaiClient.Responses.NewStreaming(context.Background(), responses.ResponseNewParams{
Model: openai.ChatModel("gpt-5-mini"),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(
"Explain the purpose of an API in one sentence.")},
})
for stream.Next() { fmt.Print(stream.Current().Delta) }
if err := stream.Err(); err != nil { panic(err) }
}
다음 스트리밍 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
오류 처리 및 다시 시도
SDK는 기하급수적 백오프를 사용하여 연결 오류 및 HTTP 408, 409, 429 및 5xx 응답을 두 번 다시 시도합니다. 기본값을 변경하는 데 사용합니다 option.WithMaxRetries . 응답을 읽기 전에 반환 error 된 항목을 확인하고 검사하는 데 errors.As사용합니다openai.Error.
package main
import (
"context"
"errors"
"fmt"
"os"
"github.com/openai/openai-go/v3"
"github.com/openai/openai-go/v3/option"
"github.com/openai/openai-go/v3/responses"
)
func main() {
endpoint := "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openaiClient := openai.NewClient(option.WithBaseURL(endpoint),
option.WithAPIKey(os.Getenv("AZURE_OPENAI_API_KEY")), option.WithMaxRetries(4))
// Send the request and inspect structured service errors.
result, err := openaiClient.Responses.New(context.Background(), responses.ResponseNewParams{
Model: openai.ChatModel("gpt-5-mini"),
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String("Explain an API.")},
})
if err != nil {
var apiError *openai.Error
if errors.As(err, &apiError) { fmt.Printf("Status: %d; Request ID: %s\n",
apiError.StatusCode, apiError.Response.Header.Get("x-request-id")) }
panic(err)
}
fmt.Println(result.OutputText())
}
성공적인 요청의 경우 다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
참조: 오류 및 다시 시도
더 많은 SDK 예제
소스 코드 | 패키지 | REST API 참조 | Java API 참조
예제에는 Java 8 이상이 필요합니다. 4.43.0 및 openai-java 1.18.4로 테스트 azure-identity 되었습니다.
패키지 설치
메이븐
Maven 프로젝트에 OpenAI 및 Azure ID 종속성을 추가합니다.
<dependencies>
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.43.0</version>
</dependency>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.18.4</version>
</dependency>
</dependencies>
Maven은 프로젝트를 빌드할 때 패키지 및 해당 전이적 종속성을 확인합니다.
Gradle
Gradle 빌드 파일의 dependencies 블록에 동일한 패키지를 추가합니다.
dependencies {
implementation("com.openai:openai-java:4.43.0")
implementation("com.azure:azure-identity:1.18.4")
}
Gradle은 프로젝트를 빌드할 때 패키지를 확인합니다.
Microsoft Entra ID 사용하여 응답 만들기
DefaultAzureCredential API 키를 저장하지 않고 사용하고 BearerTokenCredential 인증합니다.
import com.azure.identity.AuthenticationUtil;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.credential.BearerTokenCredential;
import com.openai.models.responses.ResponseCreateParams;
public class ResponsesExample {
public static void main(String[] args) {
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint)
.credential(BearerTokenCredential.create(
AuthenticationUtil.getBearerTokenSupplier(
new DefaultAzureCredentialBuilder().build(),
"https://ai.azure.com/.default")))
.build();
ResponseCreateParams params = ResponseCreateParams.builder()
.model("gpt-5-mini")
.input("Explain the purpose of an API in one sentence.")
.build();
openAIClient.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(output -> System.out.println(output.text()));
}
}
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
참조: AzureEntraIdExample 및 ResponsesExample
API 키를 사용하여 응답 만들기
프로덕션에 API 키를 사용하지 마세요. 키를 소스 코드에 AZURE_OPENAI_API_KEY 배치하는 대신 환경 변수에 저장합니다.
export AZURE_OPENAI_API_KEY="<your-api-key>"
그런 다음 클라이언트를 만들고 다음을 요청합니다.
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.responses.ResponseCreateParams;
public class ApiKeyResponsesExample {
public static void main(String[] args) {
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
String apiKey = System.getenv("AZURE_OPENAI_API_KEY");
if (apiKey == null) throw new IllegalStateException(
"AZURE_OPENAI_API_KEY is required.");
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint).apiKey(apiKey).build();
ResponseCreateParams params = ResponseCreateParams.builder()
.model("gpt-5-mini")
.input("Explain the purpose of an API in one sentence.")
.build();
openAIClient.responses().create(params).output().stream()
.flatMap(item -> item.message().stream())
.flatMap(message -> message.content().stream())
.flatMap(content -> content.outputText().stream())
.forEach(output -> System.out.println(output.text()));
}
}
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
채팅 완료 사용
새 애플리케이션의 경우 응답 API를 사용합니다. 메시지 기반 인터페이스가 필요하거나 기존 애플리케이션을 유지 관리하는 경우 채팅 완료를 사용합니다.
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
public class ChatExample {
public static void main(String[] args) {
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
String apiKey = System.getenv("AZURE_OPENAI_API_KEY");
if (apiKey == null) throw new IllegalStateException(
"AZURE_OPENAI_API_KEY is required.");
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint).apiKey(apiKey).build();
ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
.model("gpt-5-mini")
.addDeveloperMessage("You are a helpful assistant.")
.addUserMessage("Explain the purpose of an API.")
.build();
openAIClient.chat().completions().create(params).choices().stream()
.flatMap(choice -> choice.message().content().stream())
.forEach(System.out::println);
}
}
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
참조: ChatCompletionCreateParams
응답을 스트리밍하기
모델에서 생성할 때 텍스트 델타 이벤트를 호출 createStreaming하고 처리합니다.
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.StreamResponse;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseStreamEvent;
public class StreamingExample {
public static void main(String[] args) {
String endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
String apiKey = System.getenv("AZURE_OPENAI_API_KEY");
if (apiKey == null) throw new IllegalStateException(
"AZURE_OPENAI_API_KEY is required.");
OpenAIClient openAIClient = OpenAIOkHttpClient.builder()
.baseUrl(endpoint).apiKey(apiKey).build();
// Stream text as the model generates it.
ResponseCreateParams params = ResponseCreateParams.builder()
.model("gpt-5-mini")
.input("Explain the purpose of an API in one sentence.")
.build();
try (StreamResponse<ResponseStreamEvent> stream =
openAIClient.responses().createStreaming(params)) {
stream.stream().flatMap(event -> event.outputTextDelta().stream())
.forEach(delta -> System.out.print(delta.delta()));
}
}
}
다음 스트리밍 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
오류 처리 및 다시 시도
SDK는 기하급수적 백오프를 사용하여 연결 오류 및 HTTP 408, 409, 429 및 5xx 응답을 두 번 다시 시도합니다. Catch OpenAIServiceException 하여 서비스 응답에 대한 HTTP 상태 및 오류 세부 정보를 검사하고 다른 SDK 오류를 catch OpenAIException 합니다.
기본값을 변경하려면 호출 maxRetriesOpenAIOkHttpClient.builder() 합니다. 애플리케이션이 상태를 기록하고 메타데이터를 요청할 수 있도록 서비스 예외를 유지합니다.
더 많은 SDK 예제
소스 코드 | 패키지 | REST API 참조 | Azure OpenAI v1 지침
예제에는 Node.js 20 이상이 필요합니다. 6.46.0 및 openai 4.13.1로 테스트 @azure/identity 되었습니다. Microsoft Entra 토큰 공급자openai를 로 전달할 때 5.18.0 이상을 사용합니다apiKey.
패키지 설치
OpenAI 및 Azure ID 패키지를 설치합니다.
npm install openai @azure/identity
이 명령은 두 패키지를 프로젝트에 추가합니다.
Microsoft Entra ID 사용하여 응답 만들기
DefaultAzureCredential API 키를 저장하지 않고 사용하고 getBearerTokenProvider 인증합니다. 토큰 공급자는 필요할 때 액세스 토큰을 새로 고칩니다.
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
import OpenAI from "openai";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
"https://ai.azure.com/.default",
);
const openai = new OpenAI({ baseURL: endpoint, apiKey: tokenProvider });
async function main() {
const response = await openai.responses.create({
model: "gpt-5-mini",
input: "Explain the purpose of an API in one sentence.",
});
console.log(response.output_text);
}
main().catch(console.error);
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
참조: OpenAI 클라이언트 및 Azure OpenAI v1 인증
API 키를 사용하여 응답 만들기
API 키는 프로덕션 사용에 권장되지 않습니다. 키를 소스 코드에 AZURE_OPENAI_API_KEY 배치하는 대신 환경 변수에 저장합니다.
export AZURE_OPENAI_API_KEY="<your-api-key>"
그런 다음 클라이언트를 만들고 다음을 요청합니다.
import OpenAI from "openai";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
const apiKey = process.env["AZURE_OPENAI_API_KEY"];
if (!apiKey) throw new Error("AZURE_OPENAI_API_KEY is required.");
const openai = new OpenAI({ baseURL: endpoint, apiKey });
async function main() {
const response = await openai.responses.create({
model: "gpt-5-mini",
input: "Explain the purpose of an API in one sentence.",
});
console.log(response.output_text);
}
main().catch(console.error);
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
참조: responses.create
채팅 완료 사용
새 애플리케이션의 경우 응답 API를 사용합니다. 메시지 기반 인터페이스가 필요하거나 기존 애플리케이션을 유지 관리하는 경우 채팅 완료를 사용합니다.
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
import OpenAI from "openai";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
"https://ai.azure.com/.default",
);
const openai = new OpenAI({ baseURL: endpoint, apiKey: tokenProvider });
async function main() {
const completion = await openai.chat.completions.create({
model: "gpt-5-mini",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Explain the purpose of an API." },
],
});
console.log(completion.choices[0]?.message.content ?? "No response returned.");
}
main().catch(console.error);
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
요청 내부에 유지 messages 하면 값에 필요한 상황별 입력이 role 제공됩니다. 배열을 별도로 정의하는 경우 해당 배열을 .로 OpenAI.Chat.ChatCompletionMessageParam[]선언합니다.
응답을 스트리밍하기
모델에서 생성할 stream때 텍스트 델타 이벤트를 로 설정하고 true 처리합니다.
import OpenAI from "openai";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
const apiKey = process.env["AZURE_OPENAI_API_KEY"];
if (!apiKey) throw new Error("AZURE_OPENAI_API_KEY is required.");
const openai = new OpenAI({ baseURL: endpoint, apiKey });
async function main() {
// Stream text as the model generates it.
const stream = await openai.responses.create({
model: "gpt-5-mini",
input: "Explain the purpose of an API in one sentence.",
stream: true,
});
for await (const event of stream) {
if (event.type === "response.output_text.delta") {
process.stdout.write(event.delta);
}
}
}
main().catch(console.error);
다음 스트리밍 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
오류 처리 및 다시 시도
SDK는 지수 백오프를 사용하여 연결 오류, 시간 제한, HTTP 408, 409, 429 및 5xx 응답을 두 번 자동으로 다시 시도합니다. 이 동작을 maxRetries 변경하려면 클라이언트에서 설정합니다OpenAI. Catch APIError 하여 실패한 요청에 대한 HTTP 상태, 요청 ID 및 오류 세부 정보를 검사합니다.
다음 예제에서는 네 번의 재시도를 설정하고 성공 및 실패한 요청에 대한 요청 ID를 기록합니다.
import OpenAI from "openai";
const endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/";
const apiKey = process.env["AZURE_OPENAI_API_KEY"];
if (!apiKey) throw new Error("AZURE_OPENAI_API_KEY is required.");
const openai = new OpenAI({ baseURL: endpoint, apiKey, maxRetries: 4 });
async function main() {
try {
// Send the request and record its request ID.
const response = await openai.responses.create({
model: "gpt-5-mini",
input: "Explain the purpose of an API in one sentence.",
});
console.log(response.output_text);
console.log(`Request ID: ${response._request_id}`);
} catch (error) {
if (error instanceof OpenAI.APIError) {
console.error(`Status: ${error.status}; Request ID: ${error.requestID}`);
}
throw error;
}
}
main().catch(console.error);
성공적인 요청의 경우 다음 출력이 대표입니다. 응답 텍스트 및 요청 ID는 다음과 같습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
Request ID: <request-id>
더 많은 SDK 예제
예제에는 Python 3.9 이상이 필요합니다. 2.46.0 및 openai 1.25.3으로 azure-identity 테스트되었습니다. Microsoft Entra 토큰 공급자openai를 로 전달할 때 1.106.0 이상을 사용합니다api_key.
패키지 설치
OpenAI 및 Azure ID 패키지를 설치합니다.
pip install openai azure-identity
이 명령은 활성 Python 환경에 두 패키지를 모두 설치합니다.
Microsoft Entra ID 사용하여 응답 만들기
DefaultAzureCredential API 키를 저장하지 않고 사용하고 get_bearer_token_provider 인증합니다. 토큰 공급자는 필요할 때 액세스 토큰을 새로 고칩니다.
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import OpenAI
endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://ai.azure.com/.default"
)
openai = OpenAI(base_url=endpoint, api_key=token_provider)
response = openai.responses.create(
model="gpt-5-mini",
input="Explain the purpose of an API in one sentence.",
)
print(response.output_text)
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
참조: OpenAI 클라이언트 및 get_bearer_token_provider
API 키를 사용하여 응답 만들기
API 키는 프로덕션 사용에 권장되지 않습니다. 키를 소스 코드에 AZURE_OPENAI_API_KEY 배치하는 대신 환경 변수에 저장합니다.
export AZURE_OPENAI_API_KEY="<your-api-key>"
그런 다음 클라이언트를 만들고 다음을 요청합니다.
import os
from openai import OpenAI
endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
api_key = os.environ["AZURE_OPENAI_API_KEY"]
openai = OpenAI(base_url=endpoint, api_key=api_key)
response = openai.responses.create(
model="gpt-5-mini",
input="Explain the purpose of an API in one sentence.",
)
print(response.output_text)
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
참조: responses.create
채팅 완료 사용
새 애플리케이션의 경우 응답 API를 사용합니다. 메시지 기반 인터페이스가 필요하거나 기존 애플리케이션을 유지 관리하는 경우 채팅 완료를 사용합니다.
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from openai import OpenAI
endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://ai.azure.com/.default"
)
openai = OpenAI(base_url=endpoint, api_key=token_provider)
completion = openai.chat.completions.create(
model="gpt-5-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain the purpose of an API."},
],
)
print(completion.choices[0].message.content)
다음 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
응답을 스트리밍하기
모델에서 생성할 stream때 텍스트 델타 이벤트를 로 설정하고 True 처리합니다.
import os
from openai import OpenAI
endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openai = OpenAI(
base_url=endpoint,
api_key=os.environ["AZURE_OPENAI_API_KEY"],
)
# Stream text as the model generates it.
stream = openai.responses.create(
model="gpt-5-mini",
input="Explain the purpose of an API in one sentence.",
stream=True,
)
for event in stream:
if event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
다음 스트리밍 출력이 대표입니다. 정확한 표현은 다음과 같이 다를 수 있습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
오류 처리 및 다시 시도
SDK는 지수 백오프를 사용하여 연결 오류, 시간 제한, HTTP 408, 409, 429 및 5xx 응답을 두 번 자동으로 다시 시도합니다. 이 동작을 max_retries 변경하려면 클라이언트에서 설정합니다OpenAI. Catch openai.APIStatusError 하여 HTTP 상태, 요청 ID 및 실패한 요청에 대한 응답을 검사합니다.
다음 예제에서는 네 번의 재시도를 설정하고 성공 및 실패한 요청에 대한 요청 ID를 기록합니다.
import os
import openai as openai_sdk
from openai import OpenAI
endpoint = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"
openai = OpenAI(
base_url=endpoint,
api_key=os.environ["AZURE_OPENAI_API_KEY"],
max_retries=4,
)
try:
# Send the request and record its request ID.
response = openai.responses.create(
model="gpt-5-mini",
input="Explain the purpose of an API in one sentence.",
)
print(response.output_text)
print(f"Request ID: {response._request_id}")
except openai_sdk.APIStatusError as error:
print(f"Status: {error.status_code}; Request ID: {error.request_id}")
raise
성공적인 요청의 경우 다음 출력이 대표입니다. 응답 텍스트 및 요청 ID는 다음과 같습니다.
An API allows software applications to communicate and exchange data through a defined set of rules.
Request ID: <request-id>
더 많은 SDK 예제
문제 해결
- 또는 응답의
401403경우 의도한 ID 또는 API 키가 Azure OpenAI 리소스에 액세스할 수 있음을 확인합니다. - 응답의
404경우 기본 URL이 종료/openai/v1/되고 유효한 배포 이름을 포함하는지model확인합니다. - 패키지 또는 형식 오류의 경우 SDK를 업데이트하고 설치된 버전을 이 페이지에서 테스트된 버전과 비교합니다.
- 모델 매개 변수 오류의 경우 배포된 모델이 매개 변수를 지원하는지 확인합니다. 매개 변수 지원은 모델 패밀리 간에 다를 수 있습니다.