다음을 통해 공유


OpenAI ChatCompletion 에이전트

Microsoft 에이전트 프레임워크는 OpenAI ChatCompletion 서비스를 사용하는 에이전트 만들기를 지원합니다.

시작하기

필요한 NuGet 패키지를 프로젝트에 추가합니다.

dotnet add package Microsoft.Agents.AI.OpenAI --prerelease

OpenAI ChatCompletion 에이전트 만들기

첫 번째 단계로 OpenAI 서비스에 연결할 클라이언트를 만들어야 합니다.

using System;
using Microsoft.Agents.AI;
using OpenAI;

OpenAIClient client = new OpenAIClient("<your_api_key>");

OpenAI는 모델 호출 기능을 모두 제공하는 여러 서비스를 지원합니다. ChatCompletion 기반 에이전트를 만들려면 ChatCompletion 서비스를 선택해야 합니다.

var chatCompletionClient = client.GetChatClient("gpt-4o-mini");

마지막으로 CreateAIAgentChatCompletionClient 확장 메서드를 사용하여 에이전트를 만듭니다.

AIAgent agent = chatCompletionClient.CreateAIAgent(
    instructions: "You are good at telling jokes.",
    name: "Joker");

// Invoke the agent and output the text result.
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));

에이전트 사용

에이전트는 표준 AIAgent 이며 모든 표준 AIAgent 작업을 지원합니다.

에이전트를 실행하고 상호 작용하는 방법에 대한 자세한 내용은 에이전트 시작 자습서 를 참조하세요.

필수 조건

Microsoft Agent Framework 패키지를 설치합니다.

pip install agent-framework --pre

구성 / 설정

환경 변수

OpenAI 인증에 필요한 환경 변수를 설정합니다.

# Required for OpenAI API access
OPENAI_API_KEY="your-openai-api-key"
OPENAI_CHAT_MODEL_ID="gpt-4o-mini"  # or your preferred model

또는 프로젝트 루트에서 .env 파일을 사용할 수 있습니다.

OPENAI_API_KEY=your-openai-api-key
OPENAI_CHAT_MODEL_ID=gpt-4o-mini

시작하기

에이전트 프레임워크에서 필요한 클래스를 가져옵니다.

import asyncio
from agent_framework import ChatAgent
from agent_framework.openai import OpenAIChatClient

OpenAI ChatCompletion 에이전트 만들기

기본 에이전트 만들기

채팅 완료 에이전트를 만드는 가장 간단한 방법은 다음과 같습니다.

async def basic_example():
    # Create an agent using OpenAI ChatCompletion
    agent = OpenAIChatClient().create_agent(
        name="HelpfulAssistant",
        instructions="You are a helpful assistant.",
    )

    result = await agent.run("Hello, how can you help me?")
    print(result.text)

명시적 구성 사용

환경 변수를 사용하는 대신 명시적 구성을 제공할 수 있습니다.

async def explicit_config_example():
    agent = OpenAIChatClient(
        ai_model_id="gpt-4o-mini",
        api_key="your-api-key-here",
    ).create_agent(
        instructions="You are a helpful assistant.",
    )

    result = await agent.run("What can you do?")
    print(result.text)

에이전트 기능

함수 도구

에이전트에 사용자 지정 함수를 장착합니다.

from typing import Annotated
from pydantic import Field

def get_weather(
    location: Annotated[str, Field(description="The location to get weather for")]
) -> str:
    """Get the weather for a given location."""
    # Your weather API implementation here
    return f"The weather in {location} is sunny with 25°C."

async def tools_example():
    agent = ChatAgent(
        chat_client=OpenAIChatClient(),
        instructions="You are a helpful weather assistant.",
        tools=get_weather,  # Add tools to the agent
    )

    result = await agent.run("What's the weather like in Tokyo?")
    print(result.text)

스트리밍 응답

사용자 환경을 향상하기 위해 생성된 응답을 가져옵니다.

async def streaming_example():
    agent = OpenAIChatClient().create_agent(
        name="StoryTeller",
        instructions="You are a creative storyteller.",
    )

    print("Assistant: ", end="", flush=True)
    async for chunk in agent.run_stream("Tell me a short story about AI."):
        if chunk.text:
            print(chunk.text, end="", flush=True)
    print()  # New line after streaming

에이전트 사용

에이전트는 표준 BaseAgent 이며 모든 표준 에이전트 작업을 지원합니다.

에이전트를 실행하고 상호 작용하는 방법에 대한 자세한 내용은 에이전트 시작 자습서 를 참조하세요.

다음 단계