td-agentops-custom-agent¶
Deploy your own LangChain/LangGraph agent to Teradata AI Studio's AgentOps platform. For the tdfs4ds consumer agent use fs-deploy-agentops.
name: "AgentOps: Deploy a custom LangChain agent"
description: "Deploy YOUR OWN LangChain/LangGraph agent to Teradata AI Studio's AgentOps platform, wired to a Vantage database connection, the Enterprise Vector Store and the MCP server. Covers the runtime contract, the entrypoint coroutine trap, per-caller authentication, the pod's missing DNS, the two AI Studio tokens, and the 132-tool context budget. Invoke when the user has (or wants) a custom agent of their own to host on AI Studio. SKIP when the agent to deploy is the tdfs4ds consumer agent — use fs-deploy-agentops, which generates the whole package."
argument-hint: "[agent-directory][resources: db|vectorstore|mcp]"
allowed-tools: "Read, Edit, Write, Bash, Glob, Grep"
Deploy a custom LangChain agent as a hosted service on Teradata AI Studio's AgentOps platform, with a Vantage connection, the Enterprise Vector Store and the MCP server available to it.
User context: $ARGUMENTS
Everything below was established against a live AI Studio deployment. Each rule exists because its absence produced a specific failure, and those failures are named — most of them do not say what is actually wrong.
Related skills¶
| Step | Skill | Why |
|---|---|---|
| Instead | fs-deploy-agentops |
If the agent IS the tdfs4ds consumer agent, one call generates and deploys the whole package. Don't hand-roll it. |
| Before | fs-setup |
The connection settings the pod needs are the ones a working session already proves. |
| Reference | fs-vector-store |
Backend choice, auth mechanisms, service version. |
1. The deployment unit¶
AgentOps deploys a zip:
| File | What it is |
|---|---|
agent.py |
the platform entry point — registers one entrypoint |
customer_agent.py |
your agent |
config.yaml |
non-secret settings, committed to source control |
requirements.txt |
pip dependencies, installed at image build time |
agent_runtime/ |
the platform's own SDK |
agent_runtime is on no package index. The PyPI names agentops and agent_runtime are
unrelated third-party projects; putting either in requirements.txt gives a green build and an
ImportError at pod start. Use the platform's copy, or an implementation of its two-symbol contract
(AgentRuntimeApp, AuthContext).
The image build runs pip install -r requirements.txt against a package index. A local or
editable install is invisible to it. Anything of your own that the agent imports must be published,
or vendored into the zip.
2. The entrypoint must be a bare coroutine¶
# agent.py
from agent_runtime import AgentRuntimeApp, AuthContext
from customer_agent import get_agent
app = AgentRuntimeApp()
# NOTHING may wrap this function between the decorator and `async def`.
@app.entrypoint
async def invoke(message, streaming=False, session_id=None,
auth_context: AuthContext = None):
return await get_agent().run(
message,
token=getattr(auth_context, "token", None),
auth_headers=(auth_context.get_auth_header() if auth_context else None),
user_id=getattr(auth_context, "user_id", None),
session_id=session_id,
)
AgentRuntimeApp.is_async is inspect.iscoroutinefunction(self._entrypoint), and _entrypoint is
whatever @app.entrypoint received. Decorators apply bottom-up, so any decorator placed between
the two — a tracing decorator is the tempting one — becomes what gets registered. If it returns a
plain function, is_async reports False and the platform drives an async agent synchronously.
Never trace with a decorator. For spans inside a turn, put a tracer callback in the LangGraph run
config (config["callbacks"] = [OpikTracer(...)]); LangChain hands it down to every node and model
call. tdfs4ds does this itself when TDFS4DS_TRACING=opik (tdfs4ds.utils.tracing.run_callbacks).
The Opik SDK reads the platform-injected OPIK_* settings, and the entrypoint stays a bare coroutine.
thread_id must never fall back to a constant. A fixed string puts every caller of the service
into one shared conversation:
def _thread_id(session_id, user_id):
if session_id: # the platform passes it
return str(session_id)
if user_id: # per-caller isolation
return "user:%s" % user_id
return str(uuid.uuid4()) # never shared
3. Build once, at module scope¶
The platform calls the entrypoint per request. A factory that builds the graph, opens the database context and loads the vector index inside the entrypoint pays all of it on every turn.
# customer_agent.py
import asyncio
_AGENT = None
_TURN_LOCK = asyncio.Lock() # see below
def get_agent():
global _AGENT
if _AGENT is None:
_AGENT = _build() # graph, memory, tools - once per process
return _AGENT
Serialise turns with an asyncio.Lock if anything your agent does mutates process-global state.
teradataml holds one process-wide context, so two concurrent turns rebuilding it for different
callers clobber each other. The lock is what makes per-caller authentication safe at all:
async def run(self, message, *, token=None, auth_headers=None, ...):
async with _TURN_LOCK:
_bind_caller(token, auth_headers) # per-caller state
return await asyncio.to_thread(self._blocking_turn, message, thread_id)
A blocking LangChain agent belongs in asyncio.to_thread, not called directly from the coroutine.
4. The database connection¶
The pod has no DNS for the database¶
TD_HOST must be the database's IP address. dbc does not resolve from inside an AgentOps pod,
and neither does any qualified form — while the notebook resolves it fine, and every other
in-cluster service is reached by fully-qualified name
(litellm.modelhub.svc.cluster.local, vectorstore.vectorstore.svc.cluster.local), which is exactly
what makes a bare dbc look normal.
Classify a connection failure by elapsed time. TDML_2000 Failed to connect says nothing about
why. A failure in ~90 ms is a name that did not resolve; a TCP timeout takes seconds. Log the
chained cause (__cause__), never just the first line — the wrapper names the symptom and the cause
names the fault.
Two auth modes, and which to choose¶
| mode | how | trade-off |
|---|---|---|
| service | one long-lived context from TD_USERNAME/TD_PASSWORD at import |
works indefinitely; a durable password sits in the deployment record; every caller shares one database identity |
| jwt | the caller's token, per request | expiry self-heals (a new token arrives each call), the pod connects as the caller — real permissions, real audit — and no durable password is stored |
Prefer jwt for a pod — the reasoning is the opposite of a notebook, where a ~2h token is the
thing that makes a .env stop working. In a pod the token arrives per request, so expiry is a
non-issue.
But jwt is conditional on something outside your control, and this is the trap:
AI Studio issues two tokens that look alike and are not interchangeable. The session/SSO token authenticates against the platform's own services.
%gen_token'suser_tokenis minted for a Vantage logon. Confirmed live: the first is refused by the database withError 8017 / SQLState 28000, the second is accepted, and they are different strings.
A pod cannot call %gen_token. So auth='jwt' only works if the platform's auth_context.token is
itself accepted by Vantage as a JWT logon — a Vantage-side trust setting for the token's issuer,
not anything you configure in the agent. Settle it from a notebook before deploying:
import teradatasql
teradatasql.connect(host='<ip>', logmech='JWT', logdata='token=' + the_token).close()
Error 8017 there means jwt is not deployable on that site; use service.
# per caller, inside the turn lock
import teradataml as tdml
def _bind_caller(token):
fingerprint = hashlib.sha256((token or "").encode()).hexdigest()[:16]
global _BOUND
if fingerprint != _BOUND: # rebuild only when the caller changes
tdml.create_context(host=TD_HOST, logmech='JWT',
logdata='token=%s' % token)
_BOUND = fingerprint
Key on a fingerprint, never the token itself, and never log either.
5. The Vector Store¶
Authentication is teradataml.set_auth_token, and tdfs4ds resolves it from
TDFS4DS_VECTOR_STORE_AUTH_* in a fixed order — JWT, PAT, Basic, OAuth — first fully-configured
group wins:
from tdfs4ds.utils.vector_store_auth import configure_vector_store_auth
configure_vector_store_auth() # non-raising; logs the mechanism used
Four things that cost real debugging time:
- The JWT path needs a username when there is no active context. teradataml derives it from the
active database session when omitted and raises
username should be passed in the parameters or call create_context() before using set_auth_token(). SetTDFS4DS_VECTOR_STORE_AUTH_USERNAME, or open the context first. - A ready-made JWT is stored unvalidated — teradataml's validation call is commented out
upstream — so
set_auth_tokensucceeds with an expired token and the failure appears later, at the first call that spends it. SQLState 28000is not "service down". It means the service was reached and the database refused the credential it presented for you. Do not go looking at licensing. Usual cause: an expired token.- The service version matters —
>= 2.1.11. An older one is up, accepts the credential, and misbehaves only on write. It is a Vantage platform component; upgrading is an admin action, not apip install.
Prefer in-database embedding in a pod — no credential at all, authenticated by the session:
TDFS4DS_VECTOR_STORE_BACKEND: teradata
TDFS4DS_TERADATA_AI_API_TYPE: td_hosted
TDFS4DS_TERADATA_AI_MODEL_NAME: amazon.titan-embed-text-v2:0
A Chroma index lives on the container filesystem and is rebuilt on every restart. For a pod, use the Teradata backend.
6. The MCP server¶
It needs the caller's bearer, and the gateway logs on to the database with it¶
# inside the turn lock, before building the tools
os.environ['TDFS4DS_MCP_SERVER_HEADERS'] = json.dumps(auth_headers)
AuthContext.get_auth_header() builds it — its own docstring names the MCP server as the intended
consumer. Neither a static header nor Basic-from-a-password can carry a per-caller token in a pod.
The Enterprise gateway opens a Teradata session with the bearer it is given. That is why a
refusal arrives as the database's Error 8017 — The UserId, Password or Account is invalid, and
not an HTTP 401: the bearer has to be a database credential, which is stricter than being a
valid token. An invalid token fails earlier and differently, as Invalid JWT token. No agent-side
setting fixes an 8017 here — it is the same two-token problem as §4.
132 tools will overflow the context window¶
A live Enterprise server exposes 132 tools; Community exposes a few dozen. Every tool's JSON
schema is sent to the model on every turn, before the question is read, and the full set
overflows outright — surfacing as a 400 that misleadingly mentions "tools"
(litellm.ContextWindowExceededError).
from tdfs4ds.agent.mcp_connection import build_mcp_connection, select_tools
tools = select_tools(all_tools, question, max_tools=32)
select_tools ranks by deterministic token overlap on name+description — no LLM, no round trip —
and returns the list untouched at or below the cap, so a small tool set is unaffected. If you
bind MCP tools anywhere, route them through it.
7. Config, secrets, and what is actually confidential¶
| Destination | Contents |
|---|---|
config.yaml |
anything neither secret nor environment-specific — committed to source control |
runtime_config |
credentials, plus TD_* / VECTOR_STORE_AUTH_* even when not secret, since they identify a deployment |
runtime_config is not a vault. Verified against a live deployment UI: its values are stored in
the deployment record and rendered in clear there. Its real guarantee is "not committed to
source control" — you are buying durability and blast radius (git history is permanent; a
deployment record can be deleted and rotated), not secrecy. Never describe it as confidential.
Two names that look innocent and are not: MCP_USERNAME is half a credential pair (it falls back
to the database username), and MCP_AUTH is an auth-mode override a committed file could use to
change how the pod authenticates. Both belong in runtime_config.
8. Structured output: check what the gateway enforces¶
If your agent asks the model for typed JSON, do not assume the endpoint honours the request.
Measured on a live LiteLLM gateway: of nine constraint syntaxes, eight were accepted and ignored
and only tool calling was enforced — the model answered **Classification:** ... to a request
for JSON.
The JSON constraints row reports what the endpoint enforces and what to set; pin=True writes
STRUCTURED_OUTPUT_METHOD into the .env. That value travels into the pod's config.yaml —
correct when the pod shares the gateway, wrong if it does not.
Capability checks need no feature store — run them before anything else exists.
9. Deploy checklist¶
Run in this order. Each line is a failure someone has already had.
[ ] the package (and every private dependency) is published to the index the build uses
[ ] requirements.txt names neither `agentops` nor `agent_runtime`
[ ] nothing sits between @app.entrypoint and `async def`
[ ] thread_id derives from session_id / user_id, never a constant
[ ] TD_HOST is the database's IP address, not `dbc`
[ ] if auth='jwt': a raw teradatasql JWT logon with the platform token SUCCEEDS
[ ] VECTOR_STORE_AUTH_USERNAME is set, or a context is opened before set_auth_token
[ ] Vector Store service version >= 2.1.11
[ ] MCP tools go through select_tools
[ ] deploy with MCP OFF first - it removes auth and the tool budget from the picture
[ ] blocking work is in asyncio.to_thread; global-mutating work is inside the lock
[ ] resources >= 2Gi / 1000m
10. Reading the failure¶
| Symptom | What it means |
|---|---|
ImportError: agent_runtime |
the PyPI package was installed instead of the platform's |
| green build, dies at start | same |
TDML_2000 in ~90 ms |
DNS - TD_HOST must be the IP |
TDML_2000 after seconds |
reachable but refused or unroutable |
Error 8017 from MCP |
the gateway's own database logon - the bearer is not a database credential |
SQLState 28000 from the Vector Store |
expired token, or the user cannot log on the way the service logs on for it |
| 400 mentioning "tools" | the tool schemas overflowed the context - cap them |
'str' object has no attribute 'model_dump' |
the endpoint answered 200 with a non-JSON body - wrong URL path, or an ingress login page. Not a certificate problem |
bare Error code: 302 |
a custom http_client without follow_redirects=True |
| every caller sees one conversation | thread_id fell back to a constant |
| the agent answers, but never uses a tool | is_async is False - something wrapped the entrypoint |
Documented limits of a pod deployment: replicas: 1, enable_memory: False, conversation
memory lost on restart. Plan for them rather than discovering them.