Semantic Kernelと Microsoft Foundry (クラシック) を使用してアプリケーションを開発する

適用対象:Foundry (クラシック) ポータル。 この記事は、新しい Foundry ポータルでは使用できません。 新しいポータルの詳細を確認します

メモ

この記事のリンクは、現在表示している Foundry (クラシック) ドキュメントではなく、新しい Microsoft Foundry ドキュメントのコンテンツを開く場合があります。

この記事では、Microsoft Foundry ポータルの Foundry モデル カタログからデプロイされたモデルを使用してSemantic Kernelを使用する方法を学びます。

重要

Azure AI 推論ベータ SDK は非推奨となり、2026 年 8 月 26 日に廃止されます。 安定した OpenAI SDK を使用して、一般公開されている OpenAI/v1 API に切り替えます。 好みのプログラミング言語に SDK を使用して、 移行ガイド に従って OpenAI/v1 に切り替えます。

前提 条件

環境を構成する

Foundry ポータルでデプロイされた言語モデルを使用するには、プロジェクトに接続するためのエンドポイントと資格情報が必要です。 モデルから必要な情報を取得するには、次の手順に従います。

ヒント

Microsoft Foundry ポータルで左ペインをカスタマイズできるため、次の手順に示す項目とは異なる項目が表示される場合があります。 探しているものが見つからない場合は、左側のウィンドウの下部にある[...もっと見る]を選択してください。

  1. Microsoft Foundry にサインイン>。

  2. モデルがまだ開いていない場合は、モデルが配置されているプロジェクトを開きます。

  3. [モデル + エンドポイント] に移動し、前提条件に示されているようにデプロイしたモデルを選択します。

  4. エンドポイントの URL とキーをコピーします。

    ヒント

    Microsoft Entra IDサポートを使用してモデルをデプロイした場合、キーは必要ありません。

この例では、エンドポイント URL とキーの両方に環境変数を使用します。

export AZURE_AI_INFERENCE_ENDPOINT="<your-model-endpoint-goes-here>"
export AZURE_AI_INFERENCE_API_KEY="<your-key-goes-here>"

エンドポイントとキーを構成したら、エンドポイントに接続するクライアントを作成します。

from semantic_kernel.connectors.ai.azure_ai_inference import AzureAIInferenceChatCompletion

chat_completion_service = AzureAIInferenceChatCompletion(ai_model_id="<deployment-name>")

ヒント

クライアントは、 AZURE_AI_INFERENCE_ENDPOINT 環境変数を自動的に読み取り、 AZURE_AI_INFERENCE_API_KEY してモデルに接続します。 代わりに、コンストラクターの endpoint パラメーターと api_key パラメーターを使用して、エンドポイントとキーをクライアントに直接渡すことができます。

または、エンドポイントがMicrosoft Entra IDをサポートしている場合は、次のコードを使用してクライアントを作成できます。

export AZURE_AI_INFERENCE_ENDPOINT="<your-model-endpoint-goes-here>"
from semantic_kernel.connectors.ai.azure_ai_inference import AzureAIInferenceChatCompletion

chat_completion_service = AzureAIInferenceChatCompletion(ai_model_id="<deployment-name>")

メモ

Microsoft Entra IDを使用する場合は、エンドポイントがその認証方法でデプロイされていること、およびエンドポイントを呼び出すために必要なアクセス許可があることを確認します。

Azure OpenAI モデル

Azure OpenAI モデルを使用している場合は、次のコードを使用してクライアントを作成します。

from azure.ai.inference.aio import ChatCompletionsClient
from azure.identity.aio import DefaultAzureCredential

from semantic_kernel.connectors.ai.azure_ai_inference import AzureAIInferenceChatCompletion

chat_completion_service = AzureAIInferenceChatCompletion(
    ai_model_id="<deployment-name>",
    client=ChatCompletionsClient(
        endpoint=f"{str(<your-azure-open-ai-endpoint>).strip('/')}/openai/deployments/{<deployment_name>}",
        credential=DefaultAzureCredential(),
        credential_scopes=["https://cognitiveservices.azure.com/.default"],
    ),
)

推論パラメーター

AzureAIInferenceChatPromptExecutionSettings クラスを使用して推論を実行する方法を構成できます。

from semantic_kernel.connectors.ai.azure_ai_inference import AzureAIInferenceChatPromptExecutionSettings

execution_settings = AzureAIInferenceChatPromptExecutionSettings(
    max_tokens=100,
    temperature=0.5,
    top_p=0.9,
    # extra_parameters={...},    # model-specific parameters
)

サービスの呼び出し

まず、簡単なチャット履歴を使用してチャット完了サービスを呼び出します。

ヒント

Semantic Kernelは非同期ライブラリであるため、asyncio ライブラリを使用してコードを実行する必要があります。

import asyncio

async def main():
    ...

if __name__ == "__main__":
    asyncio.run(main())
from semantic_kernel.contents.chat_history import ChatHistory

chat_history = ChatHistory()
chat_history.add_user_message("Hello, how are you?")

response = await chat_completion_service.get_chat_message_content(
    chat_history=chat_history,
    settings=execution_settings,
)
print(response)

または、サービスから応答をストリーミングすることもできます。

chat_history = ChatHistory()
chat_history.add_user_message("Hello, how are you?")

response = chat_completion_service.get_streaming_chat_message_content(
    chat_history=chat_history,
    settings=execution_settings,
)

chunks = []
async for chunk in response:
    chunks.append(chunk)
    print(chunk, end="")

full_response = sum(chunks[1:], chunks[0])

長時間にわたる会話を作成する

ループを使用して、実行時間の長い会話を作成できます。

while True:
    response = await chat_completion_service.get_chat_message_content(
        chat_history=chat_history,
        settings=execution_settings,
    )
    print(response)
    chat_history.add_message(response)
    chat_history.add_user_message(user_input = input("User:> "))

応答をストリーミングする場合は、次のコードを使用できます。

while True:
    response = chat_completion_service.get_streaming_chat_message_content(
        chat_history=chat_history,
        settings=execution_settings,
    )

    chunks = []
    async for chunk in response:
        chunks.append(chunk)
        print(chunk, end="")

    full_response = sum(chunks[1:], chunks[0])
    chat_history.add_message(full_response)
    chat_history.add_user_message(user_input = input("User:> "))

埋め込みモデルを使用する

前の手順と同様に環境を構成しますが、 AzureAIInferenceEmbeddings クラスを使用します。

from semantic_kernel.connectors.ai.azure_ai_inference import AzureAIInferenceTextEmbedding

embedding_generation_service = AzureAIInferenceTextEmbedding(ai_model_id="<deployment-name>")

次のコードは、サービスから埋め込みを取得する方法を示しています。

embeddings = await embedding_generation_service.generate_embeddings(
    texts=["My favorite color is blue.", "I love to eat pizza."],
)

for embedding in embeddings:
    print(embedding)