Agentflow icon indicating copy to clipboard operation
Agentflow copied to clipboard

feat: support dynamic system prompt injection via state.extra_system_prompts in Agent.execute()

Open suchith83 opened this issue 8 months ago • 1 comments

Description:

Problem

Agent.execute() builds messages using self.system_prompt — a static list set at __init__(). There is no hook between convert_messages() and _call_llm(), so dynamic system prompt injection is impossible via callbacks today.

The before_invoke(AI) callback fires before execute() and can mutate state, but Agent.execute() never reads state for additional system content. Result: any agent that needs a dynamic system prompt (skills, RAG context, role-based prompts) must subclass Agent and re-implement execute() — coupling agent logic to framework internals.

Proposed Fix — 2 files, ~8 lines

1. agentflow/state/agent_state.py — add one field:

extra_system_prompts: list[dict[str, Any]] = Field(
    default_factory=list,
    description=(
        "Dynamic system prompt additions set by before_invoke callbacks. "
        "Merged into system_prompt before each LLM call by Agent.execute()."
    )
)

2. agentflow/graph/agent.py — 3 lines before convert_messages():

dynamic_system_prompts = list(self.system_prompt)
if getattr(state, "extra_system_prompts", None):
    dynamic_system_prompts.extend(state.extra_system_prompts)

messages = convert_messages(
    system_prompts=dynamic_system_prompts,   # was: self.system_prompt
    state=state,
    extra_messages=self.extra_messages or [],
)

What This Enables

A before_invoke(AI) callback can now inject system prompt content without subclassing:

class SkillInjectionCallback(BeforeInvokeCallback):
    async def __call__(self, context, input_data):
        state = input_data.get("state")
        skill_content = load_skill(state.active_skill)
        state.extra_system_prompts = [{"role": "system", "content": skill_content}]
        return input_data

cm.register_before_invoke(InvocationType.AI, SkillInjectionCallback())
graph.add_node("MAIN", Agent(...))   # plain Agent — no subclassing needed

Backwards Compatibility 100%. extra_system_prompts defaults to [] — all existing agents are unaffected. No changes to convert_messages(), _call_llm(), provider adapters, callbacks, or graph compilation.

Also — _trim_context() bug

_trim_context() currently does await context_manager.trim_context(state) but trim_context is a synchronous method — awaiting it raises TypeError. Should be await context_manager.atrim_context(state).

suchith83 avatar Mar 13 '26 06:03 suchith83

Fixed here: https://github.com/10xHub/Agentflow/pull/67

Iamsdt avatar Mar 24 '26 10:03 Iamsdt