使用 Protocol Buffers 定义消息类型
要使用 InProcessRuntime 以外的运行时发送消息,必须将其定义为 Protocol Buffers 消息。 这是因为消息使用 Protocol Buffers 进行序列化和反序列化。 未来可能会通过允许转换器、自定义序列化或其他机制来放宽此要求。
如何在 .NET 项目中包含 Protocol Buffers
定义消息类型的 .proto 文件必须包含在项目中,这将自动生成消息的 C# 类。
- 在您的
.csproj
文件中包含Grpc.Tools
包
<PackageReference Include="Grpc.Tools" PrivateAssets="All" />
- 在项目中创建并包含一个
.proto
文件
<ItemGroup>
<Protobuf Include="messages.proto" GrpcServices="Client;Server" Link="messages.proto" />
</ItemGroup>
- 按照 Protocol Buffers 语言指南 中的规定定义您的消息
syntax = "proto3";
package HelloAgents;
option csharp_namespace = "MyAgentsProtocol";
message TextMessage {
string Source = 1;
string Content = 2;
}
- 针对生成的类进行编码,以处理、发送和发布消息
using Microsoft.AutoGen.Contracts;
using Microsoft.AutoGen.Core;
using MyAgentsProtocol;
[TypeSubscription("default")]
public class Checker(
AgentId id,
IAgentRuntime runtime,
) :
BaseAgent(id, runtime, "MyAgent", null),
IHandle<TextMessage>
{
public async ValueTask HandleAsync(TextMessage item, MessageContext messageContext)
{
Console.WriteLine($"Received message from {item.Source}: {item.Content}");
}
}