AzureのDeepSeek-R1やーる（Python3.11）

# はじめに
AzureのDeepSeek-R1をやっていきまーす

# 開発環境
- Windows 10 PC
- Python 3.11

# 導入

1．AzureポータルからAzure AI Foundryを開く
2．Hubを作成（East USリージョン）
3．新しいプロジェクトを作成
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/ed2f95c3-510f-6cca-2b85-89d89f529a1a.png)

4．プロジェクト名を入れて作成
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/d3ebfff8-3f5c-1c98-eef5-4039801182ca.png)

5．エンドポイントとキーが表示される
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/e2144e4a-34a2-53e5-44b6-d8a986ca17ae.png)

6．モデルカタログからDeepSeek-R1の紹介のCheck out modelをクリック

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/aac7089a-79a5-42ba-63e5-a0aa77c8f277.png)

7．デプロイする
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/28777221-3cb6-cbd3-74f3-fa46f6ecd7fd.png)

サーバーレス API は以下のリージョンでご利用いただけます: [eastus2, westus3, northcentralus, eastus, southcentralus, westus]。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/8dd0d19f-61af-3b93-1fe4-95a639e2ce00.png)

価格
DeepSeek R1 use is currently priced at $0, and use is subject to rate limits which may change at any time. Pricing may change, and your continued use will be subject to the new price. The model is in preview; a new deployment may be required for continued use.

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/c6b487cd-e75a-359d-0ea1-2b9fcb61301b.png)

8．デプロイ完了
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/9d184ec4-cd6e-b30e-ca4c-a897433db38c.png)

# 実行
## チャットプレイグラウンド

1．「こんにちは」を入力

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/acb3c596-c7d3-86fe-8702-5a27fdd8c6d1.png)

~~~
Alright, I just got a message saying "こんにちは", which is "Konnichiwa" in Japanese. That means "Hello" or "Good afternoon."
Okay, the user greeted me in Japanese. I should respond appropriately. Let me recall the proper response. Usually, you'd reply with the same greeting or a friendly response. Since they used "こんにちは", it's a standard greeting, so responding with "こんにちは！元気ですか？" (Hello! How are you?) seems right.

Wait, but maybe they just wanted to test if I know Japanese. Let me check if there's any more context. The user only sent that one message. Should I ask if they need help with something specific, or is a simple greeting sufficient?

Hmm, as an assistant, I should keep it open. So start with returning the greeting and then offer help. Maybe like, "こんにちは！元気ですか？何かお手伝いできることはありますか？" which is "Hello! How are you? Is there anything I can help you with?"

Wait, but maybe mixing Japanese and the next part in Japanese. But the user might prefer continuing in Japanese or switch to another language. But their original message is only "こんにちは", no other indication. Let's see what the first response is.

Alternatively, since the user wrote in Japanese, maybe they want the rest of the conversation in Japanese. But I should also check if they need assistance in another language. Hmm, perhaps respond in Japanese first and offer help in English or the language they prefer. Wait, no, the user might have a profile or settings. But since it's a new conversation, maybe stick to the same language.

Wait, the user wrote "こんにちは" and maybe expects a response in Japanese. Maybe I should reply in Japanese, then offer help. Like:

こんにちは！ご用件がありますか？

Or "Hello! Do you have any business?" Not sure if that's the best translation. Maybe "Is there something I can help you with?"

Alternatively, make it friendlier. "こんにちは！どうされましたか？" (Hello! How can I assist you?)

But perhaps including both Japanese and English. Wait, the user might expect me to continue in Japanese. But if not, it's better to switch to the user's main language. Wait, maybe check the user's settings. But since it's a text-based interaction, maybe the initial response should be in Japanese and then offer help in both languages.

Alternatively, since the user might be testing if I understand Japanese, confirm and then proceed. Hmm, perhaps keep the response respectful and open. So:

"こんにちは！何かお手伝いできることはありますか？" → "Hello! Is there anything I can help you with?"

That's concise and friendly. Yes, that should work.

こんにちは！何かお手伝いできることはありますか？
~~~

めっちゃ長いですね…

2．「日本語でお願いします」を入力

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/63863/1379f859-9d2c-e5ce-1ab5-0a72c8a42606.png)

~~~
好的，用户现在希望我用日语来回复。之前的对话历史里，用户先用中文打招呼“こんにちは”，然后我回应了中文。用户接着纠正说要使用日语，所以我需要切换成日语。
首先，我需要确认用户当前的需求是什么。他们可能需要进一步的帮助，或者可能有一个特定的问题需要用日语沟通。考虑到用户已经明确要求使用日语，我应该在此后的回复中保持使用日语，除非用户另有指示。

接下来要检查的是用户是否有明确的问题需要解决，还是只是测试我的语言切换能力。用户当前的查询只是“日本語でお願いします”，所以可能需要进一步询问他们需要什么帮助。

但同时，之前的回复已经以日语回答了问候，但可能用户希望继续日语对话，所以需要保持一致性。需要确保接下来的回答全部使用日语，避免混合使用其他语言，特别是在用户已经明确要求的情况下。

另外要注意的是，日语中有不同的敬语和礼貌程度，作为AI助手，通常会使用礼貌但不过于复杂的敬体（です/ます形），这样既尊重用户又保持易懂。避免使用过于随便的表达方式。

最后，确保回应用户的所有需求，如果有需要进一步的信息，可以询问用户具体的需求点以提供更准确的帮助。

わかりました！日本語で対応させていただきますね。何かお手伝いできることがあれば、どんなことでもおっしゃってください。質問やお悩み事、翻訳のお手伝いなど、いつでもどうぞ！(´･ω･`)
~~~

中国語になりました…


## API

### azure-ai-inference
1．Pythonのサンプルコードを作成

~~~.py
# pip install azure-ai-inference
import os
from azure.ai.inference import ChatCompletionsClient
from azure.core.credentials import AzureKeyCredential
from dotenv import load_dotenv

load_dotenv()

api_key = os.getenv("AZURE_INFERENCE_CREDENTIAL", "")
if not api_key:
    raise Exception("A key should be provided to invoke the endpoint")


client = ChatCompletionsClient(
    endpoint="https://DeepSeek-R1-isjss.eastus.models.ai.azure.com",
    credential=AzureKeyCredential(api_key),
)

model_info = client.get_model_info()
print("Model name:", model_info.model_name)
print("Model type:", model_info.model_type)
print("Model provider name:", model_info.model_provider_name)

payload = {
    "messages": [
        {"role": "user", "content": "I am going to Paris, what should I see?"},
        {
            "role": "assistant",
            "content": "Paris, the capital of France, is known for its stunning architecture, art museums, historical landmarks, and romantic atmosphere. Here are some of the top attractions to see in Paris:\n\n1. The Eiffel Tower: The iconic Eiffel Tower is one of the most recognizable landmarks in the world and offers breathtaking views of the city.\n2. The Louvre Museum: The Louvre is one of the world's largest and most famous museums, housing an impressive collection of art and artifacts, including the Mona Lisa.\n3. Notre-Dame Cathedral: This beautiful cathedral is one of the most famous landmarks in Paris and is known for its Gothic architecture and stunning stained glass windows.\n\nThese are just a few of the many attractions that Paris has to offer. With so much to see and do, it's no wonder that Paris is one of the most popular tourist destinations in the world.",
        },
        {"role": "user", "content": "What is so great about #1?"},
    ],
    "max_tokens": 2048,
}
response = client.complete(payload)

print("Response:", response.choices[0].message.content)
print("Model:", response.model)
print("Usage:")
print("	Prompt tokens:", response.usage.prompt_tokens)
print("	Total tokens:", response.usage.total_tokens)
print("	Completion tokens:", response.usage.completion_tokens)

~~~

2．.envの作成
~~~.env
AZURE_INFERENCE_CREDENTIAL=<INSERT-YOUR-API-KEY>
~~~


3．ライブラリのインストール

pip install azure-ai-inference

4．実行

python main.py

~~~
Model name: DeepSeek-R1
Model type: chat-completion
Model provider name: DeepSeek
Response: <think>
Okay, so the user previously asked about must-see places in Paris, and I listed the Eiffel Tower as number one. Now they're asking, "What is so great about #1?" referring to the Eiffel Tower. I need to explain why it's considered such a top attraction.

Let me start by recalling what makes the Eiffel Tower special. First, it's an iconic symbol of Paris and France. Then there's the historical aspect—built for the 1889 World's Fair, initially controversial but now beloved. The engineering feat is impressive given the time it was built. The views from the tower must be breathtaking, allowing visitors to see the entire city. The light shows at night add to its charm. It's also a cultural symbol, often associated with romance and featured in many movies. Additionally, it has different levels for visitors to explore with restaurants and exhibits. Accessibility is another point—almost everyone knows about it, making it a must-visit even for first-time travelers. Maybe also mention how it's a focal point for events and celebrations. I should organize these points into sections for clarity, like historical significance, design, views, etc. Make sure to highlight the emotional appeal too, why people feel connected to it beyond just being a structure. Check if there's any interesting fact I can include, like the number of visitors annually or 
how it was the tallest man-made structure for a time. Avoid any technical jargon so it's easy to understand. Ensure the response flows well and covers all the key aspects that make the Eiffel Tower great. Need to keep it engaging and informative without being too long. Lastly, maybe end with a recommendation to visit at different times of the day for varied experiences. Oh, and mention Gustave Eiffel's role in its creation. Got it.     
</think>

The Eiffel Tower (#1) is iconic for many reasons, blending history, engineering, and cultural significance. Here's why it’s so special:

### **1. Symbol of Paris (and France)**
The Eiffel Tower is the ultimate emblem of Paris, instantly recognizable worldwide. Built for the 1889 World’s Fair to celebrate the 100th anniversary of the French Revolution, it became a bold statement of French innovation and artistry.

---

### **2. Engineering Marvel**
- **Record-breaking design**: At 1,083 feet (330 meters), it was the tallest man-made structure in the world until 1930.
- **Innovative construction**: Designed by Gustave Eiffel, its lattice structure used 7,300 tons of iron and 18,038 metal parts, assembled with remarkable precision in just 2 years.
- **Defied criticism**: Initially hated by artists and intellectuals (who called it a "metal asparagus"), it became a testament to resilience and creativity.

---

### **3. Breathtaking Views**
From its three observation decks, you’ll get panoramic views of Paris’s landmarks: the Seine River, the Louvre, Sacré-Cœur, and more. Nighttime visits are magical as the city lights up.

---

### **4. Ever-Changing Experience**
- **The Sparkle**: Every evening after dark, the tower *shimmers* for 5 minutes each hour with 20,000 golden bulbs—a dazzling spectacle.
- **Seasonal vibes**: Visit in spring for cherry blossoms at its base, in winter for ice-skating on the first 
floor, or during Bastille Day fireworks (July 14) for an unforgettable show.

---

### **5. Cultural Immortality**
The Eiffel Tower embodies romance, adventure, and artistic inspiration. It’s starred in countless films (e.g., *Midnight in Paris*, *Ratatouille*) and literature, and has hosted proposals, weddings, and global events (like Olympic ceremonies).

---

### **6. Accessible & Multifaceted**
- **Dining**: Sip champagne at the champagne bar, or enjoy gourmet meals at *Le Jules Verne* (Michelin-starred- **Thrill-seekers**: Take the glass-floored walkway on the first floor or climb stairs for a unique workout! 

---

### **Why It’s "Great"**
The Eiffel Tower transcends being a mere monument—it’s a living part of Paris’s soul. Whether you admire it from afar, picnic on the Champ de Mars, or ascend to its summit, it connects you to the city’s past, present, and timeless allure. ✨
**Pro tip**: Visit at sunset for golden-hour views, then stay to watch the lights come alive!
Model: DeepSeek-R1
Usage:
        Prompt tokens: 200
        Total tokens: 1196
        Completion tokens: 996
~~~

<!--
json

~~~.json
{
  "messages": [
    {
      "role": "user",
      "content": "I am going to Paris, what should I see?"
    },
    {
      "role": "assistant",
      "content": "Paris, the capital of France, is known for its stunning architecture, art museums, historical landmarks, and romantic atmosphere. Here are some of the top attractions to see in Paris:\n\n1. The Eiffel Tower: The iconic Eiffel Tower is one of the most recognizable landmarks in the world and offers breathtaking views of the city.\n2. The Louvre Museum: The Louvre is one of the world's largest and most famous museums, housing an impressive collection of art and artifacts, including the Mona Lisa.\n3. Notre-Dame Cathedral: This beautiful cathedral is one of the most famous landmarks in Paris and is known for its Gothic architecture and stunning stained glass windows.\n\nThese are just a few of the many attractions that Paris has to offer. With so much to see and do, it's no wonder that Paris is one of the most popular tourist destinations in the world."
    },
    {
      "role": "user",
      "content": "What is so great about #1?"
    }
  ],
  "max_tokens": 2048
}
~~~

C#

~~~.cs
// .NET Framework 4.7.1 or greater must be used

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace CallRequestResponseService
{
    class Program
    {
        static void Main(string[] args)
        {
            InvokeRequestResponseService().Wait();
        }

        static async Task InvokeRequestResponseService()
        {
            var handler = new HttpClientHandler()
            {
                ClientCertificateOptions = ClientCertificateOption.Manual,
                ServerCertificateCustomValidationCallback =
                        (httpRequestMessage, cert, cetChain, policyErrors) => { return true; }
            };
            using (var client = new HttpClient(handler))
            {
                // Request data goes here
                // The example below assumes JSON formatting which may be updated
                // depending on the format your endpoint expects.
                // More information can be found here:
                // https://docs.microsoft.com/azure/machine-learning/how-to-deploy-advanced-entry-script
                var requestBody = @"{
                  ""messages"": [
                    {
                      ""role"": ""user"",
                      ""content"": ""I am going to Paris, what should I see?""
                    },
                    {
                      ""role"": ""assistant"",
                      ""content"": ""Paris, the capital of France, is known for its stunning architecture, art museums, historical landmarks, and romantic atmosphere. Here are some of the top attractions to see in Paris:\n\n1. The Eiffel Tower: The iconic Eiffel Tower is one of the most recognizable landmarks in the world and offers breathtaking views of the city.\n2. The Louvre Museum: The Louvre is one of the world's largest and most famous museums, housing an impressive collection of art and artifacts, including the Mona Lisa.\n3. Notre-Dame Cathedral: This beautiful cathedral is one of the most famous landmarks in Paris and is known for its Gothic architecture and stunning stained glass windows.\n\nThese are just a few of the many attractions that Paris has to offer. With so much to see and do, it's no wonder that Paris is one of the most popular tourist destinations in the world.""
                    },
                    {
                      ""role"": ""user"",
                      ""content"": ""What is so great about #1?""
                    }
                  ],
                  ""max_tokens"": 2048
                }";
                
                // Replace this with the primary/secondary key, AMLToken, or Microsoft Entra ID token for the endpoint
                const string apiKey = "";
                if (string.IsNullOrEmpty(apiKey))
                {
                    throw new Exception("A key should be provided to invoke the endpoint");
                }
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Bearer", apiKey);
                client.BaseAddress = new Uri("https://DeepSeek-R1-isjss.eastus.models.ai.azure.com");

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

                // WARNING: The 'await' statement below can result in a deadlock
                // if you are calling this code from the UI thread of an ASP.Net application.
                // One way to address this would be to call ConfigureAwait(false)
                // so that the execution does not attempt to resume on the original context.
                // For instance, replace code such as:
                //      result = await DoSomeTask()
                // with the following:
                //      result = await DoSomeTask().ConfigureAwait(false)
                HttpResponseMessage response = await client.PostAsync("", content);

                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("Result: {0}", result);
                }
                else
                {
                    Console.WriteLine(string.Format("The request failed with status code: {0}", response.StatusCode));

                    // Print the headers - they include the requert ID and the timestamp,
                    // which are useful for debugging the failure
                    Console.WriteLine(response.Headers.ToString());

                    string responseContent = await response.Content.ReadAsStringAsync();
                    Console.WriteLine(responseContent);
                }
            }
        }
    }
}

~~~
-->

### requests

1．azure-ai-inferenceらいぶらｒなしで実行

~~~.py
import os
import requests
from dotenv import load_dotenv


def invoke_request_response_service():
    load_dotenv()

    # APIキーの設定
    api_key = os.getenv("AZURE_INFERENCE_CREDENTIAL", "")
    if not api_key:
        raise Exception("A key should be provided to invoke the endpoint")

    # エンドポイントとヘッダーの設定
    base_url = "https://DeepSeek-R1-isjss.eastus.models.ai.azure.com"
    endpoint = "/v1/chat/completions"
    headers = {"Content-Type": "application/json", "Authorization": f"Bearer {api_key}"}

    # リクエストボディの設定
    payload = {
        "messages": [
            {"role": "user", "content": "I am going to Paris, what should I see?"},
            {
                "role": "assistant",
                "content": "Paris, the capital of France, is known for its stunning architecture, art museums, historical landmarks, and romantic atmosphere. Here are some of the top attractions to see in Paris:\n\n1. The Eiffel Tower: The iconic Eiffel Tower is one of the most recognizable landmarks in the world and offers breathtaking views of the city.\n2. The Louvre Museum: The Louvre is one of the world's largest and most famous museums, housing an impressive collection of art and artifacts, including the Mona Lisa.\n3. Notre-Dame Cathedral: This beautiful cathedral is one of the most famous landmarks in Paris and is known for its Gothic architecture and stunning stained glass windows.\n\nThese are just a few of the many attractions that Paris has to offer. With so much to see and do, it's no wonder that Paris is one of the most popular tourist destinations in the world.",
            },
            {"role": "user", "content": "What is so great about #1?"},
        ],
        "max_tokens": 2048,
    }

    try:
        # リクエストの送信
        response = requests.post(base_url + endpoint, headers=headers, json=payload)
        response.raise_for_status()  # エラーチェック

        # レスポンスの処理
        response_json = response.json()
        print("Response:", response_json["choices"][0]["message"]["content"])
        print("Model:", response_json["model"])
        print("Usage:")
        print("\tPrompt tokens:", response_json["usage"]["prompt_tokens"])
        print("\tTotal tokens:", response_json["usage"]["total_tokens"])
        print("\tCompletion tokens:", response_json["usage"]["completion_tokens"])

    except requests.exceptions.RequestException as e:
        print(
            f"The request failed with status code: {response.status_code if 'response' in locals() else 'N/A'}"
        )
        print("Headers:", response.headers if "response" in locals() else "N/A")
        print("Response content:", response.text if "response" in locals() else str(e))


if __name__ == "__main__":
    invoke_request_response_service()
~~~

2．実行結果

~~~
Response: <think>
Okay, the user previously asked for recommendations on what to see in Paris and I gave them a list where the Eiffel Tower was number 1. Now they're asking, "What is so great about #1?" I need to explain why the Eiffel Tower is considered such a great attraction.

First, I should highlight its iconic status. It's a symbol of Paris and France. Then mention the views from the top, since that's a major draw. The history might be important too—like its construction for the World's Fair and how it was initially criticized but became beloved.

Also, the different experiences depending on the time of day: visiting during the day versus at night when it's lit up. Maybe touch on the engineering aspect, Gustave Eiffel's design. The cultural impact—how it's featured in movies, art, etc. Could also note that it's a versatile structure with restaurants and event spaces, so it's not just a static monument.

Need to make sure the response is comprehensive but not too technical. Keep it engaging, maybe add that it's a must-see for first-time visitors. Also, check if there are any special facts, like the number of visitors annually or interesting events held there. Make sure to address why someone would find it great beyond just being famous.
</think>

The Eiffel Tower (#1 on the list) is iconic for many reasons, blending history, engineering, and cultural significance into a single landmark. Here’s why it’s so special:

### 1. **Symbol of Paris and France**
   - It’s the ultimate emblem of Paris, evoking romance, elegance, and artistic inspiration. For many, it represents the essence of France itself.

### 2. **Engineering Marvel**
   - Built for the 1889 World’s Fair, it was the tallest human-made structure in the world (324 meters/1,063 feet) until 1930. Gustave Eiffel’s iron lattice design was revolutionary for its time and showcased France’s industrial prowess.

### 3. **Breathtaking Views**
   - The three observation decks (especially the top level) offer unparalleled panoramic views of Paris. Seeing landmarks like the Arc de Triomphe, the Seine River, and Montmartre from above is unforgettable.

### 4. **Ever-Changing Experience**
   - **By day:** Its intricate ironwork and grandeur are awe-inspiring up close.
   - **At night:** It sparkles with thousands of golden lights for 5 minutes every hour, creating a magical atmosphere.

### 5. **Cultural Legacy**
   - Featured in countless films, books, and artworks, the tower has become a global pop-culture symbol (e.g., *Midnight in Paris*, *Ratatouille*).

### 6. **A Living Monument**
   - It’s not just a static attraction:
     - Dine at **Le Jules Verne** (a Michelin-starred restaurant on the second floor).
     - Attend seasonal events like ice-skating on the first level in winter.
     - Watch the spectacular fireworks display on Bastille Day (July 14).

### 7. **A Story of Resilience**
   - Initially hated by many Parisians (including artists like Guy de Maupassant), it was nearly dismantled after 20 years. Today, it’s beloved worldwide and remains a testament to innovation and perseverance.

---
**Why it’s a must-do:** Whether you’re admiring it from the Champ de Mars, ascending to the top, or picnicking under its shadow, the Eiffel Tower connects you to Paris’s past, present, and timeless allure. 🌟
Model: DeepSeek-R1
Usage:
        Prompt tokens: 200
        Total tokens: 984
        Completion tokens: 784
~~~

お疲れ様でした！