• 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:
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...

I would make the argument that having an AI properly combine its forces like a player would to smash your defenses and take its objective may be frustrating for a player in the moment, but more in the sense that the player has not planned well enough to counter in that instance, or takes a hit in one area in order to prioritise some other goal. Frustration at a loss or tradeoff and entertainment are not mutually exclusive. You want to give people a compelling puzzle to solve, not a cow clicker which is honestly where the AI is at in the current build - it just cannot keep up in any meaningful way. Stellaris is at it most entertaining when the AI can give you a good fight in addition to the narrative stuff because interesting strategic, tactical and management choice flow from those interactions.

What is really deflating (not entertaining) is having the AI send its forces piecemeal into a grinder I have prepared because it couldn't simply combine all its reources into an effective stack that could actually do some damage. I may get a junk food high of constantly shitting on my enemy, but a longer term and more fullfilling satisfaction of actually using my brain is lost.
 
Last edited:
The main issue of the AI is its inability to destroy useless or harmful assets.
even with to old AI if I take control of one random country and destroy some no longer needed districts in 2240 it will defeat all it's neighbours 30 years later.
It was stated that it can do this now.
 
So performance improvements, military AND economic AI improvements. And long awaited Diplomacy expansion. Could be the "Jesus" patch if it actually comes out working well. Also I wonder if all that code that lets you see what the AI is planning might be used for Espionage down the road. Could be fun.
 
And long awaited Diplomacy expansion.
Keep in mind, diplomacy is not changing in any significant fashion. We'll still be able to bribe the AI, opinion will still polarize, and the galaxy will still solidify into motionless blocks.
 
Thanks for the quick reply!

Would it be possible to make it consider the effect of unfulfilled pop jobs, like calculating whether the pop jobs would reach its target once fulfilled, so better resettle some pops / prioritize growth? Or would that be too costly or finicky for the AI to calculate and take into consideration?

***********************************************************

Hmmmmmmmmmmmmm, it could probably do that, or at least try to approximate it. That's a good improvement suggestion, thank you!

I suppose you already have the numbers represented as "X number of unfilled job slots". It might be possible to add a check in to have the AI detect a severe lack of pops due to an event such as purging or bombardment, and prioritize resettling excess pops, or even pushing for faster growth there. That could be a simple way for the AI to fix it's planet without resorting to the complicated calculations necessary to see what jobs it needs to fill. because theoretically, the planets were set up well already, and they just need jobs to be worked.

Once they've restored the population, i'm sure the new system can trigger building replacements or demolishing to rework it's economic focus from it's worlds if it wants to.
 
I cannot tell you how happy I am to hear that the Military AI is getting such attention. To me, it has been by far the weakest part of the AI and weakened the whole game as a whole. Back in 2.3 I quit Stellaris because of it. I came back recently in 2.5 and the AI is definitely better. What you said about 2.6 so far sounds great.

You know of course the AI of any single-player game like this is everything. If it turns bad the game is is done. No fancy mechanics, graphics sounds, whatever will save its playability. I hope you guys test 2.6 real good before it comes out!!!
 
In Operations Research (the science of optimisation) you get around the general issue you describe by using a value which is practically infinite. A cost which is prohibitively high, a value whichis excessively high.

E.g. if all other weights are 1, then 10,000 should do the trick.

In the practical gaming context, a target of 10,000 alloys would encourage the AI to produce as much as it possibly could.

I think the issue here is that it would override all the other economic objectives, because the weight put on achieving each one scales based on how short you are to the target level. So if you had a super-high target level of alloy production, the AI would focus on that even if it was critically short on food or energy, because it is so far away from meeting the target level of alloys.

This becomes more problematic because it's not clear exactly how much value 1 alloy has, compared to say 1 unity or 1 research - indeed, that would shift situationally.
 
This is good. I hope it continues, and more of the AI gets reworked, but this is an excellent start. Combined with the performance improvements, this has convinced me to buy the next expansion, something I was wavering on. (I have bought every expansion except Lithovores, but didn't buy that because of broken end game content, AI issues and performance issues.)

As an aside, I'm a little concerned the change to building precincts may make criminal syndicates unplayable. It's pretty easy to crush crime.
 
For the military AI, I hope it is taking distance into account when making decisions about what target to attack. It would randomly path out 4 year trips to attack space stations in the rear of the enemy territory, which is not optimal.

And I really hope it pays some attention to where its fleets need to be before it declares war on someone. I've seen the AI declare war on another AI when all of its fleets were well over a year from the border where the actual conflict was going to take place, and end up losing because of it.
 
This Dev Diary is finally the one worthy of my first second forum post. I've logged about 1500 hours with Stellaris and been here since 1.0, generally keeping an eye on the forums and dabbling a bit with my own mods.

I haven't played as much lately, and when Federations was first announced, I mostly shrugged as it seemed like interesting features that wouldn't, in the end, add much depth. I only play SP, and while the GC sounded nice (especially on a larger map with plenty of other empires), what's the point when all AI are pathetic (and probably then laughably low DW) by 2300? Juggernaut? Yay! Another cool ship, but since the game grinds to a halt by the time I have a colossus, will I get to use it? Performance and AI are hands down the reasons not to play Stellaris/2.5.

That all said, the performance DD made me think maybe 2.6 was on the right track. And this one? Well, kudos to @sidestep and @MatRopert. Really appreciate both of them taking the time to stick around and answer all the questions that they did, and obviously all the effort they've put into the AI. Still other areas that could use some love, but this seems like a massive step in the right direction. You have me excited to actually put more time (and yes, because of these past two DD, DLC $$$) into my favorite Paradox title.

Edit: :oops: 2nd...
 
That all said, the performance DD made me think maybe 2.6 was on the right track. And this one? Well, kudos to @sidestep and @MatRopert. Really appreciate both of them taking the time to stick around and answer all the questions that they did, and obviously all the effort they've put into the AI. Still other areas that could use some love, but this seems like a massive step in the right direction. You have me excited to actually put more time (and yes, because of these past two DD, DLC $$$) into my favorite Paradox title.

I'm in the same boat. New features, yes please. AI and performance are the bedrock of this. I got 1k hours and I just cannot bring myself to play the game in the current state, and if that were to continue I would stop buying new content. 2.6 + Has me excited alongside the new content and for the future now.

Big kudos to the hard work of the devs.
 
@sidestep, @MatRopert thank you for those great dev diaries and for sticking around to answer questions! Will you be continue to work on the Stellaris AI, or do you have to move on to other projects?

Also regarding The Plan, will the goals for the AI be adjusted according to difficulty levels? An AI with 200% income bonus will reach those goals much quicker, so I think the goals should be higher, right? Likewise an AI with -25% income might need lower goals, also to go a bit easier on new players. Is this currently implemented or are you planning to implement something like this? It would be a great way to make the difficulty slider more meaningful.
 
Last edited:
"The Contingency will systematically try to stop the biggest threat to the galaxy, until nothing remains" - you mean what...they kill themselves on arrival?
 
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).
Funny that you mention EUIV, because it's not only the game I play most but it will also get better Economy-AI in 1.30. However, if I got that correctly, EU4 economy AI will have a rather different design approach from stellaris economy AI, e.g. to my knowledge it will not have any "plans". What I would like to know is
  • How much cross-semination of ideas between games do you perceive to be doable?
  • What are the reason you are doing things differently between EU4 and Stellaris?
  • Will any of the lessons learned while working on Stellaris AI feed into improving EU4 AI?
  • And of course: which AI do you consider more competent at the moment - Stellaris or EU4?
Thanks!
 
Don't get me wrong, I think the work you've done is absolutely solid. But really you had to make experiments to reach this conclusion? Doomstacking is the only sensible strategy in Stellaris, even if the general public on this forums consider this statement to be an offence against the community.
Well that's the thing, how fun is it to play against an AI that will always curb stomp you? It's sometimes easier to make an AI that is efficient rather than entertaining (take tic-tac-toe as an extreme, it's trivial to make one that cannot loose).
That's why we'll be monitoring the feedback...
I'd like to suggest this info is available by default if you select the fleet of an AI you're allied with.
That UI is a bit too unpolished to be used as a game feature, but we'll keep in mind that you guys would like to see more of what your AI allies are thinking at a given moment.