[AI] [.Net] 用WebClient呼叫Azure OpenAI API

  • 46
  • 0
  • AI
  • 2026-01-30

使用網址https://你的資源名稱.openai.azure.com/openai/v1/chat/completions";呼叫AOAI 就不用管api-version, 可參考官網

以 .net 為例, 呼叫方式是:

using System.Text;
using System.Text.Json;
....


OpenAiParameter param = ....//上行class宣告後, 自行依model需求填入資料
string url = "https://你的資源名稱.openai.azure.com/openai/v1/chat/completions";
string key=""//azure的金鑰
string json = JsonSerializer.Serialize(param);
using (StringContent content = new StringContent(json, Encoding.UTF8, MediaType.Json))
{
	Tool.client.DefaultRequestHeaders.Clear();
	Tool.client.DefaultRequestHeaders.Add("api-key", key);
	HttpResponseMessage response = await Tool.client.PostAsync(url, content);
	string result = await response.Content.ReadAsStringAsync();
	if (!response.IsSuccessStatusCode)
		throw new Exception($"HTTP Error: {result}\n{response.RequestMessage}");
	if (string.IsNullOrEmpty(result))
		throw new Exception(result);
	var rslt = JsonSerializer.Deserialize<OpenAiResult>(result);//轉成下行class
後續處理...

其中的有刻class裝上下行資料, 上行長這樣:

namespace TaiwanIsACountry
{
    public class OpenAiParameter
    {
        public enum Role
        {
            system,
            user,
            assistant
        }
        public List<Message> messages { get; set; }
        public double temperature { get; set; } = 1;
        public double top_p { get; set; } = 1;
        public int n { get; set; } = 1;

        public string model { get; set; } 

        #region subclass
        public class Message
        {
            public string role { get; set; }
            public string content { get; set; }
        }
        #endregion
    }
}

下行class全部屬性如下, 但我自己只會開會用的幾個屬性, 而且Message也會直接拿上行的Message class來用, methods是我計價用:

namespace TaiwanIsACountry
{
    public class OpenAiResult
    {
        public List<Choice> choices { get; set; }
        public int created { get; set; }
        public string id { get; set; }
        public string @object { get; set; }
        public List<PromptFilterResult> prompt_filter_results { get; set; }
        public string system_fingerprint { get; set; }
        public List<PiiEntity> piiEntities { get; set; }
        public Usage usage { get; set; }
        public string model { get; set; }

        #region methods
        public int InputTokens() { return usage.prompt_tokens - CachedTokens(); }
        public int CachedTokens() { return usage.prompt_tokens_details?.cached_tokens ?? 0; }
        public int OutputTokens() { return usage.completion_tokens; }
        #endregion

        #region subclass
        public class Choice
        {
            public ContentFilterResults content_filter_results { get; set; }
            public string finish_reason { get; set; }
            public int index { get; set; }
            public object logprobs { get; set; }
            public Message message { get; set; }
        }
        

        public class CompletionTokensDetails
        {
            public int accepted_prediction_tokens { get; set; }
            public int audio_tokens { get; set; }
            public int reasoning_tokens { get; set; }
            public int rejected_prediction_tokens { get; set; }
        }
        public class ContentFilterResults
        {
            public Hate hate { get; set; }
            public SelfHarm self_harm { get; set; }
            public Sexual sexual { get; set; }
            public Violence violence { get; set; }
            public Jailbreak jailbreak { get; set; }
        }
        public class Hate
        {
            public bool filtered { get; set; }
            public string severity { get; set; }
        }

        public class Jailbreak
        {
            public bool filtered { get; set; }
            public bool detected { get; set; }
        }
        

        public class Message
        {
            public List<object> annotations { get; set; }
            public string content { get; set; }
            public object refusal { get; set; }
            public string role { get; set; }
        }

        
        public class PromptFilterResult
        {
            public int prompt_index { get; set; }
            public ContentFilterResults content_filter_results { get; set; }
        }

        public class PromptTokensDetails
        {
            public int audio_tokens { get; set; }
            public int cached_tokens { get; set; }
        }

        public class SelfHarm
        {
            public bool filtered { get; set; }
            public string severity { get; set; }
        }

        public class Sexual
        {
            public bool filtered { get; set; }
            public string severity { get; set; }
        }
        
        public class Usage
        {
            public int completion_tokens { get; set; }
            public CompletionTokensDetails completion_tokens_details { get; set; }
            public int prompt_tokens { get; set; }
            public PromptTokensDetails prompt_tokens_details { get; set; }
            public int total_tokens { get; set; }
        }
        
        public class Violence
        {
            public bool filtered { get; set; }
            public string severity { get; set; }
        }
        #endregion
    }
}

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