You talk to an NPC, and for two seconds the screen just sits there. That's the first thing you meet when you wire an external language model into a UE5 prototype.
The frame-rate counter won't tell you why. More often than not, the game thread is simply waiting for an HTTP response.
Below is where I draw the first line when designing in-game agents for UE5, step by step. The code is excerpted, but close enough to run once you adapt it.
First, where does Antigravity actually work?
Until this is settled, the rest of the design can't move.
My understanding is that Antigravity is an agentic tool on the development side. It isn't shipped as a runtime SDK that you bundle into a game and run on the player's machine. At least, I haven't found an official UE5 plugin you can ship inside a build. Things may have changed by the time you read this, so please check the official documentation.
Seen that way, the work splits in two.
| Phase | What happens | Antigravity's role |
|---|---|---|
| Authoring (editor side) | Writing the plugin and C++, building the bridge server, generating PCG parameters, review | Yes. This is where it earns its place |
| Runtime (player machine or server) | Inference requests to a model, such as NPC dialogue | None. A bridge calls an external model API |
From here on, "in-game agent" means the runtime piece that asks a model what an NPC should say. Class names such as FAgentBridge are placeholders for illustration, not a real official SDK.
Let Antigravity handle authoring, and let a small bridge handle runtime. Once that line is drawn, most later decisions get easier.
Three integration architectures
The runtime call path boils down to three shapes.
Pattern A: client built into a plugin
You ship a model-API client as a UE5 plugin and expose it to Blueprint. Gameplay programmers can use it without touching C++.
// AgentBridgeComponent.h (excerpt; class names are illustrative)
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnDialogReceived, const FString&, Text);
UCLASS(ClassGroup=(AI), meta=(BlueprintSpawnableComponent))
class MYGAME_API UAgentBridgeComponent : public UActorComponent
{
GENERATED_BODY()
public:
UFUNCTION(BlueprintCallable, Category="AI|Agent")
void RequestNPCDialog(const FString& Context, const FString& NPCRole);
UPROPERTY(BlueprintAssignable, Category="AI|Agent")
FOnDialogReceived OnDialogReceived;
};The cost is keeping the plugin current with every UE5 release, plus the risk of embedding an API key in a product. The second one weighs more: once a key ships, assume players can extract it.
Pattern B: separate-process HTTP bridge
Run a bridge on a separate server and call it from UE5 over HTTP. Only the bridge holds the API key. Dependencies stay cleanly separated, which is why I'd pick this for a prototype.
void UAgentService::SendPromptAsync(const FString& Context, TFunction<void(bool, FString)> Done)
{
// Build JSON with a serializer, not string concatenation (quotes and newlines will break the payload)
TSharedRef<FJsonObject> Body = MakeShared<FJsonObject>();
Body->SetStringField(TEXT("context"), Context);
FString Payload;
TSharedRef<TJsonWriter<>> Writer = TJsonWriterFactory<>::Create(&Payload);
FJsonSerializer::Serialize(Body, Writer);
TSharedRef<IHttpRequest, ESPMode::ThreadSafe> Request = FHttpModule::Get().CreateRequest();
Request->SetURL(TEXT("http://127.0.0.1:9911/agent/respond"));
Request->SetVerb(TEXT("POST"));
Request->SetHeader(TEXT("Content-Type"), TEXT("application/json"));
Request->SetContentAsString(Payload);
Request->SetTimeout(4.0f); // decide the longest you will make the player wait
Request->OnProcessRequestComplete().BindLambda(
[Done](FHttpRequestPtr, FHttpResponsePtr Res, bool bOk)
{
const bool bGood = bOk && Res.IsValid() && Res->GetResponseCode() == 200;
Done(bGood, bGood ? Res->GetContentAsString() : FString());
});
Request->ProcessRequest();
}The bridge itself can be TypeScript or Python. Swapping models or prompts doesn't require rebuilding the game.
// bridge/server.ts (excerpt): the API key comes from the environment and never reaches the game
import http from "node:http";
const ENDPOINT = process.env.MODEL_ENDPOINT!;
const API_KEY = process.env.MODEL_API_KEY!; // keep real values out of the repository
http.createServer(async (req, res) => {
if (req.method !== "POST" || req.url !== "/agent/respond") {
res.writeHead(404).end();
return;
}
const chunks: Buffer[] = [];
for await (const c of req) chunks.push(c as Buffer);
const { context } = JSON.parse(Buffer.concat(chunks).toString("utf8"));
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 3500); // shorter than the game's 4 seconds
try {
const r = await fetch(ENDPOINT, {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${API_KEY}` },
body: JSON.stringify({ prompt: String(context).slice(0, 2000) }),
signal: ctrl.signal,
});
if (!r.ok) throw new Error(`upstream ${r.status}`);
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify(await r.json()));
} catch {
res.writeHead(504).end(); // the game falls back to a canned line
} finally {
clearTimeout(timer);
}
}).listen(9911, "127.0.0.1");One caveat. A localhost bridge is convenient on a dev machine but it isn't a shipping architecture. For release, either host it on your own authenticated server or move to Pattern C.
Pattern C: dedicated inference runtime
A separate inference node does the model work and UE5 acts purely as a client. It fits games where many agents run at once, or where the server holds authority in multiplayer. There's more to operate, but you control cost ceilings and rate limits in one place.
| Concern | A: built-in | B: HTTP bridge | C: dedicated runtime |
|---|---|---|---|
| Speed of prototyping | Slow | Fast | Somewhat slow |
| Where the API key lives | Inside the product (risky) | On the bridge | On your server |
| Tracking UE5 updates | Required | Mostly none | Mostly none |
| Suitability for shipping | Depends on key handling | Not on its own | Good |
I'd prototype with B and plan to move to C once release is in sight, keeping the HTTP entrance identical. If the entrance stays the same, migration is mostly a matter of where the bridge runs.
NPC agents: decide when to call first
Calling every frame inflates cost, and calling too rarely kills the sense of a living NPC. The workable middle is event-driven: a Behavior Tree task that fires only when state changes.
Limit the triggers to things like player approach, conversation start and a change in hostility. Write the result to the Blackboard so existing AI reads it as an ordinary key.
// BTTask_AgentRespond.cpp (excerpt)
EBTNodeResult::Type UBTTask_AgentRespond::ExecuteTask(UBehaviorTreeComponent& OwnerComp, uint8* NodeMemory)
{
UBlackboardComponent* BB = OwnerComp.GetBlackboardComponent();
AAIController* AIC = OwnerComp.GetAIOwner();
if (!BB || !AIC || !AIC->GetPawn()) return EBTNodeResult::Failed;
UAgentService* Service = AIC->GetPawn()->FindComponentByClass<UAgentService>();
if (!Service) return EBTNodeResult::Failed;
const FString Context = BB->GetValueAsString(ContextKey.SelectedKeyName);
TWeakObjectPtr<UBehaviorTreeComponent> WeakComp(&OwnerComp);
const FName ResponseName = ResponseKey.SelectedKeyName;
Service->SendPromptAsync(Context, [this, WeakComp, ResponseName](bool bOk, FString Text)
{
if (!WeakComp.IsValid()) return; // the NPC was gone before the reply arrived
UBlackboardComponent* BBNow = WeakComp->GetBlackboardComponent();
if (BBNow) BBNow->SetValueAsString(ResponseName, bOk ? Text : FallbackLine);
FinishLatentTask(*WeakComp, bOk ? EBTNodeResult::Succeeded : EBTNodeResult::Failed);
});
return EBTNodeResult::InProgress;
}Two things are non-negotiable. Return InProgress and let the result arrive later, because waiting synchronously stalls the game thread. And never capture a bare reference to OwnerComp in the lambda: if the level changes while you wait, you'll touch a dangling reference and crash.
When NPCs need to coordinate, I find it easier to have one mediator that holds "the state of the town" and let each NPC query it, rather than have everyone ask everyone. Contradictions in dialogue become visible in one place.
Procedural generation: use it at authoring time
Letting a model generate levels during play makes the wait fatal. Authoring-time automation is the realistic home for it.
With UE5's Procedural Content Generation (PCG) framework, the flow looks like this.
- Write the spec in natural language ("desert ruins, medium difficulty, 15 minutes, three mandatory-dodge traps")
- Have an Antigravity agent generate the parameter JSON for the PCG graph
- Batch-run with
UnrealEditor-Cmd.exeand save the level assets - A designer opens the result in the editor and adjusts it by hand
What makes this work is not skipping step 4. The output is a first draft, and whether it's fun to play is a human call. Also validate the step-2 JSON against a schema before it reaches PCG. Out-of-range values and missing keys will show up sooner or later.
Three ways to protect the frame rate
For runtime calls, everything reduces to one rule. Never let the outside world stall the game thread.
First, make every call asynchronous. A blocking wait such as Future::Wait() is best left out even for quick debugging.
Second, cache responses. The same NPC in the same situation often gives a similar reply, so an LRU cache keyed on (NPC_ID, situation code) can cut call volume. How much depends heavily on your game, so don't assume a number: log the hit rate and measure.
class FResponseCache
{
public:
TOptional<FString> Get(const FString& Key)
{
FScopeLock Lock(&Mutex);
if (FEntry* E = Map.Find(Key))
{
E->LastUsed = FPlatformTime::Seconds();
return E->Value;
}
return {};
}
void Put(const FString& Key, const FString& Value)
{
FScopeLock Lock(&Mutex);
if (Map.Num() >= MaxEntries) EvictOldest();
Map.Add(Key, { Value, FPlatformTime::Seconds() });
}
private:
struct FEntry { FString Value; double LastUsed; };
TMap<FString, FEntry> Map;
FCriticalSection Mutex;
static constexpr int32 MaxEntries = 512;
void EvictOldest()
{
const FString* OldestKey = nullptr;
double Oldest = TNumericLimits<double>::Max();
for (const TPair<FString, FEntry>& P : Map)
{
if (P.Value.LastUsed < Oldest) { Oldest = P.Value.LastUsed; OldestKey = &P.Key; }
}
if (OldestKey) Map.Remove(*OldestKey);
}
};Third, batch. When several NPCs want to speak in the same frame, fold them into one request. The more NPCs you have, the more room this gives you to hold call volume down.
Three pitfalls to defuse early
These are the places I expect almost any such build to pass through. I'm not presenting them as war stories from a shipped title. They're the points I'd rule out in advance while assembling the architecture.
Pitfall 1: game-thread waits cause hitching
If an HTTP round trip takes a few hundred milliseconds, the game thread stops for that long. Even after going async, a lambda that captures this or a raw pointer will crash if the object is destroyed before the reply. Hold it with TWeakObjectPtr and check validity when the response returns.
Pitfall 2: works in the editor, fails in the packaged build
If you ship external DLLs inside a plugin, a Shipping build may omit them and fail at startup. Declare runtime dependencies in Build.cs and narrow the target platforms correctly in .uplugin.
// MyAgentPlugin.Build.cs (example for a setup that bundles a DLL)
public MyAgentPlugin(ReadOnlyTargetRules Target) : base(Target)
{
RuntimeDependencies.Add("$(PluginDir)/Binaries/ThirdParty/agent_client.dll");
PublicDelayLoadDLLs.Add("agent_client.dll");
}{
"Modules": [
{
"Name": "MyAgentPlugin",
"Type": "Runtime",
"LoadingPhase": "Default",
"PlatformAllowList": ["Win64"]
}
]
}The platform key in .uplugin was renamed from WhitelistPlatforms to PlatformAllowList. Copying an older post verbatim can produce warnings, so check against your UE5 version.
The HTTP-bridge approach (Patterns B and C) makes this class of problem far less likely. Either way, run a packaged build early in the project.
Pitfall 3: the world drifts apart in multiplayer
If each client queries the model on its own, every player gets a different reply and the same NPC talks like a different person. Generate on the server only, and replicate the result.
Multiplayer: authority on the server, expression on the client
The server (dedicated, or the listen-server host) makes the request and decides the response text and animation ID. Clients receive that and play it back locally.
There's room for craft in how the wait looks. Fire a short gesture the moment the request goes out, such as opening the mouth or a thinking pose, and swap in the real response when it arrives. If a few hundred milliseconds of silence reads as "thinking", the experience changes a lot.
Three things to confirm before shipping
1. A cost model
Multiply players, sessions per month and calls per session to get monthly call volume. The numbers below are placeholders for illustration.
| Item | Placeholder value |
|---|---|
| Monthly active players | 10,000 |
| Sessions per player per month | 8 |
| Calls per session | 40 (after caching) |
| Monthly calls | 10,000 × 8 × 40 = 3,200,000 |
Multiply by the per-call price and set it beside revenue. The price depends on the model and on input and output length, so I haven't written a figure here. Check your chosen model's current pricing page.
2. Degradation when the model is down
As an indie developer who has run store apps for years, I've learned that every outside service has its bad days, and ad or billing SDKs taught me to design the fallback before the feature. The same applies here: there will be days when the model side is unavailable. Without a path to canned lines, players can only conclude the game is broken. Build in "bridge returns 504, show a canned line" from the start.
3. Platform policies
Steam, the console stores and the mobile stores keep updating their rules on generative-AI content and on sending player input to external services. Read each platform's latest policy directly, close to release.
Closing
In-game agents for UE5 are less about NPCs becoming magically smart and more about a series of design decisions: where to wait, where to give up, and where to put a human eye.
Start with Pattern B and a single NPC, and log only the response time and the number of timeouts on the bridge. Those two numbers alone will tell you whether to lean on caching or write more canned lines.
For related reading, see the Antigravity × Unreal Engine 5 guide.