중요합니다
이 기능은 실험 단계에 있습니다. 이 단계의 기능은 개발 중이며 미리 보기 또는 릴리스 후보 단계로 넘어가기 전에 변경될 수 있습니다.
이 설명과 관련된 자세한 API 설명서는 다음에서 확인할 수 있습니다.
현재 Java에서 기능을 사용할 수 없습니다.
AgentChat
이란 무엇인가요?
AgentChat
여러 에이전트가 서로 다른 형식인 경우에도 여러 에이전트 간의 상호 작용을 가능하게 하는 프레임워크를 제공합니다. 이렇게 하면 ChatCompletionAgent
및 OpenAIAssistantAgent
동일한 대화 내에서 함께 작동할 수 있습니다.
AgentChat
또한 여러 응답 또는 단일 에이전트 응답을 통해 에이전트 간의 공동 작업을 시작하기 위한 진입점을 정의합니다.
추상 클래스인 AgentChat
사용자 지정 시나리오를 지원하도록 서브클래스할 수 있습니다.
이러한 하위 클래스 AgentGroupChat
중 하나는 전략 기반 접근 방식을 사용하여 대화 역학을 관리하는 AgentChat
구체적인 구현을 제공합니다.
AgentGroupChat
생성하기
AgentGroupChat
만들려면 참여 에이전트를 지정하거나 빈 채팅을 만든 다음 에이전트 참가자를 추가할 수 있습니다. Chat-Settings 및 전략 구성은 AgentGroupChat
초기화 중에 수행합니다. 이러한 설정은 대화 역학이 그룹 내에서 작동하는 방식을 정의합니다.
참고: 기본 Chat-Settings은 대화가 단일 응답으로 제한되도록 합니다. 채팅 설정 구성에 대한 자세한 내용은 동작을 참조
AgentChat
하세요.
AgentGroupChat
와 Agent
를 사용하여 만들기:
// Define agents
ChatCompletionAgent agent1 = ...;
OpenAIAssistantAgent agent2 = ...;
// Create chat with participating agents.
AgentGroupChat chat = new(agent1, agent2);
# Define agents
agent1 = ChatCompletionAgent(...)
agent2 = OpenAIAssistantAgent(...)
# Create chat with participating agents
chat = AgentGroupChat(agents=[agent1, agent2])
현재 Java에서 기능을 사용할 수 없습니다.
Agent
에 AgentGroupChat
추가하기:
// Define agents
ChatCompletionAgent agent1 = ...;
OpenAIAssistantAgent agent2 = ...;
// Create an empty chat.
AgentGroupChat chat = new();
// Add agents to an existing chat.
chat.AddAgent(agent1);
chat.AddAgent(agent2);
# Define agents
agent1 = ChatCompletionAgent(...)
agent2 = OpenAIAssistantAgent(...)
# Create an empty chat
chat = AgentGroupChat()
# Add agents to an existing chat
chat.add_agent(agent=agent1)
chat.add_agent(agent=agent2)
현재 Java에서 기능을 사용할 수 없습니다.
AgentGroupChat
사용하기
AgentChat
Single-Turn
및 Multi-Turn
두 가지 작업 모드를 지원합니다.
single-turn
특정 에이전트가 응답을 제공하도록 지정됩니다.
multi-turn
대화의 모든 에이전트는 종료 기준이 충족될 때까지 차례로 응답합니다. 두 모드에서 에이전트는 서로 응답하여 공동 작업하여 정의된 목표를 달성할 수 있습니다.
입력 제공하기
AgentChat
입력 메시지를 추가하는 것은 ChatHistory
개체와 동일한 패턴을 따릅니다.
AgentGroupChat chat = new();
chat.AddChatMessage(new ChatMessageContent(AuthorRole.User, "<message content>"));
chat = AgentGroupChat()
await chat.add_chat_message(message="<message content>")
현재 Java에서 기능을 사용할 수 없습니다.
단일 단계 에이전트 호출
다중 턴 호출에서 시스템은 다음에 응답하는 에이전트와 대화가 종료되는 시기를 결정해야 합니다. 반면, 단일 턴 호출은 단순히 지정된 에이전트의 응답을 반환하므로 호출자가 에이전트 참여를 직접 관리할 수 있습니다.
에이전트가 AgentChat
을 통해 단일 턴 호출에 참여하면, 다중 턴 호출 대상인 에이전트 집합에 추가됩니다.
// Define an agent
ChatCompletionAgent agent = ...;
// Create an empty chat.
AgentGroupChat chat = new();
// Invoke an agent for its response
ChatMessageContent[] messages = await chat.InvokeAsync(agent).ToArrayAsync();
# Define an agent
agent = ChatCompletionAgent(...)
# Create an empty chat
chat = AgentGroupChat()
# Invoke an agent for its response(s)
async for message in chat.invoke(agent)
# process message response(s)
현재 Java에서 기능을 사용할 수 없습니다.
다단계 에이전트 호출
에이전트 협업을 위해서는 각 턴 동안 응답해야 하는 에이전트를 결정할 뿐만 아니라 대화가 의도한 목표를 달성한 시점을 평가하는 시스템이 있어야 하지만, 멀티 턴 협업을 시작하는 것은 여전히 간단합니다.
에이전트 응답은 생성될 때 비동기적으로 반환되므로 대화가 실시간으로 전개될 수 있습니다.
참고: 다음 섹션에서 에이전트 선택 및 채팅 종료는 실행 설정을 자세히 설명합니다. 기본 실행 설정은 순차적 또는 라운드 로빈 선택을 사용하고 에이전트 참여를 단일 턴으로 제한합니다.
.NET 실행 설정 API: AgentGroupChatSettings
// Define agents
ChatCompletionAgent agent1 = ...;
OpenAIAssistantAgent agent2 = ...;
// Create chat with participating agents.
AgentGroupChat chat =
new(agent1, agent2)
{
// Override default execution settings
ExecutionSettings =
{
TerminationStrategy = { MaximumIterations = 10 }
}
};
// Invoke agents
await foreach (ChatMessageContent response in chat.InvokeAsync())
{
// Process agent response(s)...
}
# Define agents
agent1 = ChatCompletionAgent(...)
agent2 = OpenAIAssistantAgent(...)
# Create chat with participating agents
chat = AgentGroupChat(
agents=[agent1, agent2],
termination_strategy=DefaultTerminationStrategy(maximum_iterations=10),
)
async for response in chat.invoke():
# process agent response(s)
현재 Java에서 기능을 사용할 수 없습니다.
채팅 기록에 액세스
호출 패턴을 통해 메시지가 전달되더라도 AgentChat
대화 기록에 항상 액세스할 수 있습니다. 이렇게 하면 대화 전체에서 이전 교환을 계속 사용할 수 있습니다.
참고: 가장 최근 메시지가 먼저 제공됩니다(내림차순: 최신에서 가장 오래된 메시지).
// Define and use a chat
AgentGroupChat chat = ...;
// Access history for a previously utilized AgentGroupChat
ChatMessageContent[] history = await chat.GetChatMessagesAsync().ToArrayAsync();
# Define a group chat
chat = AgentGroupChat(...)
# Access history for a previously utilized AgentGroupChat
history = await chat.get_chat_messages()
현재 Java에서 기능을 사용할 수 없습니다.
서로 다른 에이전트 유형 또는 구성이 자체 버전의 대화 기록을 유지할 수 있으므로 에이전트를 지정하여 에이전트 특정 기록을 사용할 수도 있습니다. (예: OpenAIAssistant
및 ChatCompletionAgent
.)
// Agents to participate in chat
ChatCompletionAgent agent1 = ...;
OpenAIAssistantAgent agent2 = ...;
// Define a group chat
AgentGroupChat chat = ...;
// Access history for a previously utilized AgentGroupChat
ChatMessageContent[] history1 = await chat.GetChatMessagesAsync(agent1).ToArrayAsync();
ChatMessageContent[] history2 = await chat.GetChatMessagesAsync(agent2).ToArrayAsync();
# Agents to participate in a chat
agent1 = ChatCompletionAgent(...)
agent2 = OpenAIAssistantAgent(...)
# Define a group chat
chat = AgentGroupChat(...)
# Access history for a previously utilized AgentGroupChat
history1 = await chat.get_chat_messages(agent=agent1)
history2 = await chat.get_chat_messages(agent=agent2)
현재 Java에서 기능을 사용할 수 없습니다.
AgentGroupChat
동작 정의
복잡한 작업을 해결하기 위한 에이전트 간의 협업은 핵심 에이전트 패턴입니다. 이 패턴을 효과적으로 사용하려면 각 턴 동안 응답해야 하는 에이전트를 결정할 뿐만 아니라 대화가 의도한 목표를 달성한 시기를 평가하는 시스템이 있어야 합니다. 이렇게 하려면 에이전트 선택을 관리하고 대화 종료에 대한 명확한 기준을 설정하여 솔루션에 대한 에이전트 간의 원활한 협력을 보장해야 합니다. 이러한 두 측면은 모두 실행 설정 속성에 의해 제어됩니다.
에이전트 선택 및 채팅 종료에 대한 다음 섹션에서는 이러한 고려 사항을 자세히 설명합니다.
에이전트 선택
다중 턴 호출에서 에이전트 선택은 선택 전략에 따라 수행됩니다. 이 전략은 특정 요구 사항에 맞는 사용자 지정 동작을 구현하도록 확장할 수 있는 기본 클래스에 의해 정의됩니다. 편의를 위해 미리 정의된 두 가지 구체적인 선택 전략도 사용할 수 있으며 대화 중에 에이전트 선택을 처리하기 위한 즉시 사용할 수 있는 방법을 제공합니다.
알려진 경우 항상 첫 번째 턴을 수행하도록 초기 에이전트를 지정할 수 있습니다. 기록 리듀서는 KernelFunction
기반 전략을 사용할 때 토큰 사용을 제한하는 데에도 활용할 수 있습니다.
.NET 선택 전략 API:
// Define the agent names for use in the function template
const string WriterName = "Writer";
const string ReviewerName = "Reviewer";
// Initialize a Kernel with a chat-completion service
Kernel kernel = ...;
// Create the agents
ChatCompletionAgent writerAgent =
new()
{
Name = WriterName,
Instructions = "<writer instructions>",
Kernel = kernel
};
ChatCompletionAgent reviewerAgent =
new()
{
Name = ReviewerName,
Instructions = "<reviewer instructions>",
Kernel = kernel
};
// Define a kernel function for the selection strategy
KernelFunction selectionFunction =
AgentGroupChat.CreatePromptFunctionForStrategy(
$$$"""
Determine which participant takes the next turn in a conversation based on the the most recent participant.
State only the name of the participant to take the next turn.
No participant should take more than one turn in a row.
Choose only from these participants:
- {{{ReviewerName}}}
- {{{WriterName}}}
Always follow these rules when selecting the next participant:
- After {{{WriterName}}}, it is {{{ReviewerName}}}'s turn.
- After {{{ReviewerName}}}, it is {{{WriterName}}}'s turn.
History:
{{$history}}
""",
safeParameterNames: "history");
// Define the selection strategy
KernelFunctionSelectionStrategy selectionStrategy =
new(selectionFunction, kernel)
{
// Always start with the writer agent.
InitialAgent = writerAgent,
// Parse the function response.
ResultParser = (result) => result.GetValue<string>() ?? WriterName,
// The prompt variable name for the history argument.
HistoryVariableName = "history",
// Save tokens by not including the entire history in the prompt
HistoryReducer = new ChatHistoryTruncationReducer(3),
};
// Create a chat using the defined selection strategy.
AgentGroupChat chat =
new(writerAgent, reviewerAgent)
{
ExecutionSettings = new() { SelectionStrategy = selectionStrategy }
};
Python 선택 전략 API:
REVIEWER_NAME = "Reviewer"
WRITER_NAME = "Writer"
agent_reviewer = ChatCompletionAgent(
kernel=kernel,
name=REVIEWER_NAME,
instructions="<instructions>",
)
agent_writer = ChatCompletionAgent(
kernel=kernel,
name=WRITER_NAME,
instructions="<instructions>",
)
selection_function = KernelFunctionFromPrompt(
function_name="selection",
prompt=f"""
Determine which participant takes the next turn in a conversation based on the the most recent participant.
State only the name of the participant to take the next turn.
No participant should take more than one turn in a row.
Choose only from these participants:
- {REVIEWER_NAME}
- {WRITER_NAME}
Always follow these rules when selecting the next participant:
- After user input, it is {WRITER_NAME}'s turn.
- After {WRITER_NAME} replies, it is {REVIEWER_NAME}'s turn.
- After {REVIEWER_NAME} provides feedback, it is {WRITER_NAME}'s turn.
History:
{{{{$history}}}}
""",
)
chat = AgentGroupChat(
agents=[agent_writer, agent_reviewer],
selection_strategy=KernelFunctionSelectionStrategy(
function=selection_function,
kernel=_create_kernel_with_chat_completion("selection"),
result_parser=lambda result: str(result.value[0]) if result.value is not None else COPYWRITER_NAME,
agent_variable_name="agents",
history_variable_name="history",
),
)
현재 Java에서 기능을 사용할 수 없습니다.
채팅 종료
다중 턴 호출에서 종료 전략은 최종 턴이 발생하는 시기를 결정합니다. 이 전략은 적절한 지점에서 대화가 종료되도록 합니다.
이 전략은 특정 요구 사항에 맞는 사용자 지정 동작을 구현하도록 확장할 수 있는 기본 클래스에 의해 정의됩니다. 편의를 위해 미리 정의된 몇 가지 구체적인 선택 전략을 사용할 수 있으며 대화의 종료 조건을 정의하기 위한 즉시 사용할 수 있는 AgentChat
방법을 제공합니다.
.NET 종료 전략 API:
TerminationStrategy
RegexTerminationStrategy
KernelFunctionSelectionStrategy
KernelFunctionTerminationStrategy
AggregatorTerminationStrategy
// Initialize a Kernel with a chat-completion service
Kernel kernel = ...;
// Create the agents
ChatCompletionAgent writerAgent =
new()
{
Name = "Writer",
Instructions = "<writer instructions>",
Kernel = kernel
};
ChatCompletionAgent reviewerAgent =
new()
{
Name = "Reviewer",
Instructions = "<reviewer instructions>",
Kernel = kernel
};
// Define a kernel function for the selection strategy
KernelFunction terminationFunction =
AgentGroupChat.CreatePromptFunctionForStrategy(
$$$"""
Determine if the reviewer has approved. If so, respond with a single word: yes
History:
{{$history}}
""",
safeParameterNames: "history");
// Define the termination strategy
KernelFunctionTerminationStrategy terminationStrategy =
new(terminationFunction, kernel)
{
// Only the reviewer may give approval.
Agents = [reviewerAgent],
// Parse the function response.
ResultParser = (result) =>
result.GetValue<string>()?.Contains("yes", StringComparison.OrdinalIgnoreCase) ?? false,
// The prompt variable name for the history argument.
HistoryVariableName = "history",
// Save tokens by not including the entire history in the prompt
HistoryReducer = new ChatHistoryTruncationReducer(1),
// Limit total number of turns no matter what
MaximumIterations = 10,
};
// Create a chat using the defined termination strategy.
AgentGroupChat chat =
new(writerAgent, reviewerAgent)
{
ExecutionSettings = new() { TerminationStrategy = terminationStrategy }
};
Python 종료 전략 API:
REVIEWER_NAME = "Reviewer"
WRITER_NAME = "Writer"
agent_reviewer = ChatCompletionAgent(
kernel=kernel,
name=REVIEWER_NAME,
instructions="<instructions>",
)
agent_writer = ChatCompletionAgent(
kernel=kernel,
name=WRITER_NAME,
instructions="<instructions>",
)
termination_function = KernelFunctionFromPrompt(
function_name="termination",
prompt="""
Determine if the copy has been approved. If so, respond with a single word: yes
History:
{{$history}}
""",
)
chat = AgentGroupChat(
agents=[agent_writer, agent_reviewer],
termination_strategy=KernelFunctionTerminationStrategy(
agents=[agent_reviewer],
function=termination_function,
kernel=_create_kernel_with_chat_completion("termination"),
result_parser=lambda result: str(result.value[0]).lower() == "yes",
history_variable_name="history",
maximum_iterations=10,
),
)
현재 Java에서 기능을 사용할 수 없습니다.
채팅 완료 상태 다시 설정
단일 턴 또는 다중 턴 접근 방식을 사용하여 호출되는지 여부에 AgentGroupChat
관계없이 종료 조건이 충족되면 완료되었음을 나타내도록 상태가 AgentGroupChat
업데이트됩니다. 이렇게 하면 시스템이 대화가 완전히 종료될 때 이를 인식할 수 있습니다.
AgentGroupChat
상태에 도달한 후 인스턴스를 계속 사용하려면 이 상태를 다시 설정하여 추가 상호 작용을 허용해야 합니다. 다시 설정하지 않으면 추가 상호 작용 또는 에이전트 응답이 불가능합니다.
최대 턴 제한에 도달하는 다중 턴 호출의 경우 시스템은 에이전트 호출을 중단하지만 인스턴스를 완료된 것으로 표시하지는 않습니다. 이렇게 하면 완료 상태를 다시 설정할 필요 없이 대화를 확장할 수 있습니다.
// Define an use chat
AgentGroupChat chat = ...;
// Evaluate if completion is met and reset.
if (chat.IsComplete)
{
// Opt to take action on the chat result...
// Reset completion state to continue use
chat.IsComplete = false;
}
# Define a group chat
chat = AgentGroupChat()
# Evaluate if completion is met and reset
if chat.is_complete:
# Reset completion state to continue use
chat.is_complete = False
현재 Java에서 기능을 사용할 수 없습니다.
전체 대화 상태 지우기
AgentChat
가 OpenAIAssistant
에 참여한 상태에서 작업을 완료할 때, 도우미와 연결된 원격 스레드를 삭제해야 할 수 있습니다.
AgentChat
는 모든 원격 스레드 정의를 삭제하는 것을 포함하여 전체 대화 상태를 다시 설정하거나 지울 수 있습니다. 이렇게 하면 채팅이 종료된 후 남은 대화 데이터가 도우미에 연결된 상태로 유지되지 않습니다.
전체 재설정을 해도 AgentChat
에 조인한 에이전트는 제거되지 않으며, AgentChat
는 다시 사용할 수 있는 상태로 유지됩니다. 이렇게 하면 다시 초기화할 필요 없이 동일한 에이전트와의 상호 작용을 계속하여 향후 대화의 효율성을 높일 수 있습니다.
// Define an use chat
AgentGroupChat chat = ...;
// Clear the all conversation state
await chat.ResetAsync();
# Define a group chat
chat = AgentGroupChat()
# Clear the conversation state
await chat.reset()
현재 Java에서 기능을 사용할 수 없습니다.
사용 방법
AgentGroupChat
협업에 Agent
사용하는 엔드 투 엔드 예제는 다음을 참조하세요.
-
AgentGroupChat
사용하여 에이전트 공동 작업을 조정하는 방법