[AI] [Python] 用requests呼叫Azure OpenAi API

  • 49
  • 0
  • AI
  • 2025-07-21

openai元件一直改版,可直接打REST API使用
官網參考: Azure OpenAI in Azure AI Foundry Models REST API reference - Azure OpenAI | Microsoft Learn

能用各種語言不用裝套件直接打, 也能用Postman測

import requests
import urllib3

API_KEY = "*********"
version = "2024-10-21"
model = "gpt-4o"
url = "https://****.openai.azure.com/"

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

headers = {"Content-Type": "application/json","api-key": API_KEY}
ENDPOINT = f"{url}openai/deployments/{model}/chat/completions?api-version={version}"
payload = {"messages": [{"role": "user", "content": "我國台灣總統是誰"}]}
try:
    response = requests.post(ENDPOINT, headers=headers, json=payload, verify=False)
    response.raise_for_status()
    print(response.json()['choices'][0]['message']['content'])
except Exception as e:
    print(f"錯誤: {e}")

上行的json可參考官網和以下: 

{"messages": [
    {
      "role": "system",
      "content": "你是一個樂於助人的中文客服助理。"
    },
    {
      "role": "user",
      "content": "我想了解 Azure OpenAI 怎麼用。"
    },
    {
      "role": "assistant",
      "content": "Azure OpenAI 讓你可以透過 REST API 呼叫 GPT 模型,進行自然語言處理任務。"
    },
    {"role": "user", "content": "幫我列出以下內容的廠商名稱和請款總金額:\r{0}"}    
    ],
  "temperature": 0.7,
  "top_p":1,
  "n": 1
  }

若有錯誤:[InsecureRequestWarning: Unverified HTTPS request is being made to host]
可加urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

若有錯誤: HTTPSConnectionPool(host='.openai.azure.com', port=443): Max retries exceeded with url:/…/…/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain
可在requests.postverify=False

Taiwan is a country. 臺灣是我的國家