• 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:
Great stuff, the potential to simplify stuff is tremendous.

Will the plans tie in with specific Authority Types, i.e, Imperial plans differ from Authoritarian and Egalitarian ones? Or even at the Government Type level, i.e, Representative Democracy plans differ from Communal Parity ones?
They can! Since plans are scriptable :) but the default plans do not take any of this into account
 
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
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.
 
Just out of curiosity, what happens when the AI fulfills an economic plan? How do they decide what to build next - do they shift to the next plan? Also, can the plan shoot for "as high as possible"? One might imagine you want the late game AI to try to max out alloys, tech and unity, without a cap.
When the AI finishes a plan it will try to find another that it can take, if it cant find one it will just fallback to the planet-by-planet construction. They cant really shoot for "as high as possible" but that would be a nice improvement. For now I think the easiest way to do that is just to have a late game plan with impossibly high numbers in it that the AI can try to reach, haha.
 
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?
 
Current game rule - you can't build a habitat/megastructure in orbit around an object where another station is.

Now a Habitat can earn 200 minerals, whereas a really good Gas Giant can generate 12. So the AI should demolish the mining station to build a Habitat.

The problem in the current Stellaris is that it doesn't plan. It doesn't know that demolish Mining Station allows it to build a Habitat and earn more in the future. So demolish/rebuild probably won't do anything at all unless the AI is "thinking" a couple of steps ahead.

Likewise for Ecumenopolis.

The problem is not that the AI is getting rid of a building or station that is a net negative, it is the opportunity cost that matters.


The current AI does however? So what did you change?
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!
 
When the AI finishes a plan it will try to find another that it can take, if it cant find one it will just fallback to the planet-by-planet construction. They cant really shoot for "as high as possible" but that would be a nice improvement. For now I think the easiest way to do that is just to have a late game plan with impossibly high numbers in it that the AI can try to reach, haha.

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"?
 
I meant added "dynamically" : e.g. there is a secondary plan (a sub-plan) that does not invalidate the base one, but sets additional income goal for new resources and is activated upon researching tech. Or we need to overwrite existing plan / substitute it in its entirety with our own that includes these modded in resources.
Ah, no. That was actually an improvement brought up but I didn't have time to do that. You would have to write a new plan that contains those resources and trigger a switch.
 
When the AI finishes a plan it will try to find another that it can take, if it cant find one it will just fallback to the planet-by-planet construction. They cant really shoot for "as high as possible" but that would be a nice improvement. For now I think the easiest way to do that is just to have a late game plan with impossibly high numbers in it that the AI can try to reach, haha.

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?
 
More than arbitrary dates like ''early'', doesn't it make more sense to tie the economic plans the geopolitical situation? Like having a ''wide expansion'' plan that focuses on pop growth and minerals to build stuff if there is little danger and plenty of space, a 'tall expansion'' if there is little danger but few colonization options, or a ''military buildup'' plan that focuses on alloys if the AI predicts an war in the near future.
That those make more sense, and you can do that as well in script! I didn't have time to do a lot of fancy scripted plans but that is for sure something I hope modders do and that maybe we can do in the future
 
Current game rule - you can't build a habitat/megastructure in orbit around an object where another station is.

Now a Habitat can earn 200 minerals, whereas a really good Gas Giant can generate 12. So the AI should demolish the mining station to build a Habitat.

The problem in the current Stellaris is that it doesn't plan. It doesn't know that demolish Mining Station allows it to build a Habitat and earn more in the future. So demolish/rebuild probably won't do anything at all unless the AI is "thinking" a couple of steps ahead.

Likewise for Ecumenopolis.

The problem is not that the AI is getting rid of a building or station that is a net negative, it is the opportunity cost that matters.


The current AI does however? So what did you change?
I'm a little bit worried that if this particular problem is not addressed then the AI will be literally incapable of growing up when it can no longer grow out. I'm also not really sure I understand if this was addressed by sidestep in the posts here? I mean it seemed to be is my point, but I didn't really understand if it was yes or no.
 
Ah, technical dev diaries, the best kind when this meaty and lengthy :D
Please, sir(s), may I have some more?

On a more serious note - excellent write-up, I have high hopes for the AI actually not being braindead ... well, at least on the economy side, and possibly on the military side (I suspect it's the economy killing everything else right now). I'm still going to observe my "no pre-order" rule, but don't tempt me like this ... actually, please, do :D

A few things remain unclear for me, however:
A) Will the AI be able to plan in building megastructures to integrate into the economy? What about Ascension Perks? As in, if their empire is locked in and pacifist, will the overall country AI prioritize furthering internal development via demolishing mining stations in favor of habitats, and increase priority on picking up Galactic Wonders and/or Ecus? Because if not I foresee a future where an AI is locked in due to military might or federation blocks, and it has capped out all the planets it has and thus cannot grow more. What will it do? (Admittedly this is an edge case scenario, but still)

B) What about planetary/sector AI? The automation feature that is sorely needed (when you have a large empire) - is there any way for it to benefit from all the work done here? If not, would it be possible to enable economy country AI for the player when automation is turned on, and limit it based on planet designations, as well as let the player edit The Plan™? Please, I've stopped playing conquering empires for this very reason - managing 100 planets manually is no fun at all :(
These are all good points, unfortunately the sector/megastructure/perks AI were not within the scope of this rework. I had a very limited timespan and I really wanted to focus on making the core economy AI ( resources, planet buildings etc. ) work better and be more robust. Lategame "high performance" and more special fixes ( like destroying mining stations to build something else ) I just didnt have time to do, I tried to do a general fix of the core economy that would benefit the AI throughout the entire game.
 
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!
Does that mean the AI still doesn't resettle its Pops?
Do AIs now plan for special planets like Ecus, etc (meaning they also plan to demolish Districts and Buildings)?

Edit: I've read that they CAN now demolish Districts and Buildings. So to modify my question: Does the AI build Ecus (and other planets like Resort, etc) and/or have you seen them do so?
 
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!
I think you replied to the wrong person here? They were asking a question about habitats and space stations, not pop growth.
 
I'm a little bit worried that if this particular problem is not addressed then the AI will be literally incapable of growing up when it can no longer grow out. I'm also not really sure I understand if this was addressed by sidestep in the posts here?
The post immediately after you posted this.

These are all good points, unfortunately the sector/megastructure/perks AI were not within the scope of this rework. I had a very limited timespan and I really wanted to focus on making the core economy AI ( resources, planet buildings etc. ) work better and be more robust. Lategame "high performance" and more special fixes ( like destroying mining stations to build something else ) I just didnt have time to do, I tried to do a general fix of the core economy that would benefit the AI throughout the entire game.

It's not the end of the world - it looks like A) it's on the radar and B) the AI will be much stronger.
 
Just to verify a point.... in your post, you specifically mentioned demolishing BUILDINGS, but didn't explicitly mention demolishing DISTRICTS. Its the failure to do the latter that prevents AI players from developing ecumenopolis planets. Have you made certain to specifically allow the AI to demolish districts too?

Is there currently a desire in the later-game plans to create ecumenoplis planets if available (which would encourage demolition + replacement to make particular planets all city)? If not currently, will there likely be in the future?

Additionally, just to confirm how the resource targets in the plans work - naturally, I'd assume that if we have a very successful AI that's colonized or conquered a lot of planets it would be aiming to produce more resources than the amounts specified in the plans - it would naturally want as much as possible to be produced. So, just to confirm, it won't just "give up" on producing alloys or consumer goods or research or unity once it reaches the plan targets, right? If it has the productive capacity to produce more, it would, right?

Thanks. Really looking forward to seeing these changes in 2.6 and 2.6.1.
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.
 
Economy is way harder to grasp fully, so it will take me a day or two to write something extensive. But two mistakes I can point out outright.

First, do not link the early-mid-late plans to game year. There are empires like Prikki-Ti and uplifted that may appear in lategame with 10 pops on one planet.

Second, do not use empire_size as a percentage of sprawl. Tech cost can be set to anything between 0.25 and 5. There is a huge difference between paying x4 tech cost for 1k extra sprawl on tc1 and x16 (it is actually x20, base gets multiplied too) tech cost for the same sprawl on tc5.