UserProxyAgent を SelectorGroupChat に入れる方法
💡 そもそも UserProxyAgent って何?
これは人間ユーザーの立場で発言するためのAgent。
通常は human_input_mode="ALWAYS" にすれば、毎ターンで人間が入力できるようになる。
🔁 でも SelectorGroupChat では注意が必要!
❗問題点
SelectorGroupChat は 「誰が話すか」を LLM か selector_func で決める ので、UserProxyAgent を入れても LLMがそれを選ばない限り、人間の出番が来ない!
✅ 解決法:UserProxyAgent にも選ばせるように設定する!
① まず UserProxyAgent を作る
pythonCopyEditfrom autogen_agentchat.agents import UserProxyAgent
user_agent = UserProxyAgent(
name="HumanUser",
human_input_mode="ALWAYS", # これで呼ばれたら必ず入力待ちになる
code_execution_config=False,
description="人間のユーザー。必要なときに助けます。"
)
② SelectorGroupChat に入れる
pythonCopyEditteam = SelectorGroupChat(
[user_agent, assistant_agent_1, assistant_agent_2],
model_client=model_client,
selector_prompt=selector_prompt,
termination_condition=MaxMessageTermination(10)
)
これで、人間もエージェントと同列に「話者候補」に含まれるようになる。
🧠 ③ selector_prompt に人間を考慮させる
textCopyEdit次の話者を選んでください。人間(HumanUser)がサポートできそうな場合は彼を選んでも構いません。
候補:
{participants}
エージェントの説明:
{roles}
会話の履歴:
{history}
※ このように書いておくことで、GPT-4などのLLMがHumanUserを選びやすくなります。
📝 会話時の流れ(例)
- 初期プロンプトを
team.run()で渡す - LLMが
HumanUserを選んだら、ターミナルに「あなたの番です」みたいに出て入力待ちになる - 入力すると会話が進行
✅ まとめ
| 項目 | 設定内容 |
|---|---|
UserProxyAgent | 人間ユーザーとして発言できるAgent |
human_input_mode | "ALWAYS" で話者に選ばれたら入力できる |
SelectorGroupChat | UserProxyAgent も参加させられる |
selector_prompt | 人間に発言させたい場合、その意図を明記すると良い |
🧪 追加Tips
human_input_mode="TERMINATE"にすれば、手動で終了させる係としても使える。allow_repeated_speaker=Trueにしておくと、連続で人間が話すこともできる。
🧪 人間が思い立ったタイミングで会話に割り込むようにできないか?
❌ SelectorGroupChat だけでは「人間が任意のタイミングで割り込む」ことはできない。
なぜか?
SelectorGroupChatは 次に誰が話すかを LLM か selector_func に選ばせる 仕組み。UserProxyAgentも「選ばれた時」しか入力できない(human_input_mode="ALWAYS"でも)。
✅ じゃあ、どうやる?
方法①:human_input_mode="MANUAL"+ループで message を送る(擬似割り込み)
pythonCopyEdituser = UserProxyAgent("human", human_input_mode="MANUAL")
# 手動で会話中に人間の発言を挿入
await user.send("ちょっと割り込みます!この点が気になります。", recipient=team)
これを、SelectorGroupChat.run() の外で呼べば、会話に途中割り込みができる!
方法②:run_in_background() でチャットを非同期に動かしつつ、人間が随時 send() する
pythonCopyEditchat_task = asyncio.create_task(team.run_async(task="話し合い開始"))
# 別のタイミングで割り込む
await asyncio.sleep(3)
await user.send("割り込み発言します!ここ重要ですよ", recipient=team)
await chat_task
これなら、本物のチャットっぽく、任意タイミングで割り込み発言ができます。
方法③:selector_func の中で「人間を優先する条件」を入れる(間接的)
pythonCopyEditdef human_first_selector(participants, last_speaker, history, **kwargs):
if "?" in history[-1]["content"]:
return "human" # 質問には人間で返すなど
return participants[0].name # デフォルト
これでも人間に発言が回りやすくなるけど、本当の割り込みではないね。
✅ まとめ
| 方法 | 内容 | 割り込み感 |
|---|---|---|
send() で手動挿入 | 人間が任意タイミングで発言 | ✅ 本物の割り込み |
run_async()+await send() | 会話を非同期に走らせながら人間が挿入 | ✅ 本物の割り込み |
selector_func で優先条件 | 人間が選ばれる確率を上げる(間接的) | △ 擬似割り込み |
✅ 結論:
本物の「割り込み」がしたければ、
run_async()でチャットを動かしながら、人間がsend()で差し込む方式がベスト!


コメント