모델(Model Clients)

모델(Model Clients)

많은 경우 에이전트는 OpenAI, Azure OpenAI 같은 LLM 모델 서비스나 로컬 모델에 접근해야 해요. 공급자가 많고 API도 각각 다르기 때문에, autogen-core모델 클라이언트의 프로토콜을 구현하고 autogen-ext는 인기 있는 모델 서비스를 위한 모델 클라이언트 세트를 구현해요. AgentChat은 이 모델 클라이언트들을 사용해 모델 서비스와 상호작용할 수 있습니다.

출처: Models — AutoGen 공식 문서

이 섹션은 사용 가능한 모델 클라이언트를 간단히 소개해요. 직접 사용하는 방법에 대한 자세한 내용은 Core API 문서의 Model Clients를 참고하세요.

참고: 아래 클라이언트들과 함께 쓸 캐싱 래퍼로는 ChatCompletionCache를 보세요.

모델 호출 로그

AutoGen은 표준 Python logging 모듈을 사용해 모델 호출·응답 같은 이벤트를 기록해요. 로거 이름은 autogen_core.EVENT_LOGGER_NAME이고, 이벤트 타입은 LLMCall이에요.

import logging

from autogen_core import EVENT_LOGGER_NAME

logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger(EVENT_LOGGER_NAME)
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.INFO)

OpenAI

OpenAI 모델에 접근하려면 openai 확장을 설치하면 돼요. 그러면 OpenAIChatCompletionClient를 사용할 수 있어요.

pip install "autogen-ext[openai]"

OpenAI에서 API 키도 받아야 해요.

from autogen_ext.models.openai import OpenAIChatCompletionClient

openai_model_client = OpenAIChatCompletionClient(
    model="gpt-4o-2024-08-06",
    # api_key="sk-...", # Optional if you have an OPENAI_API_KEY environment variable set.
)

모델 클라이언트를 테스트하려면 다음 코드를 쓰세요.

from autogen_core.models import UserMessage

result = await openai_model_client.create([UserMessage(content="What is the capital of France?", source="user")])
print(result)
await openai_model_client.close()

참고: 이 클라이언트는 OpenAI 호환 엔드포인트에서 호스팅되는 모델에도 쓸 수 있지만, 이 기능은 테스트하지 않았어요. 자세한 내용은 OpenAIChatCompletionClient를 보세요.

Azure OpenAI

마찬가지로 azureopenai 확장을 설치하면 AzureOpenAIChatCompletionClient를 사용할 수 있어요.

pip install "autogen-ext[openai,azure]"

클라이언트를 쓰려면 배포(deployment) ID, Azure Cognitive Services 엔드포인트, API 버전, 모델 기능(capabilities)을 제공해야 해요. 인증은 API 키 또는 Azure Active Directory(AAD) 토큰 자격 증명 중 하나를 제공하면 됩니다.

아래 코드는 AAD 인증을 사용하는 방법을 보여줘요. 사용되는 ID에는 Cognitive Services OpenAI User 역할이 할당되어 있어야 해요.

from autogen_core.models import UserMessage
from autogen_ext.auth.azure import AzureTokenProvider
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient
from azure.identity import DefaultAzureCredential

# Create the token provider
token_provider = AzureTokenProvider(
    DefaultAzureCredential(),
    "https://cognitiveservices.azure.com/.default",
)

az_model_client = AzureOpenAIChatCompletionClient(
    azure_deployment="{your-azure-deployment}",
    model="{model-name, such as gpt-4o}",
    api_version="2024-06-01",
    azure_endpoint="https://{your-custom-endpoint}.openai.azure.com/",
    azure_ad_token_provider=token_provider,  # Optional if you choose key-based authentication.
    # api_key="sk-...", # For key-based authentication.
)

result = await az_model_client.create([UserMessage(content="What is the capital of France?", source="user")])
print(result)
await az_model_client.close()

Azure 클라이언트를 직접 사용하는 방법이나 더 자세한 내용은 여기를 참고하세요.

Azure AI Foundry

Azure AI Foundry(이전 이름 Azure AI Studio)는 Azure에서 호스팅되는 모델을 제공해요. 이 모델을 사용하려면 AzureAIChatCompletionClient를 쓰면 됩니다.

이 클라이언트를 쓰려면 azure extra를 설치해야 해요.

pip install "autogen-ext[azure]"

아래는 이 클라이언트를 GitHub Marketplace의 Phi-4 모델과 함께 사용하는 예시예요.

import os

from autogen_core.models import UserMessage
from autogen_ext.models.azure import AzureAIChatCompletionClient
from azure.core.credentials import AzureKeyCredential

client = AzureAIChatCompletionClient(
    model="Phi-4",
    endpoint="https://models.github.ai/inference",
    # To authenticate with the model you will need to generate a personal access token (PAT) in your GitHub settings.
    # Create your PAT token by following instructions here: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens
    credential=AzureKeyCredential(os.environ["GITHUB_TOKEN"]),
    model_info={
        "json_output": False,
        "function_calling": False,
        "vision": False,
        "family": "unknown",
        "structured_output": False,
    },
)

result = await client.create([UserMessage(content="What is the capital of France?", source="user")])
print(result)
await client.close()

Anthropic (실험적)

AnthropicChatCompletionClient를 사용하려면 anthropic extra를 설치해야 해요. 내부적으로는 anthropic 파이썬 SDK를 사용해 모델에 접근합니다. Anthropic에서 API 키도 받아야 해요.

# !pip install -U "autogen-ext[anthropic]"
from autogen_core.models import UserMessage
from autogen_ext.models.anthropic import AnthropicChatCompletionClient

anthropic_client = AnthropicChatCompletionClient(model="claude-3-7-sonnet-20250219")
result = await anthropic_client.create([UserMessage(content="What is the capital of France?", source="user")])
print(result)
await anthropic_client.close()

Ollama (실험적)

Ollama는 머신 로컬에서 모델을 실행할 수 있는 로컬 모델 서버예요.

참고: 작은 로컬 모델은 보통 클라우드의 큰 모델만큼 강력하지 않아요. 어떤 태스크에서는 성능이 좋지 않을 수 있고 출력이 예상 밖일 수도 있어요.

Ollama를 사용하려면 ollama 확장을 설치하고 OllamaChatCompletionClient를 사용하세요.

pip install -U "autogen-ext[ollama]"
from autogen_core.models import UserMessage
from autogen_ext.models.ollama import OllamaChatCompletionClient

# Assuming your Ollama server is running locally on port 11434.
ollama_model_client = OllamaChatCompletionClient(model="llama3.2")

response = await ollama_model_client.create([UserMessage(content="What is the capital of France?", source="user")])
print(response)
await ollama_model_client.close()

Gemini (실험적)

Gemini는 현재 OpenAI 호환 API(베타)를 제공해요. 그래서 OpenAIChatCompletionClient를 Gemini API와 함께 사용할 수 있습니다.

참고: 일부 모델 공급자가 OpenAI 호환 API를 제공한다 해도, 여전히 사소한 차이가 있을 수 있어요. 예를 들어 finish_reason 필드가 응답에서 다를 수 있죠.

from autogen_core.models import UserMessage
from autogen_ext.models.openai import OpenAIChatCompletionClient

model_client = OpenAIChatCompletionClient(
    model="gemini-1.5-flash-8b",
    # api_key="GEMINI_API_KEY",
)

response = await model_client.create([UserMessage(content="What is the capital of France?", source="user")])
print(response)
await model_client.close()

또한 Gemini가 새 모델을 추가하면 model_info 필드로 모델 기능을 정의해야 할 수도 있어요. 예를 들어 gemini-2.0-flash-lite나 유사한 새 모델을 사용하려면 다음 코드를 쓸 수 있어요.

from autogen_core.models import UserMessage
from autogen_ext.models.openai import OpenAIChatCompletionClient
from autogen_core.models import ModelInfo

model_client = OpenAIChatCompletionClient(
    model="gemini-2.0-flash-lite",
    model_info=ModelInfo(vision=True, function_calling=True, json_output=True, family="unknown", structured_output=True)
    # api_key="GEMINI_API_KEY",
)

response = await model_client.create([UserMessage(content="What is the capital of France?", source="user")])
print(response)
await model_client.close()

Llama API (실험적)

Llama API는 Meta의 자사 API 제품이에요. 현재 OpenAI 호환 엔드포인트를 제공합니다. 그래서 OpenAIChatCompletionClient를 Llama API와 함께 쓸 수 있어요.

이 엔드포인트는 다음 OpenAI 클라이언트 라이브러리 기능을 완전히 지원해요.

  • 채팅 완성(Chat completions)
  • 모델 선택
  • Temperature/sampling
  • 스트리밍
  • 이미지 이해
  • 구조화된 출력(JSON 모드)
  • 함수 호출(도구)
from pathlib import Path

from autogen_core import Image
from autogen_core.models import UserMessage
from autogen_ext.models.openai import OpenAIChatCompletionClient

# Text
model_client = OpenAIChatCompletionClient(
    model="Llama-4-Scout-17B-16E-Instruct-FP8",
    # api_key="LLAMA_API_KEY"
)

response = await model_client.create([UserMessage(content="Write me a poem", source="user")])
print(response)
await model_client.close()

# Image
model_client = OpenAIChatCompletionClient(
    model="Llama-4-Maverick-17B-128E-Instruct-FP8",
    # api_key="LLAMA_API_KEY"
)
image = Image.from_file(Path("test.png"))

response = await model_client.create([UserMessage(content=["What is in this image", image], source="user")])
print(response)
await model_client.close()

Semantic Kernel 어댑터

SKChatCompletionAdapter를 사용하면 Semantic Kernel 모델 클라이언트를 요구되는 인터페이스에 맞춰 적응시켜 ChatCompletionClient로 사용할 수 있어요.

이 어댑터를 쓰려면 관련 공급자 extras를 설치해야 합니다.

설치할 수 있는 extras 목록:

  • semantic-kernel-anthropic: Anthropic 모델을 사용하려면 이 extra를 설치.
  • semantic-kernel-google: Google Gemini 모델을 사용하려면 이 extra를 설치.
  • semantic-kernel-ollama: Ollama 모델을 사용하려면 이 extra를 설치.
  • semantic-kernel-mistralai: MistralAI 모델을 사용하려면 이 extra를 설치.
  • semantic-kernel-aws: AWS 모델을 사용하려면 이 extra를 설치.
  • semantic-kernel-hugging-face: Hugging Face 모델을 사용하려면 이 extra를 설치.

예를 들어 Anthropic 모델을 사용하려면 semantic-kernel-anthropic을 설치해야 해요.

# pip install "autogen-ext[semantic-kernel-anthropic]"

이 어댑터를 쓰려면 Semantic Kernel 모델 클라이언트를 만들고 어댑터에 전달해야 해요.

예를 들어 Anthropic 모델을 사용한다면:

import os

from autogen_core.models import UserMessage
from autogen_ext.models.semantic_kernel import SKChatCompletionAdapter
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.anthropic import AnthropicChatCompletion, AnthropicChatPromptExecutionSettings
from semantic_kernel.memory.null_memory import NullMemory

sk_client = AnthropicChatCompletion(
    ai_model_id="claude-3-5-sonnet-20241022",
    api_key=os.environ["ANTHROPIC_API_KEY"],
    service_id="my-service-id",  # Optional; for targeting specific services within Semantic Kernel
)
settings = AnthropicChatPromptExecutionSettings(
    temperature=0.2,
)

anthropic_model_client = SKChatCompletionAdapter(
    sk_client, kernel=Kernel(memory=NullMemory()), prompt_settings=settings
)

# Call the model directly.
model_result = await anthropic_model_client.create(
    messages=[UserMessage(content="What is the capital of France?", source="User")]
)
print(model_result)
await anthropic_model_client.close()

Semantic Kernel 어댑터에 대해 더 알아보세요.

더 알아보기 (Learn more)