의미 체계 커널
중요합니다
이 기능은 실험 단계에 있습니다. 이 단계의 기능은 개발 중이며 미리 보기 또는 릴리스 후보 단계로 넘어가기 전에 변경될 수 있습니다.
곧
OpenAIResponsesAgent출시될 예정입니다.
현재 Java에서 기능을 사용할 수 없습니다.
응답 에이전트란?
OpenAI 응답 API는 모델 응답을 생성하기 위한 OpenAI의 가장 고급 인터페이스입니다. 텍스트 및 이미지 입력 및 텍스트 출력을 지원합니다. 이전 응답의 출력을 입력으로 사용하여 모델과 상태 저장 상호 작용을 만들 수 있습니다. 파일 검색, 웹 검색, 컴퓨터 사용 등에 대한 기본 제공 도구를 사용하여 모델의 기능을 확장할 수도 있습니다.
개발 환경 준비
OpenAIResponsesAgent개발을 계속하려면 적절한 패키지로 개발 환경을 구성합니다.
곧
OpenAIResponsesAgent출시될 예정입니다.
semantic-kernel 패키지를 설치합니다.
pip install semantic-kernel
중요합니다
OpenAIResponsesAgent 의미 체계 커널은 Python 패키지 1.27.0 이상에서 지원됩니다.
현재 Java에서 기능을 사용할 수 없습니다.
OpenAIResponsesAgent 생성하기
OpenAIResponsesAgent를 생성하려면 원격 서비스와 통신할 수 있는 클라이언트를 먼저 만들어야 합니다.
곧
OpenAIResponsesAgent출시될 예정입니다.
OpenAI 또는 Azure OpenAI 응답 API에서 사용하는 모델을 구성하기 위해 새 환경 변수가 도입되었습니다.
OPENAI_RESPONSES_MODEL_ID=""
AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME=""
사용 중인 공급자에 따라 적절한 변수를 설정합니다.
팁 (조언)
허용되는 최소 Azure OpenAI api 버전은 .입니다 2025-03-01-preview. 지역 가용성, 모델 지원 및 자세한 내용을 보려면 다음 링크를 방문하세요.
Azure OpenAI 모델에서 사용할 AzureResponsesAgent을(를) 만들려면 다음 단계를 따르세요.
from semantic_kernel.agents import AzureResponsesAgent
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings, OpenAISettings
# Set up the client and model using Azure OpenAI Resources
client = AzureResponsesAgent.create_client()
# Create the AzureResponsesAgent instance using the client and the model
agent = AzureResponsesAgent(
ai_model_id=AzureOpenAISettings().responses_deployment_name,
client=client,
instructions="your instructions",
name="name",
)
대안으로, OpenAI 모델과 함께 사용할 OpenAIResponsesAgent을(를) 생성하려면 다음을 수행합니다.
from semantic_kernel.agents import OpenAIResponsesAgent
# Set up the client and model using OpenAI Resources
client = OpenAIResponsesAgent.create_client()
# Create the OpenAIResponsesAgent instance using the client and the model
agent = OpenAIResponsesAgent(
ai_model_id=OpenAISettings().responses_model_id,
client=client,
instructions="your instructions",
name="name",
)
현재 Java에서 기능을 사용할 수 없습니다.
OpenAIResponsesAgent을/를 사용하기
곧
OpenAIResponsesAgent출시될 예정입니다.
OpenAI 응답 API는 대화의 선택적 원격 스토리지를 지원합니다. 기본적으로 응답은 ResponsesAgentThread사용하는 경우 원격으로 저장됩니다. 이렇게 하면 호출 간에 컨텍스트를 유지하기 위해 응답 API previous_response_id 를 사용할 수 있습니다.
각 대화는 고유한 문자열 ID로 식별되는 스레드로 처리됩니다. 사용자 OpenAIResponsesAgent와의 모든 상호 작용은 이 스레드 식별자에 한정됩니다.
응답 API 스레드의 기본 메커니즘은 ResponsesAgentThread 인터페이스를 구현하는 AgentThread 클래스에 의해 추상화됩니다.
OpenAIResponsesAgent 현재 ResponsesAgentThread형식의 스레드만 지원합니다.
OpenAIResponsesAgent를 호출할 때 AgentThread를 지정하지 않아도 새 스레드를 시작할 수 있으며, 새 AgentThread가 응답의 일부로 반환됩니다.
from semantic_kernel.agents import AzureResponsesAgent
# Set up the client and model using Azure OpenAI Resources
client = AzureResponsesAgent.create_client()
# Create the AzureResponsesAgent instance using the client and the model
agent = AzureResponsesAgent(
ai_model_id=AzureOpenAISettings().responses_deployment_name,
client=client,
instructions="your instructions",
name="name",
)
USER_INPUTS = [
"My name is John Doe.",
"Tell me a joke",
"Explain why this is funny.",
"What have we been talking about?",
]
thread = None
# Generate the agent response(s)
for user_input in USER_INPUTS:
print(f"# User: '{user_input}'")
# Invoke the agent for the current message and print the response
response = await agent.get_response(messages=user_input, thread=thread)
print(f"# {response.name}: {response.content}")
# Update the thread so the previous response id is used
thread = response.thread
# Delete the thread when it is no longer needed
await thread.delete() if thread else None
현재 Java에서 기능을 사용할 수 없습니다.
OpenAIResponsesAgent를 사용하여 중간 메시지 처리
의미 체계 커널 OpenAIResponsesAgent 은 사용자 쿼리 또는 질문을 충족하는 에이전트를 호출하도록 설계되었습니다. 호출하는 동안 에이전트는 도구를 실행하여 최종 답변을 파생시킬 수 있습니다. 이 프로세스 중에 생성된 중간 메시지에 액세스하기 위해 호출자는 FunctionCallContent 또는 FunctionResultContent 인스턴스를 처리하는 콜백 함수를 제공할 수 있습니다.
곧
OpenAIResponsesAgent출시될 예정입니다.
on_intermediate_message 또는 agent.invoke(...) 안에서 agent.invoke_stream(...) 콜백을 구성하면, 호출자는 에이전트의 최종 응답을 작성하는 과정에서 생성된 중간 메시지를 수신할 수 있습니다.
import asyncio
from typing import Annotated
from semantic_kernel.agents import AzureResponsesAgent
from semantic_kernel.contents import AuthorRole, FunctionCallContent, FunctionResultContent
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.functions import kernel_function
# Define a sample plugin for the sample
class MenuPlugin:
"""A sample Menu Plugin used for the concept sample."""
@kernel_function(description="Provides a list of specials from the menu.")
def get_specials(self) -> Annotated[str, "Returns the specials from the menu."]:
return """
Special Soup: Clam Chowder
Special Salad: Cobb Salad
Special Drink: Chai Tea
"""
@kernel_function(description="Provides the price of the requested menu item.")
def get_item_price(
self, menu_item: Annotated[str, "The name of the menu item."]
) -> Annotated[str, "Returns the price of the menu item."]:
return "$9.99"
# This callback function will be called for each intermediate message,
# which will allow one to handle FunctionCallContent and FunctionResultContent.
# If the callback is not provided, the agent will return the final response
# with no intermediate tool call steps.
async def handle_intermediate_steps(message: ChatMessageContent) -> None:
for item in message.items or []:
if isinstance(item, FunctionResultContent):
print(f"Function Result:> {item.result} for function: {item.name}")
elif isinstance(item, FunctionCallContent):
print(f"Function Call:> {item.name} with arguments: {item.arguments}")
else:
print(f"{item}")
async def main():
# 1. Create the client using Azure OpenAI resources and configuration
client = AzureResponsesAgent.create_client()
# 2. Create a Semantic Kernel agent for the OpenAI Responses API
agent = AzureResponsesAgent(
ai_model_id=AzureOpenAISettings().responses_deployment_name,
client=client,
name="Host",
instructions="Answer questions about the menu.",
plugins=[MenuPlugin()],
)
# 3. Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread = None
user_inputs = ["Hello", "What is the special soup?", "What is the special drink?", "How much is that?", "Thank you"]
try:
for user_input in user_inputs:
print(f"# {AuthorRole.USER}: '{user_input}'")
async for response in agent.invoke(
messages=user_input,
thread=thread,
on_intermediate_message=handle_intermediate_steps,
):
thread = response.thread
print(f"# {response.name}: {response.content}")
finally:
await thread.delete() if thread else None
if __name__ == "__main__":
asyncio.run(main())
다음은 에이전트 호출 프로세스의 샘플 출력을 보여 줍니다.
AuthorRole.USER: 'Hello'
Host: Hi there! How can I assist you with the menu today?
AuthorRole.USER: 'What is the special soup?'
Function Call:> MenuPlugin-get_specials with arguments: {}
Function Result:>
Special Soup: Clam Chowder
Special Salad: Cobb Salad
Special Drink: Chai Tea
for function: MenuPlugin-get_specials
Host: The special soup is Clam Chowder. Would you like to know more about any other specials?
AuthorRole.USER: 'What is the special drink?'
Host: The special drink is Chai Tea. Would you like any more information?
AuthorRole.USER: 'How much is that?'
Function Call:> MenuPlugin-get_item_price with arguments: {"menu_item":"Chai Tea"}
Function Result:> $9.99 for function: MenuPlugin-get_item_price
Host: The Chai Tea is $9.99. Is there anything else you would like to know?
AuthorRole.USER: 'Thank you'
Host: You're welcome! If you have any more questions, feel free to ask. Enjoy your day!
현재 Java에서 기능을 사용할 수 없습니다.
선언적 사양
선언적 사양 사용에 대한 설명서는 곧 제공될 예정입니다.
중요합니다
이 기능은 실험 단계에 있습니다. 이 단계의 기능은 개발 중이며 미리 보기 또는 릴리스 후보 단계로 넘어가기 전에 변경될 수 있습니다.
YAML OpenAIResponsesAgent 선언적 사양에서 인스턴스화를 지원합니다. 선언적 접근 방식을 사용하면 감사 가능한 단일 문서에서 에이전트의 속성, 지침, 모델 구성, 도구 및 기타 옵션을 정의할 수 있습니다. 이렇게 하면 에이전트 컴퍼지션이 여러 환경에서 이식 가능하고 쉽게 관리할 수 있습니다.
비고
선언적 YAML에 나열된 모든 도구, 함수 또는 플러그 인은 생성 시 에이전트에서 사용할 수 있어야 합니다. 커널 기반 플러그 인의 경우 커널에 등록해야 합니다. 코드 인터프리터 또는 파일 검색과 같은 기본 제공 도구의 경우 올바른 구성 및 자격 증명을 제공해야 합니다. 에이전트 로더는 함수를 처음부터 만들지 않습니다. 필요한 구성 요소가 없으면 에이전트를 만들지 못합니다.
선언적 사양을 사용하는 방법
이 섹션에서는 가능한 모든 YAML 구성을 열거하는 대신 주요 원칙을 간략하게 설명하고 각 도구 유형에 대한 전체 코드를 보여 주는 개념 샘플에 대한 링크를 제공합니다. 선언적 사양을 사용하는 엔드 투 엔드 구현은 OpenAIResponsesAgent 다음 개념 샘플을 참조하세요.
AzureResponsesAgent 샘플:
OpenAIResponsesAgent 샘플:
예: YAML에서 AzureAIAgent 만들기
최소한의 YAML 선언적 사양은 다음과 같을 수 있습니다.
type: openai_responses
name: Host
instructions: Respond politely to the user's questions.
model:
id: ${OpenAI:ChatModelId}
tools:
- id: MenuPlugin.get_specials
type: function
- id: MenuPlugin.get_item_price
type: function
에이전트를 연결하는 방법에 대한 자세한 내용은 위의 전체 코드 샘플을 참조하세요.
요점
- 선언적 사양을 사용하면 YAML에서 에이전트 구조, 도구 및 동작을 정의할 수 있습니다.
- 모든 참조된 도구 및 플러그 인은 런타임에 등록되거나 액세스할 수 있어야 합니다.
- Bing, 파일 검색 및 코드 인터프리터와 같은 기본 제공 도구에는 적절한 구성 및 자격 증명(환경 변수 또는 명시적 인수를 통해)이 필요합니다.
- 포괄적인 예제는 플러그 인 등록, Azure ID 구성 및 고급 도구 사용을 비롯한 실제 시나리오를 보여 주는 제공된 샘플 링크를 참조하세요.
이 기능을 사용할 수 없습니다.