의미 체계 커널
중요합니다
같은 OpenAIAssistantAgent
단일 에이전트 기능은 릴리스 후보 단계에 있습니다. 이러한 기능은 거의 완전하고 일반적으로 안정적이지만 전체 일반 공급에 도달하기 전에 약간의 개선 또는 최적화가 필요할 수 있습니다.
현재 Java에서 기능을 사용할 수 없습니다.
도우미란?
OpenAI Assistants API는 고급 및 대화형 AI 기능을 위해 설계된 특수 인터페이스로, 개발자가 개인 설정된 다단계 작업 지향 에이전트를 만들 수 있습니다. 간단한 대화형 교환에 중점을 둔 채팅 완료 API와 달리 Assistant API는 코드 인터프리터 및 파일 검색과 같은 추가 기능과 동적 목표 기반 상호 작용을 허용합니다.
개발 환경 준비
OpenAIAssistantAgent
개발을 계속하려면 적절한 패키지로 개발 환경을 구성합니다.
프로젝트에 Microsoft.SemanticKernel.Agents.OpenAI
패키지를 추가합니다.
dotnet add package Microsoft.SemanticKernel.Agents.OpenAI --prerelease
Azure.Identity
패키지를 포함할 수도 있습니다.
dotnet add package Azure.Identity
semantic-kernel
패키지를 설치합니다.
pip install semantic-kernel
현재 Java에서 기능을 사용할 수 없습니다.
OpenAIAssistantAgent
생성하기
OpenAIAssistant
를 생성하려면 원격 서비스와 통신할 수 있는 클라이언트를 먼저 만들어야 합니다.
AssistantClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(...).GetAssistantClient();
Assistant assistant =
await client.CreateAssistantAsync(
"<model name>",
"<agent name>",
instructions: "<agent instructions>");
OpenAIAssistantAgent agent = new(assistant, client);
from semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent, OpenAIAssistantAgent
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings, OpenAISettings
# Set up the client and model using Azure OpenAI Resources
client = AzureAssistantAgent.create_client()
# Define the assistant definition
definition = await client.beta.assistants.create(
model=AzureOpenAISettings().chat_deployment_name,
instructions="<instructions>",
name="<agent name>",
)
# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=definition,
)
# or
# Set up the client and model using OpenAI Resources
client = OpenAIAssistantAgent.create_client()
# Define the assistant definition
definition = await client.beta.assistants.create(
model=OpenAISettings().chat_model_id,
instructions="<instructions>",
name="<agent name>",
)
# Create the OpenAIAssistantAgent instance using the client and the assistant definition
agent = OpenAIAssistantAgent(
client=client,
definition=definition,
)
현재 Java에서 기능을 사용할 수 없습니다.
OpenAIAssistantAgent
가져오기
생성되면 도우미의 식별자는 해당 식별자를 통해 액세스할 수 있습니다. 이 식별자는 기존 도우미 정의에서 OpenAIAssistantAgent
만드는 데 사용할 수 있습니다.
.NET의 경우 에이전트 식별자는 에이전트에서 정의한 string
속성을 통해 노출됩니다.
AssistantClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(...).GetAssistantClient();
Assistant assistant = await client.GetAssistantAsync("<assistant id>");
OpenAIAssistantAgent agent = new(assistant, client);
# Using Azure OpenAI Resources
# Create the client using Azure OpenAI resources and configuration
client = AzureAssistantAgent.create_client()
# Create the assistant definition
definition = await client.beta.assistants.create(
model=AzureOpenAISettings().chat_deployment_name,
name="<agent name>",
instructions="<instructions>",
)
# Store the assistant ID
assistant_id = definition.id
# Retrieve the assistant definition from the server based on the assistant ID
new_asst_definition = await client.beta.assistants.retrieve(assistant_id)
# Create the AzureAssistantAgent instance using the client and the assistant definition
agent = AzureAssistantAgent(
client=client,
definition=new_asst_definition,
)
현재 Java에서 기능을 사용할 수 없습니다.
OpenAIAssistantAgent
을/를 사용하기
Assistant API의 모든 측면과 마찬가지로 대화는 원격으로 저장됩니다. 각 대화를 스레드라고 하며 고유 string
식별자로 식별됩니다. 사용자 OpenAIAssistantAgent
와의 상호 작용은 이 특정 스레드 식별자에 연결됩니다. Assistant API 스레드의 세부 정보는 OpenAIAssistantAgentThread
의 구현인 AgentThread
클래스를 통해 추상화됩니다.
OpenAIAssistantAgent
현재 OpenAIAssistantAgentThread
형식의 스레드만 지원합니다.
OpenAIAssistantAgent
를 호출할 때 AgentThread
를 지정하지 않아도 새 스레드를 시작할 수 있으며, 새 AgentThread
가 응답의 일부로 반환됩니다.
// Define agent
OpenAIAssistantAgent agent = ...;
AgentThread? agentThread = null;
// Generate the agent response(s)
await foreach (AgentResponseItem<ChatMessageContent> response in agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "<user input>")))
{
// Process agent response(s)...
agentThread = response.Thread;
}
// Delete the thread if no longer needed
if (agentThread is not null)
{
await agentThread.DeleteAsync();
}
OpenAIAssistantAgent
를 여러분이 만든 AgentThread
와 함께 호출할 수도 있습니다.
// Define agent
OpenAIAssistantAgent agent = ...;
// Create a thread with some custom metadata.
AgentThread agentThread = new OpenAIAssistantAgentThread(client, metadata: myMetadata);
// Generate the agent response(s)
await foreach (ChatMessageContent response in agent.InvokeAsync(new ChatMessageContent(AuthorRole.User, "<user input>"), agentThread))
{
// Process agent response(s)...
}
// Delete the thread when it is no longer needed
await agentThread.DeleteAsync();
ID를 사용하여 이전 대화를 다시 시작하는 OpenAIAssistantAgentThread
를 만들 수도 있습니다.
// Create a thread with an existing thread id.
AgentThread agentThread = new OpenAIAssistantAgentThread(client, "existing-thread-id");
from semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent
# Define agent
openai_agent = await ...
# Create a thread for the agent conversation
thread: AssistantAgentThread = None
# Generate the agent response(s)
async for response in agent.invoke(messages="user input", thread=thread):
# process agent response(s)...
thread = response.thread
# Delete the thread when it is no longer needed
await thread.delete() if thread else None
현재 Java에서 기능을 사용할 수 없습니다.
OpenAIAssistantAgent
을 삭제하기
도우미의 정의는 원격으로 저장되므로 삭제되지 않으면 유지됩니다.
도우미 정의를 삭제하는 작업은 클라이언트에서 직접 수행할 수 있습니다.
참고: 삭제된 후 에이전트 인스턴스를 사용하려고 하면 서비스 예외가 발생합니다.
.NET의 경우 에이전트 식별자는 에이전트가 정의한 속성인 string
를 통해 Agent.Id
에서 노출됩니다.
AssistantClient client = OpenAIAssistantAgent.CreateAzureOpenAIClient(...).GetAssistantClient();
await client.DeleteAssistantAsync("<assistant id>");
await client.beta.assistants.delete(agent.id)
현재 Java에서 기능을 사용할 수 없습니다.
OpenAIAssistantAgent
를 사용하여 중간 메시지 처리
의미 체계 커널 OpenAIAssistantAgent
은 사용자 쿼리 또는 질문을 충족하는 에이전트를 호출하도록 설계되었습니다. 호출하는 동안 에이전트는 도구를 실행하여 최종 답변을 파생시킬 수 있습니다. 이 프로세스 중에 생성된 중간 메시지에 액세스하기 위해 호출자는 FunctionCallContent
또는 FunctionResultContent
인스턴스를 처리하는 콜백 함수를 제공할 수 있습니다.
OpenAIAssistantAgent
에 대한 콜백 설명서는 곧 제공될 예정입니다.
on_intermediate_message
또는 agent.invoke(...)
안에서 agent.invoke_stream(...)
콜백을 구성하면, 호출자는 에이전트의 최종 응답을 작성하는 과정에서 생성된 중간 메시지를 수신할 수 있습니다.
import asyncio
from typing import Annotated
from semantic_kernel.agents import AssistantAgentThread, AzureAssistantAgent
from semantic_kernel.connectors.ai.open_ai import AzureOpenAISettings
from semantic_kernel.contents import AuthorRole, ChatMessageContent, FunctionCallContent, FunctionResultContent
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():
# Create the client using Azure OpenAI resources and configuration
client = AzureAssistantAgent.create_client()
# Define the assistant definition
definition = await client.beta.assistants.create(
model=AzureOpenAISettings().chat_deployment_name,
name="Host",
instructions="Answer questions about the menu.",
)
# Create the AzureAssistantAgent instance using the client and the assistant definition and the defined plugin
agent = AzureAssistantAgent(
client=client,
definition=definition,
plugins=[MenuPlugin()],
)
# Create a new thread for use with the assistant
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AssistantAgentThread = 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,
):
print(f"# {response.role}: {response}")
thread = response.thread
finally:
await thread.delete() if thread else None
await client.beta.assistants.delete(assistant_id=agent.id)
if __name__ == "__main__":
asyncio.run(main())
다음은 에이전트 호출 프로세스의 샘플 출력을 보여 줍니다.
AuthorRole.USER: 'Hello'
AuthorRole.ASSISTANT: Hello! How can I assist you 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
AuthorRole.ASSISTANT: The special soup is Clam Chowder. Would you like to know more about the specials or
anything else?
AuthorRole.USER: 'What is the special drink?'
AuthorRole.ASSISTANT: The special drink is Chai Tea. If you have any more questions, feel free to ask!
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
AuthorRole.ASSISTANT: The Chai Tea is priced at $9.99. If there's anything else you'd like to know,
just let me know!
AuthorRole.USER: 'Thank you'
AuthorRole.ASSISTANT: You're welcome! If you have any more questions or need further assistance, feel free to
ask. Enjoy your day!
현재 Java에서 기능을 사용할 수 없습니다.
선언적 사양
선언적 사양 사용에 대한 설명서는 곧 제공될 예정입니다.
중요합니다
이 기능은 실험 단계에 있습니다. 이 단계의 기능은 개발 중이며 미리 보기 또는 릴리스 후보 단계로 넘어가기 전에 변경될 수 있습니다.
YAML OpenAIAssistantAgent
선언적 사양에서 인스턴스화를 지원합니다. 선언적 접근 방식을 사용하면 감사 가능한 단일 문서에서 에이전트의 속성, 지침, 모델 구성, 도구 및 기타 옵션을 정의할 수 있습니다. 이렇게 하면 에이전트 컴퍼지션이 여러 환경에서 이식 가능하고 쉽게 관리할 수 있습니다.
비고
선언적 YAML에 나열된 모든 도구, 함수 또는 플러그 인은 생성 시 에이전트에서 사용할 수 있어야 합니다. 커널 기반 플러그 인의 경우 커널에 등록해야 합니다. 코드 인터프리터 또는 파일 검색과 같은 기본 제공 도구의 경우 올바른 구성 및 자격 증명을 제공해야 합니다. 에이전트 로더는 함수를 처음부터 만들지 않습니다. 필요한 구성 요소가 없으면 에이전트를 만들지 못합니다.
선언적 사양을 사용하는 방법
이 섹션에서는 가능한 모든 YAML 구성을 열거하는 대신 주요 원칙을 간략하게 설명하고 각 도구 유형에 대한 전체 코드를 보여 주는 개념 샘플에 대한 링크를 제공합니다. 선언적 사양을 사용하는 엔드 투 엔드 구현은 OpenAIAssistantAgent
다음 개념 샘플을 참조하세요.
AzureAssistantAgent
샘플:
OpenAIAssistantAgent
샘플:
예: YAML에서 AzureAIAgent 만들기
최소한의 YAML 선언적 사양은 다음과 같을 수 있습니다.
type: openai_assistant
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 구성 및 고급 도구 사용을 비롯한 실제 시나리오를 보여 주는 제공된 샘플 링크를 참조하세요.
이 기능을 사용할 수 없습니다.
사용 방법
OpenAIAssistantAgent
대한 엔드 투 엔드 예제는 다음을 참조하세요.
-
사용 방법:
OpenAIAssistantAgent
코드 인터프리터 -
OpenAIAssistantAgent