• 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 cannot shake the feeling that you guys have not read each other's drafts.
Economy has realised, that good AI needs to see the bigger picture, but military is still trying to manage it on per objective basis.

Few thoughts on military first.
It is useful to imagine the extremes of difficulty settings. Like how good this will be on GA and on Ensign.
On GA (whatever the highest difficulty is, you may add 5 new levels or not even use the toughest version of AI in game at all, but AI has to allow level of competence human cannot compete with) no scaling the war looks like this:
1. mass fleets in doomstack
2. defeat enemy's main fleet in the border fight, if the enemy is stupid, it will attack your border fortress giving you the advantage of additional firepower and immediately available spot for repairs
3. proceed to take enemy's capital system, defeat the retreat jumped fleet when it arrives
4. take other star bases, primarily 6 slots with shipyards
5. after the enemy has lost the ability to reinforce, take claimed systems
6. take everything else until status quo becomes available, if it is war for claims
7. continue to take literally everything if you need a total victory

From there you can use regressing difficulty levels to limit percentage of navcap in doomstack, on lowest difficulties you can limit them to be 80-50-30% of player's navcap. Remove the ability to perform coup-de-grace (pardon me French).

AI has to decide before the war breaks out, what is it fighting for.
High difficulty AI will aim to defeat enemy fleet and get most populated world or primary ecumenopolis via claim.
Mid level AI will aim to defeat enemy fleet, take out enemy shipyards, take couple of border systems by claims and wait for peace.
Easy level AI will be doing what your AI is doing: splitting and merging fleets, wasting time on regroups, deciding what to do next after previous objective was completed, reacting to what is being done to it and generally using ad hoc decisions.
 
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!
 
Also, another thought about plans - if you were to allow a player to devise a plan for their own empire, UI and all, and then have economy AI assisting with it, you'd also be theoretically able to gather metrics on how different players plan and potentially use that information to further refine AI planning in the future.
 
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).

@MatRopert It's good to have confirmation the AI works this way (I'd suspected as such). One thing that strikes me is how similar this sounds - on paper - to the victory point system from HOI4.
  • Have any special values been assigned to certain systems?
    • E.g. will a system be scored higher if its a Homeworld, or a sector capital? Or if it has a megastructure in it.
  • Additionally, which AI module controls claims decisions? The military one? Does it also use this scoring system?
    • I've seen the AI make some ... odd claims - often cutting its own space off in the process
      • (e.g. I'll have a forge world, 1 system away from Blorg space, and there's a starbase of mine between me and the Blorg, but the blorg wont also claim the starbase, so, if they won the war for my forge world it'd lead to them owning a cut-off system which would drive up their sprawl/drive down empire unity?
  • 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?
    • That way we can see what our AI allies are thinking (in federations) and figure out how to work with them - without turning on the Debug UI.
    • Or an option to add an attack/defend/rally "Ping" command to system X to increase its value to allied AI to force them to attack it/protect it
      • (Vassals and federal allies have long been considered crap because we cant really direct them to attack or defend a given system).
  • 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?)
This all sounds very fancy-like and good, but now for the real question; does the economic AI perform better overall? Well...yeah!

In our tests we have seen much more robust AI economies and a better handling of the economy overall. And I’m really happy with it! Of course this wasn’t all me, I had lots of help from QA and other devs, and am very thankful for that because without them this wouldn’t have been nearly as good. Now of course, with the release of Federations closing in I would love to see what you ( the community ) manage to do with this and how you will manage to mod this into oblivion ;)

@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?
More generally, on the crisis - has purging been touched at all?
  • The Prethoryn just use generic extermination purges, and this is slow AF - it can take them Centuries(!) to wipe out a highly populated world.
  • I also remember reading someone observed constructors have pathing/allocation problems for the prethoryn too, which can also break them, has this been covered by moving them to the "Generic" AI package?
And whilst not related to the economy or AI directly, could we please get an automatic suspension for Assembled pops? The AI does this for robots, and for Biopops they stop growing at a multiple of the housing cap, but for humans we need to manually shut down assemblers, its micro intensive and not fun to constantly shuffle robots around.
 
Last edited:
@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.
 
Of course I knew that SPECIFICALLY you would ask ;)

Yeah, you can add any modded stuff to the existing plans, or just change them out completely if you want. The system does not rely on any static data that way and does not require the vanilla mods to function or anything.

Fantastic. Thank you sir.
 
This is actually a uhhh...really, really good post. It's by far the best developer diary I can remember reading pretty much...ever. It's got meaty information to back up the claims, and I feel like I understand the rationale behind the decisions present.
EDIT: Reading through the replies my enthusiasm is tempered slightly: I just hope the AI is actually good, this time around. I mean of course it's easy to state we've fixed the problems and then not offer any real evidence, but this dev diary seems to be at least trying to convince me that the problem is solved, so it's more than other ones I have read recently. Still, looks promising.
 
Right now there exists no such specific plans, BUT the system is setup so that you can do that very easily. You could for example make a general "high science" plan and weight it higher for technocracy empires. Or make a Technocracy specific plan that is limited to them only via the potential = {} trigger!

Is AI personality type a valid condition in the potential scope?
 
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- .

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.

This is the beauty of the planning system as I understand it - it compares the current production surplus (after all upkeeps are deducted) to The Plan. It then queues up construction, which is accounted for in future evaluations. The one question with regards to this that remains standing, is whether the AI will demolish/rebuild districts if that is the optimal course of action (sudden synth ascension, food no longer needed, scrap almost all farms in favor of other things or just reducing sprawl if the pops have another job to do)

With regards to point 3 that you're raising - I'd assume that yes, the AI accounts for a dip in basic resource production when building advanced production, or possibly only does this when there is unemployment or bad clerks. But I agree, clarification on this would be welcome.
 
Sounds promising. How much does the economic plan react to the diplomacy and military ministers?

For example, diplo says lets kill the geckos, military says we need loads of new ships for that, so will economy then bump prioritisation off minerals and alloys to quickly grow the fleet?
 
You said the economic performance is noticeably better. Is this evident at the rate at which other empires become inferior to you? As it is you don't need even need to look at AI planets to see how bad it is doing. In fact it can be better to spare oneself that horror. But one you make it out of the early game, you just need to look at the diplomacy screen to see that everyone else is soon "inferior" and "pathetic". Even without trying much. Sure, a good human player will always outperform the AI in the long run, but what I expect to see here is that it takes longer and that the AI sometimes can be a serious opponent at least into the mid game. Things like wars, federations and galactic communities are pointless when you are effortlessly dominating everyone.

As you say, a human player will always beat the AI, we can think in ways that the AI just cant. The goal was to make the AI more "competitive" ( whatever that means ) and for a longer time. The results weve been seeing is that the AI economy scales much better and does not stagnate in the same way it used to. Also on higher difficulties it can be quite dangerous beyond mid-late game :)
 
I'm very curious how much of a performance increase we can see from cutting down on the if/then statements that the AI uses for its decision making. We had the dev diary speaking about performance improvements not long ago; was that before or after this new AI was implemented?

Also hopefully the AI will be 'smart' enough not to put down multiple police stations on their planets. Playing crime syndicates was very underwhelming with that behaviour.
The AI is no longer capped at one police station per planet, if a planet has crime and nothing else crazy important is needed then they can build several stations.
If you do crime, you will do time!
 
This is the beauty of the planning system as I understand it - it compares the current production surplus (after all upkeeps are deducted) to The Plan. It then queues up construction, which is accounted for in future evaluations. The one question with regards to this that remains standing, is whether the AI will demolish/rebuild districts if that is the optimal course of action (sudden synth ascension, food no longer needed, scrap almost all farms in favor of other things or just reducing sprawl if the pops have another job to do)

With regards to point 3 that you're raising - I'd assume that yes, the AI accounts for a dip in basic resource production when building advanced production, or possibly only does this when there is unemployment or bad clerks. But I agree, clarification on this would be welcome.
I mean it would be a fairly huge oversight if the AI didn't accomodate for actual pop needs, as opposed to preset pop needs it thinks it has, so I doubt this is an issue
 
As you say, a human player will always beat the AI, we can think in ways that the AI just cant. The goal was to make the AI more "competitive" ( whatever that means ) and for a longer time. The results weve been seeing is that the AI economy scales much better and does not stagnate in the same way it used to. Also on higher difficulties it can be quite dangerous beyond mid-late game :)
So in other words, the AI is more competitive to such an extent that it needed nerfing?
 
So in other words, the AI is more competitive to such an extent that it needed nerfing?
Well, higher difficulties just give the AI more resources to work with, and the player correspondingly less. The idea of a good AI is to prevent you from cheesing it at the high levels rather than making it difficult on "normal". Normal should, after all, be only moderately difficult. The problem is recently the AI just wasn't progressing *at all*
 
Well, higher difficulties just give the AI more resources to work with, and the player correspondingly less. The idea of a good AI is to prevent you from cheesing it at the high levels rather than making it difficult on "normal". Normal should, after all, be only moderately difficult.
I know :)

The point of the question is, given that that is a band-aid solution - did improving the AI improve it so it doesn't actually need those band-aid solutions.
 
This is the dev diary I've been waiting for for a long time now. Thank you very much. At a first glance it looks like there have been some huge improvements on the economic side I am very much looking forward to see in action. It seems that a lot of work has gone into the AI plans and I have no doubt that they are a sound basis to develop actually working AI empires.

However I can already see a couple problems coming:

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.
1. The triggers that check if you need food/consumer goods checks this, so it should not be an issue, it will switch plans!
2. Planetary plans would be really nice, and the planet automation and planed designations could be tied more into the economic AI, but as always: can't do everything :(
3. The AI will not build buildings if there are lots of free jobs on a planet, so there shouldnt be any massive shifts in jobs like this, it will however fluctuate a bit but then it can favorite jobs that are more critical
4. The AI will only plan for buildings that it needs and then wait until construction queues are empty before building more stuff, so this should be less of an issue now.