• 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:
Set Zro goal to 0 if Machine or Genetic Ascension path is chosen)

they already talked about how the AI will simply considerate it fullfilled , if it can't find it , while all other goals are reached .

Different Plans for different personalities. This doesn't need to be a unique plan for every personality, but there should be a science plan for erudite explorers, a warmonger plan for genocidals/despoilers/crusaders, A pop growth for Migratory flocks and Harmonius Collectives, a unity plan for inward perfection and spiritual seekers. Just tweaking the numbers a little in various directions so that each personality feels unique in how it tends to play.

i would put it more in the side of "use your ethics bonuses \ and starting triats) since there are bonus to productions with various ethics, you may want the AI to focus more on the thing it is good at .

simply because otherwise you will find intelligent* races building less laboratory , because theyr laboratory produce more and so they need less to reach the goal .
 
Will jobs still use scripted priorities for traits, or will they look at the pop in question's bonuses? (For trait mods and the like)
 
Is the economic 'Plan' going to take the empire size and empire types into consideration? For a mega-corp with less than 10 planets, 300 mineral production will be considered excessive since there is no way to consume them. For Commonwealth of Man with more than 30 planets, there will be extensive planetary construction, 300 minerals is not going to be enough. The 'Plan' should be dynamic to the current empire size or the production target will not be enough to support the empire growth.

Will the 'Plan' taken edicts and decisions into considerations? Human player could intentionally keep up a high food production to launch food distribution on every planets to spur the growth rate, or keeping certain level of gas production for thruster boost edicts to gain strategic advantage in fleets manoeuvre and space mining station constructions.

To conclude, could you explain how dynamic the 'Plan' is? Other than the factors previously mentioned, other factors, such as diplomatic environment (Empire surrounded by same ethics compared to surrounded by purifiers), empire ethics (Militarist AI might demand more in alloy while the materialists ask for researches), AI personality (Playing tall or wide? international market trades? Federation deals?), Technologies (Galactic Wonders, Ecumenopolis or even Ascensions, players could tolerate short period reduction of foods or consumer goods stock if they are close to full habitability through cyber ascensions). Personally, I do agree that the implementation of 'Plan' is a good idea, since it could better simulate how a human player thinks. However, The 'Plan' will only be a shallow digit tables without any grand strategic prospects if it is not dynamic enough. In some sense it is much more important than the military minister, since economic is a strategic long term thinking instead of short term tactical considerations.
 
As someone who spent a few hundred hours testing and modding stellaris economic AI this all soubds positively amazing.

This kind of stuff is what ive been holding out hopes for ever since the post by @Chaingun 1-2 years ago, detailing some of the workings and potential for AI planning in Imperator. (My understanding is that this potential is far from realized yet - largely as a consequence of how fast & fundamentally that game has been changing)

... looking back at all the hard work that has gone into AI modding over the years by ppl like @Glavius and @AlphaAsh , this degree of transperency and depth of modular AI design is no doubt a dream come true....

... a primary reason for ever modding the AI has been the desire to experience the singleplayer game of Stellaris with a satisfactory degree of strategic immersion. This should make that significantly easier.

Thank you!
 
@Todie, you Sir, still need to advertise your mod more often. :D Took me awhile to place you. :)
 
@Todie, you Sir, still need to advertise your mod more often. :D Took me awhile to place you. :)

I havnt updated my AI mod in like a year. The dynamic deficit modifiers mod might still be of potential relevance though. I’ll get back to the game and maybe some modding when federations is launched.
 
I havnt updated my AI mod in like a year. The dynamic deficit modifiers mod might still be of potential relevance though. I’ll get back to the game and maybe some modding when federations is launched.
Count me in, I might be useful. :)
 
they already talked about how the AI will simply considerate it fullfilled , if it can't find it , while all other goals are reached .

i would put it more in the side of "use your ethics bonuses \ and starting triats) since there are bonus to productions with various ethics, you may want the AI to focus more on the thing it is good at .

simply because otherwise you will find intelligent* races building less laboratory , because theyr laboratory produce more and so they need less to reach the goal .

I understand that the plan doesn't need to achieve 100% of goals to be considered fulfilled. It will still *try* to reach those goals, and it would be better for the AI to straight up ignore resources they don't use. There might be other instances where a value should be set to a non-zero number, but I couldn't think of any off the top of my head, and wanted to include a set value in addition to modifying values.
 
I understand that the plan doesn't need to achieve 100% of goals to be considered fulfilled. It will still *try* to reach those goals, and it would be better for the AI to straight up ignore resources they don't use. There might be other instances where a value should be set to a non-zero number, but I couldn't think of any off the top of my head, and wanted to include a set value in addition to modifying values.
It will consider resources only when needed. Like food for an ME; it'll build food stuff only when it has bio Pops it needs to take care of (being amalgamated for example).
 
I come from an economics background, which might be why this is the first thing that comes to my mind. Instead of using some kind of pre-specified plan as to how you want production to end up, why not just create a scoring algorithm (ie a utility function) for different combinations of income flows and then have the AI maximise the score of those different combinations?This is how growth models taking into effect various different baskets of goods have worked since around the 1980s (though perhaps better thought of in a Victoria II sense because the populations are static).

Also, on this: does the AI automatically resettle (I'm not talking about some policy permitting it either, people who have no work should look for it) populations to other planets? While this is a separate system, working emigration and immigration would also solve some of the problems related to labour mobility that seem to pop up a lot even in human-run empires.
 
Will the AI evaluate the sources of various resources in it's economic plan? I.E. if they receive resources from trade deals or temporary bonuses, factoring those parts as less close to complete than they are from a pure numbers perspective? Or is there still going to be the thing where you can destroy the AI economy by subsidising them for a while so they become reliant on you, then pulling the plug?
 
Will the AI evaluate the sources of various resources in it's economic plan? I.E. if they receive resources from trade deals or temporary bonuses, factoring those parts as less close to complete than they are from a pure numbers perspective? Or is there still going to be the thing where you can destroy the AI economy by subsidising them for a while so they become reliant on you, then pulling the plug?

That does sound a fairly realistic way of economic sabotage, with how short-sighted most real-life governments are. xD
 
Every resource has a "use" though, even if it's only selling it off on the market.

(Zro, fin particular though, will have a potential late-game use via a Galactic Community law that boosts research using it).

Yes, and if they have a goal of keeping at 1 production they will keep at 1 production, RATHER than selling it. Yes bulk selling is a thing, but it's generally less efficient than monthly trades. Your point about the galactic community law is valid, as well as the fact its used for psionic battle challenge type.
 
in the video of the terravore you can see some AI action ( i didn't look at planets conquered , maybe i should have ) .

it is on normal difficulty , seems the AI don't stand a chance against an experienced player and is kinda passive even when is overwhelming military against an exterminator . guess the normal behavior is to blame .

you could see the AI run for theyr life and finaly making an effort in a last battle with both theyr fleet and losing miserably .then is just stomping with the power of the exterminator civic and corvette spam .

hope to see a game with some less experienced players on normal difficulty to see more of the AI capacity .
 
Mother of Blorgs, that is one impressive dev diary. Thank you @sidestep and @MatRopert for staying this active here. On the chance that you are still reading, mind if I have a couple more questions?

  1. You mentioned that The Plan does not take difficulty into account. Wouldn't it then make sense to scrap the concept of free resources at higher difficulty alltogether in favour of just lowering prices? Functionally there should be no difference in just giving the AI alloys and making sure it can buy more battleships for the same price. That way the AI following the plan would make sure that the economy could always support itself. It would also scale better into the lategame.
  2. How do the build plans for automated planets look like? Are they somewhat similar to the old system? Can we have them modable?