The four built-in speaker selection methods do not cover every routing rule. AG2 lets you pass a custom function that receives the last speaker and the group chat, and returns either an agent from the group or one of the built-in method names, so your own rules decide who speaks next.
Before you start
You need a working AG2 group chat where the built-in methods route wrongly. Write the routing rules as a short list first: after the planner, the admin; after the admin approves, the engineer; and so on.
Write the function with one rule per transition
Write a function that takes the last speaker and the group chat and returns the next agent. Use the message history and the agent list from the group chat object to decide. Keep each rule to one line, and fall back to auto when no rule matches, so an unexpected state still gets a speaker.
Pass the function and test every transition
Pass the function as the speaker selection method when you create the GroupChat. Run a chat that exercises every rule and read the speaker order in the log. If a rule never fires, the last-speaker check is comparing the wrong name.
Worked example: Custom routing for a fictional research group
Maple Research is a fictional research desk. Its group chat routes by fixed transitions. The table shows the rules.
| Last speaker | Next speaker | Rule |
|---|---|---|
| planner | admin | Admin reviews every plan |
| admin, approved | engineer | Work starts after approval |
| engineer | executor | Executor runs the code |
| executor | scientist | Scientist reads the result |
Expected result (UNTESTED): the log shows the speakers following the table order, with the admin asked after every plan. We checked the AG2 custom speaker selection documentation, which describes the function shape and the allowed transitions, but we did not run the chat on this machine.
Limits
A custom function is code you own: a bug in it can stall the chat or loop two agents forever. Keep the rules short, always include a fallback, and keep the max_round limit in place so a routing bug ends the run instead of looping.
