xAI SuperGrok Per-User Sign-In
Several people share one deployment and each spends their own SuperGrok subscription.
Each identified run first resolves that user's SuperGrok token. With the source's default require_user_token=False, an unsigned user can use the deployment's shared token, then XAI_API_KEY if neither token slot is available. A stored tmp/xai_oauth.db may already contain a shared token from another example.
Set require_user_token=True on xAIResponses(...) when every identified user must sign in personally. This flag does not reject anonymous runs: your application must authenticate requests and pass trusted, nonempty user IDs. A supplied user_id alone is not authentication. The separate session IDs below preserve both users' stored conversations.
Use an xAI account with API access for the selected model; browser sign-in alone does not establish entitlement.
"""
Xai SuperGrok Per-User Sign-In
==============================
Several people share one deployment and each spends their own SuperGrok
subscription. The token is stored under the user_id the run carries, and the
xAI model resolves that user's token per request, so two users on the same
agent never share a credential.
A user who has not signed in falls back to the deployment's own SuperGrok
session - the shared slot a script or an operator signs in to - which is what a
single-subscription deployment wants. Pass require_user_token=True to the model
to refuse that fallback and require every identified user to sign in first.
This script starts from an empty store, so there is no deployment session to
fall back to and the second user is asked to sign in instead. Sign in once
without a user_id, through oauth_device_login.py, to watch the fallback serve
somebody who never signed in.
user_id is passed directly here so the recipe runs without a server. In
production it arrives the same way from AgentOS, off the authenticated request.
Requires OPENAI_API_KEY (for the sign-in agent) and XAI_TOKEN_ENCRYPTION_KEY.
Generate an encryption key with:
python -c "from agno.utils.encryption import generate_encryption_key; print(generate_encryption_key())"
"""
from agno.agent import Agent
from agno.db.sqlite import SqliteDb
from agno.models.openai import OpenAIResponses
from agno.models.xai import xAIResponses
from agno.models.xai.oauth import XAITokenManager
from agno.tools.xai_auth import XAIAuth
# SqliteDb is for local development only; use PostgresDb in production.
# Per-user tokens need a database: one token file cannot hold one session each.
db = SqliteDb(db_file="tmp/xai_oauth.db")
token_manager = XAITokenManager(db=db)
# ---------------------------------------------------------------------------
# Create Agents
# ---------------------------------------------------------------------------
# Not an xAI model: this agent runs the sign-in, so it cannot depend
# on the SuperGrok session it is about to create.
signin_agent = Agent(
model=OpenAIResponses(id="gpt-5.5"),
tools=[XAIAuth(token_manager=token_manager)],
db=db,
# The second turn refers back to the link handed out on the first
add_history_to_context=True,
markdown=True,
)
grok_agent = Agent(
model=xAIResponses(token_manager=token_manager), db=db, markdown=True
)
# ---------------------------------------------------------------------------
# Run Agents
# ---------------------------------------------------------------------------
if __name__ == "__main__":
# --- Alice signs in; the token is stored under her user_id ---
signin_agent.print_response("Sign me in with SuperGrok", user_id="alice")
input("Approve Alice's sign-in in your browser, then press Enter to continue...")
signin_agent.print_response("Done, I approved it", user_id="alice")
# --- Alice's question runs on Alice's subscription ---
grok_agent.print_response("Share a 2 sentence horror story", user_id="alice")
# --- Bob has not signed in: the deployment's shared session answers him,
# or he is told to sign in when the deployment has no session either ---
grok_agent.print_response("Share a 2 sentence horror story", user_id="bob")
# --- Bob signs in, and his requests carry his own subscription ---
signin_agent.print_response("Sign me in with SuperGrok", user_id="bob")
input("Approve Bob's sign-in in your browser, then press Enter to continue...")
signin_agent.print_response("Done, I approved it", user_id="bob")
grok_agent.print_response("Share a 2 sentence horror story", user_id="bob")Run the Example
Set up your virtual environment
uv venv --python 3.12
source .venv/bin/activateInstall dependencies
uv pip install -U agno openai sqlalchemy cryptographySet the sign-in agent's OpenAI key
The sign-in agent uses OpenAI while the user obtains an xAI token.
export OPENAI_API_KEY="your_openai_api_key_here"Configure encrypted token storage
Generate an encryption key once in the activated environment:
python -c "from agno.utils.encryption import generate_encryption_key; print(generate_encryption_key())"Copy the generated key into the environment variable below. Keep the same key in your secret storage and restore it on later runs; do not generate a new one on every restart.
export XAI_TOKEN_ENCRYPTION_KEY="paste_the_generated_key_here"
unset XAI_API_KEYA missing encryption key keeps new tokens in process memory; a placeholder or invalid key cannot encrypt them. Encrypted reuse needs a successful database write, the same key and the same database on later runs. Token refresh also requires a valid grant and provider access. Clearing XAI_API_KEY makes this example exercise OAuth without falling back to a separate API key.
Give each user separate conversations
Add session_id="alice-signin" to both Alice signin_agent.print_response(...) calls and session_id="bob-signin" to both Bob sign-in calls. Add session_id="alice-grok" to Alice's grok_agent.print_response(...) call and session_id="bob-grok" to both Bob Grok calls.
Reuse each ID only for that person's conversation. Without these arguments, a reused Agent keeps one session ID and Bob's conversation cannot be saved under a session owned by Alice. The same SQLite file can retain state from earlier examples; it is not necessarily an empty store.
Run the example
Save the code above as oauth_multi_user.py, then run:
python oauth_multi_user.pyFull source: cookbook/90_models/xai/oauth_multi_user.py