Azure OpenAI API 버전 지원
- 이제 v1 GA(일반 공급) API를 통해 GA 및 미리 보기 작업에 모두 액세스할 수 있습니다. 자세한 내용은 API 버전 수명 주기 가이드를 참조하세요.
설치
dotnet add package OpenAI
인증
안전하고 키가 없는 인증 방법은 Azure ID 라이브러리를 통해 Microsoft Entra ID(이전의 Azure Active Directory)를 사용하는 것입니다. 라이브러리를 사용하려면:
dotnet add package Azure.Identity
라이브러리에서 원하는 자격 증명 형식을 사용합니다. 예: DefaultAzureCredential
using Azure.Identity;
using OpenAI;
using OpenAI.Chat;
using System.ClientModel.Primitives;
#pragma warning disable OPENAI001
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://cognitiveservices.azure.com/.default");
ChatClient client = new(
model: "gpt-4.1-nano",
authenticationPolicy: tokenPolicy,
options: new OpenAIClientOptions() {
Endpoint = new Uri("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1")
}
);
ChatCompletion completion = client.CompleteChat("Tell me about the bitter lesson.'");
Console.WriteLine($"[ASSISTANT]: {completion.Content[0].Text}");
Azure OpenAI 키 없는 인증에 대한 자세한 내용은 "Azure OpenAI 보안 구성 요소 시작" 빠른 시작 문서를 참조하세요.
채팅
추론 모델에 대한 채팅 완료 요청의 예입니다.
using OpenAI;
using OpenAI.Chat;
using System.ClientModel.Primitives;
#pragma warning disable OPENAI001 //currently required for token based authentication
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://cognitiveservices.azure.com/.default");
ChatClient client = new(
model: "o4-mini",
authenticationPolicy: tokenPolicy,
options: new OpenAIClientOptions()
{
Endpoint = new Uri("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1")
}
);
ChatCompletionOptions options = new ChatCompletionOptions
{
ReasoningEffortLevel = ChatReasoningEffortLevel.Low,
MaxOutputTokenCount = 100000
};
ChatCompletion completion = client.CompleteChat(
new DeveloperChatMessage("You are a helpful assistant"),
new UserChatMessage("Tell me about the bitter lesson")
);
Console.WriteLine($"[ASSISTANT]: {completion.Content[0].Text}");
포함
using OpenAI;
using OpenAI.Embeddings;
using System.ClientModel;
string apiKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")
?? throw new InvalidOperationException("AZURE_OPENAI_API_KEY environment variable is not set");
EmbeddingClient client = new(
"text-embedding-3-large",
credential: new ApiKeyCredential(apiKey),
options: new OpenAIClientOptions()
{
Endpoint = new Uri("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1")
}
);
string input = "This is a test";
OpenAIEmbedding embedding = client.GenerateEmbedding(input);
ReadOnlyMemory<float> vector = embedding.ToFloats();
Console.WriteLine($"Embeddings: [{string.Join(", ", vector.ToArray())}]");
응답 API
using OpenAI;
using OpenAI.Responses;
using System.ClientModel.Primitives;
using Azure.Identity;
#pragma warning disable OPENAI001 //currently required for token based authentication
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://cognitiveservices.azure.com/.default");
OpenAIResponseClient client = new(
model: "o4-mini",
authenticationPolicy: tokenPolicy,
options: new OpenAIClientOptions()
{
Endpoint = new Uri("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1")
}
);
OpenAIResponse response = await client.CreateResponseAsync(
userInputText: "What's the optimal strategy to win at poker?",
new ResponseCreationOptions()
{
ReasoningOptions = new ResponseReasoningOptions()
{
ReasoningEffortLevel = ResponseReasoningEffortLevel.High,
},
});
Console.WriteLine(response.GetOutputText());
스트리밍
using OpenAI;
using OpenAI.Responses;
using System.ClientModel.Primitives;
using Azure.Identity;
#pragma warning disable OPENAI001 //currently required for token based authentication
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://cognitiveservices.azure.com/.default");
#pragma warning disable OPENAI001
OpenAIResponseClient client = new(
model: "o4-mini",
authenticationPolicy: tokenPolicy,
options: new OpenAIClientOptions()
{
Endpoint = new Uri("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1")
}
);
await foreach (StreamingResponseUpdate update
in client.CreateResponseStreamingAsync(
userInputText: "What's the optimal strategy to win at poker?",
new ResponseCreationOptions()
{
ReasoningOptions = new ResponseReasoningOptions()
{
ReasoningEffortLevel = ResponseReasoningEffortLevel.High,
},
}))
{
if (update is StreamingResponseOutputItemAddedUpdate itemUpdate
&& itemUpdate.Item is ReasoningResponseItem reasoningItem)
{
Console.WriteLine($"[Reasoning] ({reasoningItem.Status})");
}
else if (update is StreamingResponseOutputTextDeltaUpdate delta)
{
Console.Write(delta.Delta);
}
}
MCP 서버
using OpenAI;
using OpenAI.Responses;
using System.ClientModel.Primitives;
using Azure.Identity;
#pragma warning disable OPENAI001 //currently required for token based authentication
BearerTokenPolicy tokenPolicy = new(
new DefaultAzureCredential(),
"https://cognitiveservices.azure.com/.default");
OpenAIResponseClient client = new(
model: "o4-mini",
authenticationPolicy: tokenPolicy,
options: new OpenAIClientOptions()
{
Endpoint = new Uri("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1")
}
);
ResponseCreationOptions options = new();
options.Tools.Add(ResponseTool.CreateMcpTool(
serverLabel: "microsoft_learn",
serverUri: new Uri("https://learn.microsoft.com/api/mcp"),
toolCallApprovalPolicy: new McpToolCallApprovalPolicy(GlobalMcpToolCallApprovalPolicy.NeverRequireApproval)
));
OpenAIResponse response = (OpenAIResponse)client.CreateResponse([
ResponseItem.CreateUserMessageItem([
ResponseContentPart.CreateInputTextPart("Search for information about Azure Functions")
])
], options);
Console.WriteLine(response.GetOutputText());
오류 처리
오류 코드
상태 코드 | 오류 유형 |
---|---|
400 | Bad Request Error |
401 | Authentication Error |
403 | Permission Denied Error |
404 | Not Found Error |
422 | Unprocessable Entity Error |
429 | Rate Limit Error |
500 | Internal Server Error |
503 | Service Unavailable |
504 | Gateway Timeout |
다시 시도
클라이언트 클래스는 지수 백오프를 사용하여 다음 오류를 최대 세 번 더 자동으로 다시 시도합니다.
- 408 요청 시간 초과
- 429 요청이 너무 많음
- 500 내부 서버 오류
- 502 잘못된 게이트웨이
- 503 서비스를 사용할 수 없음
- 504 게이트웨이 시간 초과
소스 코드 | 패키지(pkg.go.dev) | REST API 참조 설명서 | 패키지 참조 설명서
Azure OpenAI API 버전 지원
- 이제 v1 GA(일반 공급) API를 통해 GA 및 미리 보기 작업에 모두 액세스할 수 있습니다. 자세한 내용은 API 버전 수명 주기 가이드를 참조하세요.
설치
go get을 사용하여 openai
및 azidentity
모듈을 설치합니다.
go get -u 'github.com/openai/openai-go@v2.1.1'
# optional
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity
인증
azidentity 모듈은 Azure OpenAI를 사용한 Microsoft Entra ID 인증에 사용됩니다.
package main
import (
"context"
"fmt"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/openai/openai-go/v2"
"github.com/openai/openai-go/v2/azure"
"github.com/openai/openai-go/v2/option"
)
func main() {
// Create an Azure credential
tokenCredential, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
panic(fmt.Sprintf("Failed to create credential: %v", err))
}
// Create a client with Azure OpenAI endpoint and token credential
client := openai.NewClient(
option.WithBaseURL("https://YOUR-RESOURCE_NAME.openai.azure.com/openai/v1/"),
azure.WithTokenCredential(tokenCredential),
)
// Make a completion request
chatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{
Messages: []openai.ChatCompletionMessageParamUnion{
openai.UserMessage("Explain what the bitter lesson is?"),
},
Model: "o4-mini", // Use your deployed model name on Azure
})
if err != nil {
panic(err.Error())
}
fmt.Println(chatCompletion.Choices[0].Message.Content)
}
Azure OpenAI 키 없는 인증에 대한 자세한 내용은 키 없이 Azure OpenAI 사용을 참조하세요.
포함
package main
import (
"context"
"fmt"
"os"
"github.com/openai/openai-go/v2"
"github.com/openai/openai-go/v2/option"
)
func main() {
// Get API key from environment variable
apiKey := os.Getenv("AZURE_OPENAI_API_KEY")
if apiKey == "" {
panic("AZURE_OPENAI_API_KEY environment variable is not set")
}
// Create a client with Azure OpenAI endpoint and API key
client := openai.NewClient(
option.WithBaseURL("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"),
option.WithAPIKey(apiKey),
)
ctx := context.Background()
text := "The attention mechanism revolutionized natural language processing"
// Make an embedding request
embedding, err := client.Embeddings.New(ctx, openai.EmbeddingNewParams{
Input: openai.EmbeddingNewParamsInputUnion{OfString: openai.String(text)},
Model: "text-embedding-3-small", // Use your deployed model name on Azure
})
if err != nil {
panic(err.Error())
}
// Print embedding information
fmt.Printf("Model: %s\n", embedding.Model)
fmt.Printf("Number of embeddings: %d\n", len(embedding.Data))
fmt.Printf("Embedding dimensions: %d\n", len(embedding.Data[0].Embedding))
fmt.Printf("Usage - Prompt tokens: %d, Total tokens: %d\n", embedding.Usage.PromptTokens, embedding.Usage.TotalTokens)
// Print first few values of the embedding vector
fmt.Printf("First 10 embedding values: %v\n", embedding.Data[0].Embedding[:10])
}
Responses
package main
import (
"context"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/openai/openai-go/v2"
"github.com/openai/openai-go/v2/azure"
"github.com/openai/openai-go/v2/option"
"github.com/openai/openai-go/v2/responses"
)
func main() {
// Create Azure token credential
tokenCredential, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
panic(err)
}
// Create client with Azure endpoint and token credential
client := openai.NewClient(
option.WithBaseURL("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/"),
azure.WithTokenCredential(tokenCredential),
)
ctx := context.Background()
question := "Tell me about the attention is all you need paper"
resp, err := client.Responses.New(ctx, responses.ResponseNewParams{
Input: responses.ResponseNewParamsInputUnion{OfString: openai.String(question)},
Model: "o4-mini",
})
if err != nil {
panic(err)
}
println(resp.OutputText())
}
소스 코드 |REST API 참조 설명서 | 패키지 참조 설명서 | Maven Central
Azure OpenAI API 버전 지원
- 이제 v1 GA(일반 공급) API를 통해 GA 및 미리 보기 작업에 모두 액세스할 수 있습니다. 자세한 내용은 API 버전 수명 주기 가이드를 참조하세요.
설치
Gradle
implementation("com.openai:openai-java:4.0.1")
메이븐
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.0.1</version>
</dependency>
인증
Microsoft Entra ID를 사용하여 인증하려면 몇 가지 초기 설정이 필요합니다.
Azure ID 패키지 추가:
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.18.0</version>
</dependency>
설치 후 사용할 azure.identity
에서 자격 증명 유형을 선택할 수 있습니다. 예를 들어 DefaultAzureCredential
은 클라이언트를 인증하는 데 사용할 수 있습니다. Microsoft Entra ID 애플리케이션의 클라이언트 ID, 테넌트 ID 및 클라이언트 비밀 값을 환경 변수: AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET으로 설정합니다.
권한 부여는 .를 사용하는 것이 가장 쉽습니다 DefaultAzureCredential
.
DefaultAzureCredential
은 테스트용으로만 권장되고 프로덕션용으로는 권장되지 않지만 실행 환경에서 사용할 수 있는 최상의 자격 증명을 찾습니다.
Credential tokenCredential = BearerTokenCredential.create(
AuthenticationUtil.getBearerTokenSupplier(
new DefaultAzureCredentialBuilder().build(),
"https://cognitiveservices.azure.com/.default"));
OpenAIClient client = OpenAIOkHttpClient.builder()
.baseUrl("https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/")
.credential(tokenCredential)
.build();
Azure OpenAI 키 없는 인증에 대한 자세한 내용은 키 없이 Azure OpenAI 사용을 참조하세요.
Responses
package com.example;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.ChatModel;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.azure.core.credential.AzureKeyCredential;
public class OpenAITest {
public static void main(String[] args) {
// Get API key from environment variable for security
String apiKey = System.getenv("OPENAI_API_KEY");
String resourceName = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1";
String modelDeploymentName = "gpt-4.1"; //replace with you model deployment name
try {
OpenAIClient client = OpenAIOkHttpClient.builder()
.baseUrl(resourceName)
.apiKey(apiKey)
.build();
ResponseCreateParams params = ResponseCreateParams.builder()
.input("Tell me about the bitter lesson?")
.model(modelDeploymentName)
.build();
Response response = client.responses().create(params);
System.out.println("Response: " + response);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
Azure OpenAI API 버전 지원
- 이제 v1 GA(일반 공급) API를 통해 GA 및 미리 보기 작업에 모두 액세스할 수 있습니다. 자세한 내용은 API 버전 수명 주기 가이드를 참조하세요.
설치
npm install openai
인증
npm install @azure/identity
그러나 OpenAI
클라이언트를 인증하려면 getBearerTokenProvider
패키지의 @azure/identity
함수를 사용해야 합니다. 이 함수는 OpenAI
가 각 요청에 대한 토큰을 가져오기 위해 내부적으로 사용하는 토큰 공급자를 만듭니다. 토큰 공급자는 다음과 같이 만들어집니다.
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
import { OpenAI } from "openai";
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
'https://cognitiveservices.azure.com/.default');
const client = new OpenAI({
baseURL: "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
apiKey: tokenProvider
});
Azure OpenAI 키 없는 인증에 대한 자세한 내용은 "Azure OpenAI 보안 구성 요소 시작" 빠른 시작 문서를 참조하세요.
Responses
responses.create
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
import { OpenAI } from "openai";
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
'https://cognitiveservices.azure.com/.default');
const client = new OpenAI({
baseURL: "https://YOUR-RESORCE-NAME.openai.azure.com/openai/v1/",
apiKey: tokenProvider
});
const response = await client.responses.create({
model: 'gpt-4.1-nano', //model deployment name
instructions: 'You are a helpful AI agent',
input: 'Tell me about the bitter lesson?',
});
console.log(response.output_text);
스트리밍
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
import { OpenAI } from "openai";
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
'https://cognitiveservices.azure.com/.default');
const client = new OpenAI({
baseURL: "https://YOUR-RESORCE-NAME.openai.azure.com/openai/v1/",
apiKey: tokenProvider
});
const stream = await client.responses.create({
model: 'gpt-4.1-nano', // model deployment name
input: 'Provide a brief history of the attention is all you need paper.',
stream: true,
});
for await (const event of stream) {
if (event.type === 'response.output_text.delta' && event.delta) {
process.stdout.write(event.delta);
}
}
MCP 서버
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
import { OpenAI } from "openai";
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
'https://cognitiveservices.azure.com/.default');
const client = new OpenAI({
baseURL: "https://YOUR-RESORCE-NAME.openai.azure.com/openai/v1/",
apiKey: tokenProvider
});
const resp = await client.responses.create({
model: "gpt-5",
tools: [
{
type: "mcp",
server_label: "microsoft_learn",
server_description: "Microsoft Learn MCP server for searching and fetching Microsoft documentation.",
server_url: "https://learn.microsoft.com/api/mcp",
require_approval: "never",
},
],
input: "Search for information about Azure Functions",
});
console.log(resp.output_text);
채팅
chat.completions.create
import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity";
import { OpenAI } from "openai";
const tokenProvider = getBearerTokenProvider(
new DefaultAzureCredential(),
'https://cognitiveservices.azure.com/.default');
const client = new OpenAI({
baseURL: "https://france-central-test-001.openai.azure.com/openai/v1/",
apiKey: tokenProvider
});
const messages = [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Tell me about the attention is all you need paper' }
];
// Make the API request with top-level await
const result = await client.chat.completions.create({
messages,
model: 'gpt-4.1-nano', // model deployment name
max_tokens: 100
});
// Print the full response
console.log('Full response:', result);
// Print just the message content from the response
console.log('Response content:', result.choices[0].message.content);
오류 처리
오류 코드
상태 코드 | 오류 유형 |
---|---|
400 | Bad Request Error |
401 | Authentication Error |
403 | Permission Denied Error |
404 | Not Found Error |
422 | Unprocessable Entity Error |
429 | Rate Limit Error |
500 | Internal Server Error |
503 | Service Unavailable |
504 | Gateway Timeout |
다시 시도
다음 오류는 간단한 지수 백오프와 함께 기본적으로 두 번 자동으로 사용 중지됩니다.
- 연결 오류
- 408 요청 시간 초과
- 429 속도 제한
-
>=
500 내부 오류
maxRetries
를 사용하여 다시 시도 동작을 설정/비활성화:
// Configure the default for all requests:
const client = new OpenAI({
maxRetries: 0, // default is 2
});
// Or, configure per-request:
await client.chat.completions.create({ messages: [{ role: 'user', content: 'How can I get the name of the current day in Node.js?' }], model: '' }, {
maxRetries: 5,
});
라이브러리 소스 코드 | 패키지(PyPi) | 참조 |
비고
이 라이브러리는 OpenAI에서 유지 관리합니다. 라이브러리의 최신 업데이트를 추적하려면 릴리스 기록을 참조하세요.
Azure OpenAI API 버전 지원
- 이제 v1 GA(일반 공급) API를 통해 GA 및 미리 보기 작업에 모두 액세스할 수 있습니다. 자세한 내용은 API 버전 수명 주기 가이드를 참조하세요.
설치
pip install openai
최신 버전의 경우:
pip install openai --upgrade
인증
리소스에 대한 엔드포인트 및 API 키는 Azure Portal 또는 AI Foundry에서 검색할 수 있습니다.
- Azure> Portal에 로그인하여 리소스 >리소스 관리>키 및 엔드포인트 선택
- AI Foundry 포털>에 로그인하여 리소스 선택
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = OpenAI(
base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key = token_provider
)
응답 API
responses.create()
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = OpenAI(
base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=token_provider,
)
response = client.responses.create(
model="gpt-4.1-nano",
input= "This is a test"
)
print(response.model_dump_json(indent=2))
자세한 예제는 응답 API 설명서를 참조하세요.
responses.create()를 MCP 서버 도구와 함께 사용
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = OpenAI(
base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=token_provider,
)
resp = client.responses.create(
model="gpt-5",
tools=[
{
"type": "mcp",
"server_label": "microsoft_learn",
"server_description": "Microsoft Learn MCP server for searching and fetching Microsoft documentation.",
"server_url": "https://learn.microsoft.com/api/mcp",
"require_approval": "never",
},
],
input="Search for information about Azure Functions",
)
print(resp.output_text)
자세한 예제는 응답 API 설명서를 참조하세요.
채팅
chat.completions.create()
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = OpenAI(
base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=token_provider,
)
completion = client.chat.completions.create(
model="gpt-4o", # Replace with your model deployment name.
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "When was Microsoft founded?"}
]
)
#print(completion.choices[0].message)
print(completion.model_dump_json(indent=2))
chat.completions.create() - 스트리밍
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = OpenAI(
base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=token_provider,
)
completion = client.chat.completions.create(
model="gpt-4o", # Replace with your model deployment name.
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "When was Microsoft founded?"}
],
stream=True
)
for chunk in completion:
if chunk.choices and chunk.choices[0].delta.content is not None:
print(chunk.choices[0].delta.content, end='',)
chat.completions.create() - 이미지 입력
from openai import OpenAI
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
client = OpenAI(
base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=token_provider,
)
completion = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": [
{"type": "text", "text": "What's in this image?"},
{
"type": "image_url",
"image_url": {
"url": "https://raw.githubusercontent.com/MicrosoftDocs/azure-ai-docs/main/articles/ai-foundry/openai/media/how-to/generated-seattle.png",
}
},
],
}
],
max_tokens=300,
)
print(completion.model_dump_json(indent=2))
포함
임베딩 생성()
임베딩은 현재 Azure OpenAI 및 v1 API에서 Microsoft Entra ID를 지원하지 않습니다.
미세 조정
오류 처리
# from openai import OpenAI
# client = OpenAI()
import openai
try:
client.fine_tuning.jobs.create(
model="gpt-4o",
training_file="file-test",
)
except openai.APIConnectionError as e:
print("The server could not be reached")
print(e.__cause__) # an underlying Exception, likely raised within httpx.
except openai.RateLimitError as e:
print("A 429 status code was received; we should back off a bit.")
except openai.APIStatusError as e:
print("Another non-200-range status code was received")
print(e.status_code)
print(e.response)
오류 코드
상태 코드 | 오류 유형 |
---|---|
400 | BadRequestError |
401 | AuthenticationError |
403 | PermissionDeniedError |
404 | NotFoundError |
422 | UnprocessableEntityError |
429 | RateLimitError |
>=500 | InternalServerError |
해당 없음(N/A) | APIConnectionError |
요청 ID
요청의 ID를 검색하려면 _request_id
응답 헤더에 해당하는 x-request-id
속성을 사용할 수 있습니다.
print(completion._request_id)
print(legacy_completion._request_id)
다시 시도
다음 오류는 간단한 지수 백오프와 함께 기본적으로 두 번 자동으로 사용 중지됩니다.
- 연결 오류
- 408 요청 시간 초과
- 429 속도 제한
-
>=
500 내부 오류
max_retries
를 사용하여 다시 시도 동작을 설정/비활성화:
# For all requests
from openai import OpenAI
client = OpenAI(
max_retries=0
)
# max retires for specific requests
client.with_options(max_retries=5).chat.completions.create(
messages=[
{
"role": "user",
"content": "When was Microsoft founded?",
}
],
model="gpt-4o",
)
다음 단계
- 현재 지원되는 모델을 확인하려면 Azure OpenAI 모델 페이지를 확인하세요.