다음을 통해 공유


의미 체계 커널 및 Azure AI Foundry를 사용하여 애플리케이션 개발

이 문서에서는 Azure AI Foundry 포털의 Azure AI 모델 카탈로그에서 배포된 모델에서 의미 체계 커널을 사용하는 방법을 알아봅니다.

필수 구성 요소

  • Azure 구독.

  • Azure AI Foundry 포털에서 프로젝트 만들기에 설명된 대로 Azure AI 프로젝트입니다.

  • Azure AI 모델 유추 API를 지원하는 모델이 배포되었습니다. 이 예에서는 Mistral-Large 배포를 사용하지만 원하는 모델을 사용할 수 있습니다. LlamaIndex에서 포함 기능을 사용하려면 cohere-embed-v3-multilingual과 같은 포함 모델이 필요합니다.

  • pip를 포함하여 Python 3.10 이상이 설치되었습니다.

  • 의미 체계 커널이 설치되었습니다. 다음을 사용하여 수행할 수 있습니다.

    pip install semantic-kernel
    
  • 이 예제에서는 Azure AI 모델 유추 API를 사용하여 작업하므로 관련 Azure 종속성을 설치합니다. 다음을 사용하여 수행할 수 있습니다.

    pip install semantic-kernel[azure]
    

환경 구성

Azure AI Foundry 포털에 배포된 LLM을 사용하려면 엔드포인트 및 자격 증명을 연결해야 합니다. 사용하려는 모델에서 필요한 정보를 가져오려면 다음 단계를 따릅니다.

  1. Azure AI Foundry 포털이동합니다.

  2. 아직 열려 있지 않은 경우 모델이 배포된 프로젝트를 엽니다.

  3. 모델 + 엔드포인트이동하여 필수 구성 요소에 표시된 대로 배포한 모델을 선택합니다.

  4. 엔드포인트 URL과 키를 복사합니다.

    엔드포인트에서 엔드포인트 URI와 키를 복사하는 옵션의 스크린샷.

    모델이 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_API_KEY 모델에 연결합니다AZURE_AI_INFERENCE_ENDPOINT. 그러나 생성자의 매개 변수 및 매개 변수를 통해 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
)

서비스 호출

먼저 간단한 채팅 기록을 사용하여 채팅 완료 서비스를 호출해 보겠습니다.

의미 체계 커널은 비동기 라이브러리이므로 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)