Semantic Kernel：Azureでのdeepseek-r1の接続

SemanticKernelはすでにdeepseek-r1をサポートしており、公式ブログは[こちら](https://devblogs.microsoft.com/semantic-kernel/using-deepseek-models-in-semantic-kernel)です。接続のデモも提供されていますが、残念ながらdeepseekはAPIの課金ができず、テストができません。

困難に対して解決策はあるもので、ちょうどMicrosoftが現在Azureでdeepseek-r1のデプロイをサポートしているので、公式の具体的な方法を参照することができます。詳細は以下のURLを参照してください：

[https://azure.microsoft.com/en-us/blog/deepseek-r1-is-now-available-on-azure-ai-foundry-and-github/](https://azure.microsoft.com/en-us/blog/deepseek-r1-is-now-available-on-azure-ai-foundry-and-github/)

また、Azure上のデモは以下の通りです：

```csharp
var apiKey = File.ReadAllText("C:/gpt/deepseekkey.txt");
var handler = new HttpClientHandler()
    {
         ClientCertificateOptions = ClientCertificateOption.Manual,
         ServerCertificateCustomValidationCallback =
             (httpRequestMessage, cert, cetChain, policyErrors) => { return true; }
    };
using (var client = new HttpClient(handler))
{
     var requestBody = @"{
         ""messages"": [
             {
                 ""role"": ""user"",
                 ""content"": ""あなたは誰ですか？""
             }
         ],
         ""max_tokens"": 2048
     }";

     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
     client.BaseAddress = new Uri("https://DeepSeek-R1-iwztj.eastus2.models.ai.azure.com/chat/completions");

     var content = new StringContent(requestBody);
     content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

     HttpResponseMessage response = await client.PostAsync("", content);

     if (response.IsSuccessStatusCode)
     {
         string result = await response.Content.ReadAsStringAsync();
         var ent = System.Text.Json.JsonSerializer.Deserialize<ChatCompletionResponse>(result, new System.Text.Json.JsonSerializerOptions { PropertyNameCaseInsensitive = true });
         foreach (var choice in ent.Choices)
         {
             Console.WriteLine("Result: {0}", choice.Message.Content);
         }
     }
     else
     {
         Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));
         Console.WriteLine(response.Headers.ToString());

         Console.WriteLine("エラー");
     }
}
public class ChatCompletionResponse
{
     public List<Choice> Choices { get; set; }
     public long Created { get; set; }
     public string Id { get; set; }
     public string Model { get; set; }
     public string Object { get; set; }
     public List<PromptFilterResult> PromptFilterResults { get; set; }
     public Usage Usage { get; set; }
}
public class Choice
{
     public ContentFilterResults ContentFilterResults { get; set; }
     public string FinishReason { get; set; }
     public int Index { get; set; }
     public Message Message { get; set; }
}
public class ContentFilterResults
{
     public FilterStatus Hate { get; set; }
     public FilterStatus SelfHarm { get; set; }
     public FilterStatus Sexual { get; set; }
     public FilterStatus Violence { get; set; }
}
public class FilterStatus
{
     public bool Filtered { get; set; }
     public string Severity { get; set; }
}
public class Message
{
     public string Content { get; set; }
     public string ReasoningContent { get; set; }
     public string Role { get; set; }
     public object ToolCalls { get; set; }
}
public class PromptFilterResult
{
     public int PromptIndex { get; set; }
     public ContentFilterResults ContentFilterResults { get; set; }
}
public class Usage
{
     public int CompletionTokens { get; set; }
     public int PromptTokens { get; set; }
     public object PromptTokensDetails { get; set; }
     public int TotalTokens { get; set; }
}
```

結果は以下の通りです：

![画像](https://mmbiz.qpic.cn/sz_mmbiz_png/4CAA63nvHRBmPZuzc6pxO9CtQOjCEceQ0OzXHyu8UFS34VFGzctribhrp16ATO7zC8DAkkOZuH66SUwNH5NWfmg/640?wx_fmt=png&from=appmsg)

SKへの接続方法に変更すると以下の通りです：

```csharp
var apiKey = File.ReadAllText("C:/gpt/deepseekkey.txt");
var chatCompletionService = new OpenAIChatCompletionService(
   endpoint: new Uri("https://DeepSeek-R1-iwztj.eastus2.models.ai.azure.com/"),
   apiKey: apiKey,
   modelId: "deepseek-chat"
);
var chatHistory = new ChatHistory();
chatHistory.AddUserMessage("こんにちは、あなたは誰ですか?");
var reply = await chatCompletionService.GetChatMessageContentAsync(chatHistory);
Console.WriteLine(reply);
```

結果は以下の通りです：

![画像](https://mmbiz.qpic.cn/sz_mmbiz_png/4CAA63nvHRBmPZuzc6pxO9CtQOjCEceQziab6z3rV6fTSlTg9GJQtf997zUTJqQaicElZN1RicicGwpls7jsNnAVoA/640?wx_fmt=png&from=appmsg)

(Translated by GPT)
元のリンク：https://mp.weixin.qq.com/s/DXrEHJf5RfpkYXZB_C5qnA?token=1135395277&lang=zh_CN&wt.mc_id=MVP_325642