• We have updated our Community Code of Conduct. Please read through the new rules for the forum that are an integral part of Paradox Interactive’s User Agreement.

Stellaris Dev Diary #172 - Reworking the AI

Bonjour everyone, it’s the French Paradox speaking! For those who don’t know me, I’ve joined the Stellaris team this December after a year and a half as a programmer on Europa Universalis IV.

Today, we are gonna talk about AI.

pasted image 0.png

A good introduction for those new to the field

Fifty Shades of AI
There are several AI modules in Stellaris. For historical reasons we call them “ministers” as each one is supposed to handle a specific role in an AI empire.

There are 3 broad kinds:
  • The AI foreign minister handles diplomacy, federations, galactic community, peace deals and the like
  • The AI interior minister is in charge of the economy. He keeps budgets and order constructions, both civil and military.
  • The AI military minister is in command of all troops and military fleets, and also responsible for laying out strategic plans when at war.
For each of those ministries there are different “ministers” there are several options that can be selected for every empire in the game. All of those have generic one which behaves more or less like we’d expect a player to and is used for most AI empires. Then we have a bunch of specialized ones for special tags such as space monsters, fallen empires, crisis, marauders and the like.

As almost everything in our games, AI is configurable in script for our modders, although I’m not exactly sure what would happen if you assigned a space monster military AI to the caravaneers ;)

In guise of a welcoming gift when I joined the team, I was tasked with reworking the military one...

The Military AI
To give you a little bit of background, there were several generations of military AIs in Stellaris. The generic one (used by most “classic” empires) was redone by the great @sidestep last year, while the more specialized ones (crisis, space monsters) have kept close to what they were on release. In the midst of the sad and dark swedish winter, I managed to bring some improvements that I’ll showcase today.

First of all, I worked on visualization to help us debug how the AI “thinks”. Funny thing is, it already made it look “better” to audiences even if it didn’t actually change any behaviour. It’s actually something that’s been observed in video games: a good AI tells you what it does, which makes it look smarter. One of my favourite examples of that would be the enemies in FEAR.

So by typing 'debug_ai' in the console and observing an AI empire, you can see what it has in mind:

pasted image 0 (1).png

“I don't even see the code. All I see is blonde, brunette, redhead. Hey uh, you want a drink?”

As a simple analogy, imagine that the AI has a war minister that looks at the big picture and rates every potential target, a general staff who assign fleets to some of those objectives, and then admirals who try to lead those fleets on a tactical level to achieve those objectives.

The skulls on top of each system shows military objectives that the AI is considering (the war minister). Red ones are the ones they selected and committed some fleets to, while green ones are other options they haven’t retained for now. Finally for each individual fleet, in those task forces, you see what they are doing at present.

In our screenshot example, the AI decided that taking Tiralam was the most important objective with a score of 4500, and that they estimated that at least 11.2k fleet power was needed to accomplish this. They committed the Kilik Armada, the Jinki-Ki-Ti Armada and the the Grekki Armada to this. Since it makes little tactical sense to attack in a dispersed formation, the AI issued orders to regroup in Broon’s Singularity before proceeding on the attack (something we improved in this patch).

For convenience, the summary is also visible in the outliner:

pasted image 0 (2).png

As seen from the other side of that war

That change alone allowed us to see where the AI was a bit weak and also made evident a few bugs in the production AI that we promptly fixed. A funny one was that in some cases a fleet would end up assigned to two different fleet groups, nicely simulating two admirals fighting over command of a fleet and issuing contradictory orders every day.

Crisis AI
The next step was to rewrite the various crisis to use the generic AI, so that any effort spent on making better would benefit all. In patch 2.6 the specific AI of the Khan, the Prethoryn, the Unbidden and the Contingency will use the same AI as the “standard” empires, with a few twists to still retain their personality.

Without spoiling every secret, here’s a few ideas:
  • The Khan doesn’t really believe in defense and will try to beat the closest systems into submission
  • The Prethoryn will swarm in every direction they can
  • The Contingency will systematically try to stop the biggest threat to the galaxy, until nothing remains
  • The Unbidden will be harder to predict, but there’s reason behind their alien way of acting.
One of the biggest challenges we faced was assigning fleets to objectives. Matching X fleets with Y out of Z objectives is not an easy task. Do we try to accomplish as many objectives as we can at the risk of spreading too thin or accomplishing nothing of value? Should we instead focus on the most valuable target and possibly end up in a big fight that we could have avoided? How often should we reconsider our options?

The current version solves this by putting a fleet power value on every target, then grabbing fleets by order of priority until it either has enough to accomplish the objective, or go over the next one. This approach showed its limits when we plugged the crisis AI into it, as it relies a lot on the size of available fleets (it doesn’t know how to split them, it can only merge them).

Teaching the AI how to split fleets proved quite interesting:

pasted image 0 (3).png

What shall we do with this knowledge?

It took several tries to find a good balance, as the AI tended to split too much (most objectives don’t call for that much fleet power, unless you’re fighting your enemy main fleet). In the end, after trying some complex strategies such as keeping statistics on accomplished objectives and deriving a good target number from that, a simpler approach turned out more efficient: put all the nation’s offensive fleet power into one stack, and then consider splitting in 2,3 or more depending on how confident the AI feels about its military power versus its foes.

Knowing some of you like to mod our AI, here’s some new defines you may want to play with once all that hits the shelves.

Code:
# Objective values
HORDE_INVASION_PLANNING_DEPTH = 5    # How far out does the Horde AI looks for invasion targets (in system hops)
SWARM_INVASION_PLANNING_DEPTH = 5    # How far out does the Swarm AI looks for invasion targets (in system hops)
SWARM_POP_TARGET_MULT = 1.0            # Extra target scoring for swarm (multiplied by number of edible pop on the planet)
CONTINGENCY_MEGASTRUCTURE_EXTRA_VALUE = 4    # How attractive are megastructures to the Contingency (added to the base value of 1)
UNBIDDEN_PORTAL_EXTRA_VALUE = 20            # How much does the Unbidden want to defend their portal (compared to base value of 1)
UNBIDDEN_BYPASSES_EXTRA_VALUE = 4            # How attractive are bypasses to the Unbidden (added to the base value of 1)
UNBIDDEN_RIVALS_EXTRA_VALUE = 10            # Extra target scoring for rival invaders (Aberrant and Vehement)
UNBIDDEN_TARGET_EXTRA_VALUE = 10            # Extra target scoring for randomly chosen nemesis
UNBIDDEN_PSIONIC_CONQUER_DESIRE = 20        # Extra weight added to psionic empires when rolling a nemesis (base 1 + number of owned bypasses)
UNBIDDEN_CHOSEN_ONE_CONQUER_DESIRE = 50        # Extra weight added to empire lead by the chosen one when rolling a nemesis (base 1 + number of owned bypasses)

# Fleet sizing
OFFENSE_VS_DEFENSE_STRATEGY_ALLOTMENT = 0.75 # How much of its fleet power should a country with 1.0 aggressiveness should try to commit to offensive missions
AVERAGE_FLEET_SIZE_FACTOR    = 0.05            # Ballpark estimate of the minimum size a fleet should be in relation to total fleet power
OWN_FLEET_POWER_FACTOR = 1.0                # How much does AI count its own fleet power when evaluating forces
ALLY_FLEET_POWER_FACTOR = 0.5                # How much does AI count ally fleet power when evaluating forces
ENEMY_FLEET_POWER_FACTOR = 1.0                # How much does AI count enemy fleet power when evaluating forces
FLEET_SUPERIORITY_FACTOR = 1.5                # How stronger should the AI be before it starts considering splitting fleets (fleet count = relative strength / this factor)
CRISIS_FLEET_SUPERIORITY_FACTOR = 1.0        # Same as previous but will be compared to the strongest foe in the universe

Most of those changes will be delivered in the patch coming alongside the Federations release (2.6.0), but not all. As you may imagine, changes to the military AI are quite impactful and we don’t want to release the changes without enough testing, so some of them will be delivered in the first support patch (2.6.1).

And with that, I shall leave you with @sidestep one last time.
 
Last edited by a moderator:
  • 2Like
Reactions:
I am also confused by this

Paradox forums don't have nested quotes.

Sidestep said: They won't ever stop growing/building pops, it just becomes less of a priority. In later plans that number is of course increased. See it more as something for the AI to work towards actively than a hard cutoff :)
I said: The current AI does however? So what did you change?
Sidestep said: Oh you mean the planetary decision to stop growing pops? Well, I haven't actually touched any of that so, they will probably still do that if they cant build more buildings, unless someone else changed that. Sorry for the confusion!
 
You missed the question.

Planet A has zero free specialist jobs and 20 worker jobs.

The AI upgrades an alloy foundry. Now there are 3 free specialist jobs.

The pop allocation system will automatically upgrade 3 miners to be specialists.

Does the AI know that this will occur, and will it plan ahead?

Particularly a problem with Ecumenopolis, where 10 clerks may all be promoted to specialists.
Ah, sorry. No, the AI cannot plan ahead for this, which is a technical limitation unfortunately, you cannot truly beforehand know what jobs pops will switch to since all of those weights are scripted all over the place. You can only really know by doing those calculations and pre-calculating that when creating a build plan would be WAAAAAY too expensive performance wise :(
 
Districts also have destroy trigger so yes, should also work. I have not made any changes to ecumenopolis-building though so I honestly don't know, it was outside the scope of this particular rework.

No, they will never just "stop", they will try to find another plan and if they don't find one they will fallback to the old system and just keep building stuff anyways.

Thanks for the clarification!

I assume that when it defaults to the old plans, it won't try to get rid of buildings if it say had more than amount of that building (like foundries) that were allowed in the old plans? Rather, just when its expanding beyond the plan with the old-plan defaults it will just limit what it builds to those restrictions until a new plan becomes valid?
 
Can any of the plan values be changed in-game, for an ongoing campaign (via events or decisions)? I understand the goal would be to have several plans for different occasions, and it is a significant improvement over the old system, however, I see a missed opportunity to actually incorporate the plan system into the gameplay. I think it would be nice for the player to devise his own plan (on its own dedicated tab/GUI in-game), see how it plays out and tweak it if necessary. At least it would be a good way of reducing micromanagement for those who want it.
Perhaps this is technically quite difficult to implement, but it could be something worth considering in the future?

Very nice DD and thank you for talking about the inner workings of the AI!
Unfortunately not, that would be nice to do but I wanted to keep the plans as simple as possible for now and focus more on how the AI tries to reach those planned goals.
 
What I want to know is what was stopping the AI from colonising all those habitats?
The AI treats building a habitat the same as building a megastructure. Once the habitat is there, it should consider it a colonization opportunity. (Whenever they get around to it.)

We did end up adding a check so they won't build any more habitats in a system that already has an uncolonized one.
 
@sidestep This is great news! and it looks like a much less messy system! I have 3 questions:
  • How does the new economic AI / Economic plan factor in the galactic market or internal market?
    • Does the AI aim to be totally self sufficient now,
    • Or will it happily just buy in Food, or Volatile gasses (for example), for a long term, instead of laying down refinery worlds.
  • Have there been any changes to the slave market/how decisions there will work?
    • The Slave market is quite binary (depending on the empires in the galaxy at the time) - it'll either be mostly empty with slaves being immediately bought up, or itll have hundreds of slaves up for sale (to the point that the slave market UI literally lags out).
  • After something like synthetic ascension, will the AI be loaded on to a new economic plan (i.e. no more building farms, weight generators very highly).
    • More generally, will food/mineral/energy weights shift dynamically if an empire has more Bio Pops/Lithoid Pops/Robo pops in it?
* The AI does aim to be self-sufficient but it will buy resources if needed, more specifically it will allow a deficit of for example Volatile Motes to upgrade an Alloy Foundry if it can buy motes without issue.
* I did not touch the slave market.
* If the AI starts/stops needing a certain resource they will switch plans, yes.
 
Ah, sorry. No, the AI cannot plan ahead for this, which is a technical limitation unfortunately, you cannot truly beforehand know what jobs pops will switch to since all of those weights are scripted all over the place. You can only really know by doing those calculations and pre-calculating that when creating a build plan would be WAAAAAY too expensive performance wise :(

It would be a reasonable simplification to do what a sane player does - ensure that any job deficit resulting from pop promotion doesn't cripple your economy, i.e. that the "focus" goals are exceeded by x amount of output before doing things that trigger a pop promotion. Edit: with a special consideration for clerks in regular empires, since clerks are the buffer job in almost all cases that aren't merchant-focused.
 
@sidestep My apologies if thi is considered spamming and I hate to re-ask, but as you're currently active in this thread I'm trying anyway. Can I get a response to these percieved issues from a couple pages ago?:

1. What happens to a lithoid empire if it aquires a non-lithoid minority? Do the normal pops starve because the AI remains in a non-food-producing plan? Or does the AI switch to a plan that does produce a food surplus but is completely inadequate to produce the mineral surplus the lithoid population requires? Similar problems I can see for synthetically ascended empires while assimilating new pops, normal empires conquering lithoid planets and any machine empire with organic pops -pampered, enslaved or otherwise- .

2. I hate that there still are no planetary plans. Sure the AI can see a need for an alloy foundry and order one one the planet most suited, but the human player is still stuck with dozens of planets that the AI can't be trusted to take care of when we have no ability to assign an AI-plan specifically to a single world.

3. How well does the AI handle big numbers of pops switching jobs? If it upgrades an Alloy foundry and then all the former mining workers flock to the new improved jobs there is a sudden demand in minerals and CGs as well as a sudden drop in mineral production.

4.Does the AI take buildings under construction into account? Otherwise a mineral deficit will cause minign districts to be ordered en masse until the first ones are actually finished.
I think I answered this but im bad at forums so ill do it again, quickly this time.
1. They will switch plan and produce food etc.
2. No planet-specific plans no, not enough time to rework together with this
3. They will still switch, did not touch the job system directly
 
So the answer is no, then? I mean I haven't played in a while and I'm not sure if this is actually an issue
Habitat spam is an issue. The AI builds a whole bunch of habitats that it then doesn't colonise because of a bug which I assume is fixed (because Sidestep identified that it was a bug)

I feel Habitats are best used as mining, research or energy stations. Your experience may vary. I think Trade and Unity habitats are a waste of alloys and influence.

Basically in my heuristic, if a Habitat is going to be built it should be mining, reserach or energy, and I consider trade/unity habitats worthless. I assume that the AI knows that colonising lots of trade/unity habitats is useless and so rationally doesn't' do it. But because its building isn't planned, it still builds lots of megastructures it doesn't need.
 
So in other words, the AI is more competitive to such an extent that it needed nerfing?
Haha, I will stick to no such claims.
I like all of the informations in the DD. Will anything of this influence the sector AI or is this a completely different field? And what about special goals like megastructures. Are they part of The Plan or are they handled by other "ministries" or in a totally different way?
You basically hit the nail on the head here, the sector AI is something completely different in code as well as megastructures. Different ministers indeed and a different system.
 
Last edited:
Would it be possible to do something like "if all plans fulfilled, adjust building weights for basic construction so that alloys, science and unity keep getting spammed in this designated proportion to each other"?
This was actually brought up as one possible improvement when I presented it to some other devs, would definitely be super-nice to have but is not supported right now.
 
I mean, as players what we probably often do, when you fulfill your plan; you just build Research/Alloys and construct a bigger fleet.
So late game plan+ would just be the classic late game plan but with like +100k income in sciences and +10k alloys (maybe Unity also), no?
You could script early/mid/lategame+ plans, so that if you fulfill the initial plan the AI would then move on to the earlygame+ plan that just has the same goals except more in science/alloys. Then when you hit midgame you would start the midgame plan and so on :)
 
Thanks for the clarification!

I assume that when it defaults to the old plans, it won't try to get rid of buildings if it say had more than amount of that building (like foundries) that were allowed in the old plans? Rather, just when its expanding beyond the plan with the old-plan defaults it will just limit what it builds to those restrictions until a new plan becomes valid?
No, the old scripts usually just disallow the AI from building more than a certain number of a building or weight them much lower, it does not destroy buildings if it has more than that. For that to happen the destroy = {} trigger would need to be triggered.
 
It would be a reasonable simplification to do what a sane player does - ensure that any job deficit resulting from pop promotion doesn't cripple your economy, i.e. that the "focus" goals are exceeded by x amount of output before doing things that trigger a pop promotion. Edit: with a special consideration for clerks in regular empires, since clerks are the buffer job in almost all cases that aren't merchant-focused.
Sure, good point, but we also don't know which jobs will be left when pops promote. They could leave 4 mineral jobs behind or 4 farming jobs behind so it's all just guesswork at that point. As a human you can do that guesswork and kind of "wing it" but the AI just can't think that way, it needs numbers and that means expensive calculations and then we're back to the original issue unfortunately
 
Could you elaborate on what changes will come in 2.6.1? Will we miss out on a lot in the mean time or is it technical stuff?
As any minor patch, 2.6.1 will be about bugfixes. The military AI changes in it were mostly done in reaction to behaviours observed in the 2.6.0 release candidate that couldn't be added in time. Speaking of which, maybe one day we should elaborate a bit on our release process and why we sometime ship with bugs that are already known and fixed internally (spoiler: it's not _only_ because we are evil).
As far as my observations go in over 2500 hours of this game (probably more than your average QA :)), the worst enemy of AI fleets is subsequent reinforcements.

A meatbag player tends to doomstack always (human nature, as well generic military strategy - hit it hard, hit where it hurts, instead of matching forces hit with overwhelming advantage to reduce your casualties).
That's the conclusion I came to after trying a bunch of various "clever" fleet divisions. At the end of the day, making sure each of your stacks can safely take anything your enemy can throw at you is the safest bet.
But maybe not the most entertaining one? Something I'll definitely monitor post release (but is hard to measure), how is the AI fun to play against...
Have any special values been assigned to certain systems?
There are several factors yes. The AI considers things like "is this a good chokepoint?", "is this a claim?" and "is this fleet more of a distraction than a real danger?".
Additionally, which AI module controls claims decisions? The military one? Does it also use this scoring system?
They both use a scoring system but it's not the same one. A system may be important to take to win the war, but not so much as a conquest goal.
Would the team consider adding these AI values (simplified like a 4500 score system could have "✦45" next to it in war) to the normal UI for humans?
This is a thought that has been running in my head for quite some time. For example on EU4 there's a mapmode hidden somewhere that tells you which provinces each nation wants (even if not how much/why it wants it) but it's not super usable. If we can figure out a good UX design for it... maybe? ;)
Also, how do AIs value neutral systems (e.g. Sanctuary, or marauder systems or systems filled with space amoeba etc) - they leave them undisturbed well into the late 2200s sometimes. Would there be some special evaluation to attack those too? (as they're neutral I assume usual wartime calculations don't apply?)
Funny you ask, this was a bug in the beta that we fixed. The ignored systems outside of its borders and the enemies (if at war), which made it super shy and unwilling to disturb even the smallest spaceborn alien next door. Even the Priki-ti-ki could not hurt them (unless a military objective made them cross the system by chance).
 
If I understood correctly, the AI should be able to use the market in cases where it is hit with a deficit it needs to fix. Does it realize when a deficit is caused by a loss of pops working on it, rather than a lack of buildings or districts and it needs to either shuffle pops around or just weather the storm? For example, if an ecumenopolis constructs a new districts and 10 clerks disappear, leaving it with badly lacking amenities and trade value, does it realize that it doesn't need to construct anything new, but instead that it needs to get some new pops working there?
 
This is a thought that has been running in my head for quite some time. For example on EU4 there's a mapmode hidden somewhere that tells you which provinces each nation wants (even if not how much/why it wants it) but it's not super usable. If we can figure out a good UX design for it... maybe? ;)
Interesting! I know map filters are scriptable in stellaris. Is there a specific modifier that can be called which will output the "Strategic value" of a system, for a given AI?
like click on empire X and it will shade each star in the galaxy (or within X jumps of their border, for performance) by the strategic value that AI has assigned, to each system?

Basically I'm imagining a per-empire heatmap of what they value/covet most.

This idea has drawbacks (can only see what 1 empire wants at a time) but it might be a good thing to test in a mod for now.

And glad to hear neutral systems will be ruthlessly purged by the AI now lol.
 
As any minor patch, 2.6.1 will be about bugfixes. The military AI changes in it were mostly done in reaction to behaviours observed in the 2.6.0 release candidate that couldn't be added in time. Speaking of which, maybe one day we should elaborate a bit on our release process and why we sometime ship with bugs that are already known and fixed internally (spoiler: it's not _only_ because we are evil).

That's the conclusion I came to after trying a bunch of various "clever" fleet divisions. At the end of the day, making sure each of your stacks can safely take anything your enemy can throw at you is the safest bet.
But maybe not the most entertaining one? Something I'll definitely monitor post release (but is hard to measure), how is the AI fun to play against...

There are several factors yes. The AI considers things like "is this a good chokepoint?", "is this a claim?" and "is this fleet more of a distraction than a real danger?".

They both use a scoring system but it's not the same one. A system may be important to take to win the war, but not so much as a conquest goal.

This is a thought that has been running in my head for quite some time. For example on EU4 there's a mapmode hidden somewhere that tells you which provinces each nation wants (even if not how much/why it wants it) but it's not super usable. If we can figure out a good UX design for it... maybe? ;)

Funny you ask, this was a bug in the beta that we fixed. The ignored systems outside of its borders and the enemies (if at war), which made it super shy and unwilling to disturb even the smallest spaceborn alien next door. Even the Priki-ti-ki could not hurt them (unless a military objective made them cross the system by chance).
Thank you for the reply!
Then I won't have to wait for 2.6.1 and can straight away jump into 2.6.
So technically the AI is feature complete (as of 2.6) and anything extra is tweaking values and fixing bugs. That is good to know!
 
If I understood correctly, the AI should be able to use the market in cases where it is hit with a deficit it needs to fix. Does it realize when a deficit is caused by a loss of pops working on it, rather than a lack of buildings or districts and it needs to either shuffle pops around or just weather the storm? For example, if an ecumenopolis constructs a new districts and 10 clerks disappear, leaving it with badly lacking amenities and trade value, does it realize that it doesn't need to construct anything new, but instead that it needs to get some new pops working there?
Unfortunately not, it doesn't really know why there is a deficit, only that there is. This is another one of those things that we humans are so good at understanding because we can make that logical "leap" and figure out what went wrong. The AI needs numbers and in this case the numbers just say -50 EC / month and so it tries to fix it. But job weights should be balanced such that the AI doesn't heap ALL pops into one type of job, avoiding this extreme case in the first place.

edit: also it wont build new buildings on planets with lots of free jobs, so at least it wont add to it
 
Last edited: