Примечание.
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
На этой странице представлен обзор использования агентов в рабочих процессах Microsoft Agent Framework.
Обзор
Чтобы добавить аналитику в рабочие процессы, вы можете использовать агенты ИИ в рамках выполнения рабочего процесса. Агенты искусственного интеллекта можно легко интегрировать в рабочие процессы, что позволяет создавать сложные интеллектуальные решения, которые ранее были трудно достичь.
Добавление агента непосредственно в рабочий процесс
Агенты можно добавить в рабочий процесс через узлы.
using Microsoft.Agents.AI.Workflows;
using Microsoft.Extensions.AI;
using Microsoft.Agents.AI;
// Create the agents first
AIAgent agentA = new ChatClientAgent(chatClient, instructions);
AIAgent agentB = new ChatClientAgent(chatClient, instructions);
// Build a workflow with the agents
WorkflowBuilder builder = new(agentA);
builder.AddEdge(agentA, agentB);
Workflow<ChatMessage> workflow = builder.Build<ChatMessage>();
Запуск рабочего процесса
В рабочем процессе, созданном выше, агенты фактически обернуты внутри исполнителя, который обрабатывает их коммуникацию с другими частями рабочего процесса. Исполнитель может обрабатывать три типа сообщений:
-
ChatMessage: одно сообщение чата -
List<ChatMessage>: список сообщений чата -
TurnToken: маркер поворота, который сигнализирует о начале нового поворота
Исполнитель не активирует агент, пока он не получит ответ TurnToken. Все сообщения, полученные до TurnToken, буферизуются и отправляются агенту, когда получено TurnToken.
StreamingRun run = await InProcessExecution.StreamAsync(workflow, new ChatMessage(ChatRole.User, "Hello World!"));
// Must send the turn token to trigger the agents. The agents are wrapped as executors.
// When they receive messages, they will cache the messages and only start processing
// when they receive a TurnToken. The turn token will be passed from one agent to the next.
await run.TrySendMessageAsync(new TurnToken(emitEvents: true));
await foreach (WorkflowEvent evt in run.WatchStreamAsync().ConfigureAwait(false))
{
// The agents will run in streaming mode and an AgentRunUpdateEvent
// will be emitted as new chunks are generated.
if (evt is AgentRunUpdateEvent agentRunUpdate)
{
Console.WriteLine($"{agentRunUpdate.ExecutorId}: {agentRunUpdate.Data}");
}
}
Использование встроенного исполнителя агента
Агенты можно добавить в рабочий процесс через узлы.
from agent_framework import WorkflowBuilder
from agent_framework.azure import AzureChatClient
from azure.identity import AzureCliCredential
# Create the agents first
chat_client = AzureChatClient(credential=AzureCliCredential())
writer_agent: ChatAgent = chat_client.create_agent(
instructions=(
"You are an excellent content writer. You create new content and edit contents based on the feedback."
),
name="writer_agent",
)
reviewer_agent = chat_client.create_agent(
instructions=(
"You are an excellent content reviewer."
"Provide actionable feedback to the writer about the provided content."
"Provide the feedback in the most concise manner possible."
),
name="reviewer_agent",
)
# Build a workflow with the agents
builder = WorkflowBuilder()
builder.set_start_executor(writer_agent)
builder.add_edge(writer_agent, reviewer_agent)
workflow = builder.build()
Запуск рабочего процесса
В рабочем процессе, созданном выше, агенты фактически обернуты внутри исполнителя, который обрабатывает их коммуникацию с другими частями рабочего процесса. Исполнитель может обрабатывать три типа сообщений:
-
str: одно сообщение чата в строковом формате -
ChatMessage: одно сообщение чата -
List<ChatMessage>: список сообщений чата
Каждый раз, когда исполнитель получает сообщение одного из этих типов, он заставляет агента реагировать, а тип ответа будет AgentExecutorResponse объектом. Этот класс содержит полезные сведения об ответе агента, в том числе:
-
executor_id: идентификатор исполнителя, создающего этот ответ -
agent_run_response: полный ответ от агента -
full_conversation: вся история бесед до этой точки
При запуске рабочего процесса можно создать два возможных типа событий, связанных с ответами агентов:
-
AgentRunUpdateEventсодержит фрагменты ответа агента по мере их создания в режиме потоковой передачи. -
AgentRunEventсодержит полный ответ от агента в режиме, отличном от потоковой передачи.
По умолчанию агенты упаковываются в исполнителей, которые выполняются в режиме потоковой передачи. Это поведение можно настроить, создав пользовательский исполнительный механизм. Дополнительные сведения см. в следующем разделе.
last_executor_id = None
async for event in workflow.run_streaming("Write a short blog post about AI agents."):
if isinstance(event, AgentRunUpdateEvent):
if event.executor_id != last_executor_id:
if last_executor_id is not None:
print()
print(f"{event.executor_id}:", end=" ", flush=True)
last_executor_id = event.executor_id
print(event.data, end="", flush=True)
Использование пользовательского исполнителя агента
Иногда может потребоваться настроить интеграцию агентов ИИ в рабочий процесс. Это можно сделать, создав пользовательский выполнитель. Это позволяет управлять следующими способами:
- Вызов агента: потоковый или непотоковый режим
- Типы сообщений, которые агент будет обрабатывать, включая пользовательские типы сообщений
- Жизненный цикл агента, включая инициализацию и очистку
- Использование потоков агентов и других ресурсов
- Дополнительные события, создаваемые во время выполнения агента, включая пользовательские события
- Интеграция с другими функциями рабочего процесса, такими как общие состояния и запросы и ответы
internal sealed class CustomAgentExecutor : Executor<CustomInput, CustomOutput>("CustomAgentExecutor")
{
private readonly AIAgent _agent;
/// <summary>
/// Creates a new instance of the <see cref="CustomAgentExecutor"/> class.
/// </summary>
/// <param name="agent">The AI agent used for custom processing</param>
public CustomAgentExecutor(AIAgent agent) : base("CustomAgentExecutor")
{
this._agent = agent;
}
public async ValueTask<CustomOutput> HandleAsync(CustomInput message, IWorkflowContext context)
{
// Retrieve any shared states if needed
var sharedState = await context.ReadStateAsync<SharedStateType>("sharedStateId", scopeName: "SharedStateScope");
// Render the input for the agent
var agentInput = RenderInput(message, sharedState);
// Invoke the agent
// Assume the agent is configured with structured outputs with type `CustomOutput`
var response = await this._agent.RunAsync(agentInput);
var customOutput = JsonSerializer.Deserialize<CustomOutput>(response.Text);
return customOutput;
}
}
from agent_framework import (
ChatAgent,
ChatMessage,
Executor,
WorkflowContext,
handler
)
class Writer(Executor):
agent: ChatAgent
def __init__(self, chat_client: AzureChatClient, id: str = "writer"):
# Create a domain specific agent using your configured AzureChatClient.
agent = chat_client.create_agent(
instructions=(
"You are an excellent content writer. You create new content and edit contents based on the feedback."
),
)
# Associate the agent with this executor node. The base Executor stores it on self.agent.
super().__init__(agent=agent, id=id)
@handler
async def handle(self, message: ChatMessage, ctx: WorkflowContext[list[ChatMessage]]) -> None:
"""Handles a single chat message and forwards the accumulated messages to the next executor in the workflow."""
# Invoke the agent with the incoming message and get the response
messages: list[ChatMessage] = [message]
response = await self.agent.run(messages)
# Accumulate messages and send them to the next executor in the workflow.
messages.extend(response.messages)
await ctx.send_message(messages)
Дальнейшие шаги
- Узнайте, как использовать рабочие процессы в качестве агентов.
- Узнайте, как обрабатывать запросы и ответы в рабочих процессах.
- Узнайте, как управлять состоянием в рабочих процессах.
- Узнайте, как создавать контрольные точки и возобновлять их.
- Узнайте, как отслеживать рабочие процессы.
- Узнайте об изоляции состояния в рабочих процессах.
- Узнайте, как визуализировать рабочие процессы.