If I update the agent state using agent.setState will the agent be aware of the state? like if i query the agent about something whose information is available in the state will the agent be able to answer properly? or do we have to manually use useAgentContext to set the context to the agent state and reset every-time the state changes?
#Query on agent context and agent state
1 messages · Page 1 of 1 (latest)
This solution has been AI generated
Yes—updating the agent with agent.setState makes the agent aware of that data, and it can answer based on it on the next run. You don’t need to mirror this via useAgentContext. If you want an immediate reaction, call agent.runAgent() after setState.
How agent.setState works
- Shared, bidirectional state between UI and agent.
- When you call
setState, the agent sees the new value on its next execution, and your UI re-renders accordingly.
When to use useAgentContext
- Provide supplementary, read-only context the agent should “see” but not “own” (e.g., current UI data, user role, visible items).
- Automatically updates when your reactive source changes—no manual reset required.
Recommended pattern
- Use
agent.setStatefor agent-owned/persistent data the agent or UI may modify. - Use
useAgentContextfor ephemeral/read-only UI context the agent should reference. - Optionally call
agent.runAgent()aftersetStateif you need an immediate response to the change.
Example
const { agent } = useAgent({ agentId: "my-agent" });
function onUpdate() {
agent.setState({ ...agent.state, userInfo: "New Info" });
// Optional: have the agent react right away
agent.runAgent();
}
References
- useAgent (state sync): https://docs.copilotkit.ai/reference/v2/hooks/useAgent
- useAgentContext (dynamic context): https://docs.copilotkit.ai/reference/v2/hooks/useAgentContext
Was this helpful?
If this solution worked for you, please click on the appropriate option below to help us improve: