Building LLM-Friendly Graph APIs with TGraphX
When an AI assistant writes graph-learning code, the risky part is rarely the syntax. It is the choices the code does not show: how the split was made, whether a mask is boolean, which way edges point, which model actually ran. An API can make some of those mistakes hard to write and others loud.
This article looks at TGraphX from that angle: what helps, and where the library is forgiving in ways you need to check. Nothing here is a measurement of how well any particular assistant performs. Examples tested with TGraphX 1.5.1 on CPU; the blocks build on one another.
Choice 1: A few core types
For everyday work there are a few names to learn:
tgx.Graphfor a single graphtgx.GraphBatchfor several graphs batched togethertgx.NeighborLoaderfor mini-batch neighbour sampling
The full surface is much larger than this (the readiness report below counts well over a hundred public names, many marked Beta or Experimental), and there are aliases and several loaders. One pair deserves a warning: tgx.train_node_classifier is an alias of tgx.classify_nodes and takes tensors, while tgx.easy.train_node_classifier is a different function that takes a Graph and returns a trained model. In a prompt or a review, use the full name.
Choice 2: PyG-style aliases
People and assistants often write x, y and edge_attr out of PyTorch Geometric habit. Graph accepts them:
import torch
import tgraphx as tgx
torch.manual_seed(0)
N, E = 120, 600
x = torch.randn(N, 3, 8, 8) # [N, C, H, W]
ei = torch.randint(0, N, (2, E)) # [2, E]
y = torch.randint(0, 3, (N,))
g = tgx.Graph(node_features=x, edge_index=ei, node_labels=y) # canonical
g_alias = tgx.Graph(x=x, edge_index=ei, y=y) # PyG-style
assert g_alias.node_features is g.node_features
assert g_alias.y is g.node_labels
assert g_alias.x is x
The aliases are alternative spellings of the same fields (labels= works for node labels too). The object does not record which spelling you used. Passing two spellings of one field with different tensors raises ValueError.
Choice 3: One-call entry points
Common workflows have a single function each:
result = tgx.classify_nodes(x, ei, y, model="tensor_gcn", seed=42, device="cpu")
triples = torch.stack([torch.randint(0, 50, (300,)), # head
torch.randint(0, 4, (300,)), # relation
torch.randint(0, 50, (300,))], 1) # tail
kg = tgx.kg_completion(triples, num_entities=50, num_relations=4,
model="transe", seed=42, device="cpu")
ba = tgx.generate_graph("ba", num_nodes=100, m=3, seed=42)
evo = tgx.optimize_graph(objective="connectivity", algorithm="ga", num_nodes=30, seed=42)
rl = tgx.train_graph_rl(env="maxcut", algorithm="dqn", episodes=50, seed=42, device="cpu")
print(result.metrics)
print(kg.metrics)
Short calls are convenient, but check what they did, because these helpers do not validate everything. All of the following runs without an error:
# the model string is recorded, not checked: vector features always train a GCN
r = tgx.classify_nodes(torch.randn(N, 8), ei, y, model="banana", device="cpu")
assert r.config["model"] == "banana"
# unknown keywords are swallowed
a = tgx.generate_graph("er", num_nodes=50, p=0.1, seed=0)
b = tgx.generate_graph("er", num_nodes=50, edge_prob=0.1, seed=0) # ignored, p stays 0.3
assert b.num_edges > 2 * a.num_edges
# fast mode (the default) caps what you asked for
assert rl.config["episodes"] == 5 # 50 were requested
assert len(evo.fitness_history) == 3 # the default asks for 10 generations
build_model() also ignores keyword arguments it does not know. For optimize_graph, pass fast_mode=False and generations=.
Choice 4: Specific error messages
The Graph constructor says what is wrong and by how much:
bad_edges = torch.tensor([[0, 5], [1, N]]) # node id N does not exist
try:
tgx.Graph(x=x, edge_index=bad_edges, y=y)
except ValueError as err:
message = str(err)
else:
raise AssertionError("an out-of-range node id should be rejected")
print(message)
# edge_index contains out-of-range indices for 120 nodes
# (found min=0, max=120; valid range [0, 119])
That message is what an assistant should be given. There is also tgx.explain_error(), but read its output critically:
hint = tgx.explain_error(message)
print(hint)
assert "transpose" in hint # not the problem here
It is a small keyword table (_ERROR_MAP in tgraphx/ux/helpers.py). The first key found in the message selects a canned paragraph; the exception type and your tensors are not examined. Here the word edge_index picks advice about a transposed [E, 2] layout, which has nothing to do with an invalid node id. Treat it as a hint list, not a diagnosis.
Choice 5: A readiness report
python -m tgraphx readiness
This prints the versions, required and optional dependencies, public API counts by stability level, workflow task names, feature flags and known limitations. The same information is available as a dictionary:
report = tgx.audit_package_readiness()
print(report["tgraphx_version"], report["public_api"])
print(report["workflow_tasks"])
It is useful context to paste into a prompt, with one caution: the task list includes graph_classification and graph_generation, which tgx.workflow() rejects with NotImplementedError in 1.5.1.
A review checklist for generated code
- Are the function and argument names real? Where a function accepts
**kwargs, a wrong name may raise nothing:generate_graph,build_modelandoptimize_graphaccept it silently, whileGraphDataLoaderforwards it to PyTorch, which raises. - Are all three masks passed to
classify_nodes, as boolean tensors? - Does
NeighborLoadergetmask=graph.train_mask? Withmask=None, every node is a seed. - Does
tgx.easy.train_node_classifiergetmask=graph.train_maskwith the default neighbour sampler? Withoutmask=it trains on every node, andsampler="full"ignores the mask. - Is
fit()being used for node classification? It ignores node masks and trains on every labelled node. - Is
check_leakagecalled with keyword arguments? Positional masks bind to the wrong parameters. - Did the architecture named in the report actually run?
The researcher's side of the same question is covered in why explicit APIs help LLM-assisted coding.
What this does NOT mean
LLM-friendly is not the same as good for every project. For custom losses or sampling schemes, write the training loop yourself with TGraphX layers; the one-call helpers will not stretch that far. Your own message passing alone does not require that: tgx.easy.train_node_classifier accepts a module with forward(x, edge_index) as model=. PyTorch Geometric offers many more built-in layers and datasets and may be the better fit.
Trade-offs
- One-call helpers hide their defaults. Reading the source is sometimes the only way to learn them.
- Aliases mean two spellings can appear in one codebase.
- Forgiving wrappers turn some typos into silent changes of behaviour.
FAQ
Q: Can I disable the alias system if I prefer strict canonical names?
A: There is no switch. Use only the canonical names in your own code, and enforce that in review if you care.
Q: Does this design help only AI-generated code?
A: No. Early input checks and clear names help any reader. The silent cases above can catch humans just as easily.
Q: How does tgx.explain_error() work?
A: It looks for known keywords in the error text and returns the matching paragraph. If none matches, it tries a fuzzy match and otherwise returns general suggestions.
Q: Is there a guide for LLM-assisted code?
A: The GitHub repository has docs/llm_usage_guide.md. It is not part of the installed wheel, and generated or copied snippets should still be run against your installed version.