Creating a trash-talking Minecraft bot using Regression Games, Steamship, and GPT-4

--

Developing an AI to play a multiplayer game is a lot of fun — you get to create a strategy, put that into code, and see if other bots and humans can beat your creation. However, part of the fun of competing against humans is the trash talk — you know you are better than your enemy, and you want them to know!

Well, bots should feel the same way. They know they are better than the humans, so why not talk back and get into that competitive spirit? In this quick tutorial, we will show you how to get a bot to trash talk to a player’s messages and game events in our Capture the Flag game mode in Minecraft, using Steamship and their GPT-4 plugin. Also, participate in the Alpha Cup for a chance to win the Steamship sponsor prize of $400!

Creating the Steamship App

The first thing we will do is create a Steamship app that will generate the trash talk messages for us. Steamship is a platform to easily create and deploy AI apps, such as NLP apps that harness the power of GPT-4. We will be using their gpt-4 plugin to build this trash-talking bot. Note that you can see their getting started docs here, and the final app we will make is located here.

Let’s head over to their website, https://www.steamship.com/, and create an account. Once you create an account and choose your username, click on your profile picture, and select “Account”. Then click “API Key” and click the copy button to copy the API key to your clipboard. Save this somewhere — we will need it later.

The API Key page on steamship

Cloning the Starter Template

Now, let’s create our first Steamship app! We will do this by creating and cloning a starting template. Visit this GitHub page, click “Fork”, and name it “TrashTalkBot-Steamship”.

Once forked, clone the project to your computer and open it up in the Python editor of your choice. Also run the following command to install the local dependencies

pip install -r requirements.txt

Login to Steamship Locally

Now that you have the project open locally, let’s login to Steamship. Do this by running the following command into your terminal. A login screen should appear — this will save your API key to your computer automatically.

npm install -g @steamship/cli && ship login

Once you fork the template, open up src/api.py, and replace the contents with the code below. Take note of the PROMPT variable, which you can modify to your liking:

Please create a response to an enemy game player who says “{phrase}”. The trash talk should be related to the game, which is a Minecraft capture the flag game.

from steamship import check_environment, RuntimeEnvironments, Steamship, SteamshipError
from steamship.invocable import post, PackageService
import json
import time

# Hint: Try changing this!
PROMPT = 'Please create a response to an enemy game player who says "{phrase}". ' \
'The trash talk should be related to the game, which is a Minecraft ' \
'capture the flag game.'


class PromptPackage(PackageService):
"""Generates trash talk"""

@post("generate")
def generate(self, phrase: str = None) -> str:

# First, create an LLM instance (specifically GPT-4)
llm = self.client.use_plugin("gpt-4",
config={
"max_tokens": 30,
"temperature": 0.8
})

# Just in case there is an error getting a response, retry
# a few times
retries = 3
while retries > 0:
try:
response = llm.generate(text=PROMPT.format(phrase=phrase))
response.wait()
return json.dumps({"response": response.output.blocks[0].text})
except SteamshipError as e:
time.sleep(1)
retries = retries - 1

return json.dumps({"error": f"Error getting response: {e}"})


# Try it out locally by running this file!
if __name__ == "__main__":
print("Generate Trash Talk with GPT-4\n")

# This helper provides runtime API key prompting, etc.
check_environment(RuntimeEnvironments.REPLIT)

with Steamship.temporary_workspace() as client:
package = PromptPackage(client)

player_said = input("What did the player say? ")

print("Generating...")

# This is the prompt-based generation call
result = json.loads(package.generate(phrase=player_said))
insult = result['response']
print("Insult: ", f'{insult}')

The code above will define a new package that can be deployed to Steamship, which generates a response to a player’s message. The `class` defines the API for the package, while the if statement at the bottom of the file allows you to try it out by running the file directly in your local environment.

Trying running the file with the following command, and type a message — you’ll see the app respond with some trash talk!

python src/api.py

Nice! Now we will deploy this to Steamship so we can use it within our Regression Games bot. First, add a steamship.json file to your project, with the following contents. Make sure to add your own package name and author information.

{
"type": "package",
"handle": "YOURNAME-rg-trash-talker",
"version": "0.0.1",
"description": "An app to generate trash talk for a Regression Games bot.",
"author": null,
"entrypoint": "Unused",
"public": true,
"plugin": null,
"build_config": {
"ignore": []
},
"configTemplate": {},
"steamshipRegistry": {
"tagline": "An app to generate trash talk for a Regression Games bot.",
"tagline2": "Generates trash talk specifically for a capture the flag bot in Minecraft.",
"usefulFor": "Useful for https://regression.gg",
"videoUrl": null,
"githubUrl": null,
"demoUrl": null,
"blogUrl": null,
"jupyterUrl": null,
"authorGithub": null,
"authorName": "Regression Games",
"authorEmail": null,
"authorTwitter": "RegressionGG",
"authorUrl": "https://regression.gg",
"tags": [
"Regression Games",
"NPC"
]
}
}

Next, run ship deploy in your console. You should see your app deploy, and you can click the link to see your deployed app!

The final step is to create an instance of the app, which we can then call via an API. Simply click “Create Instance”, follow the steps to create the instance, and then you will see the API information (as well as code examples if you click on the /generate endpoint).

Creating the Regression Games Bot

Our trash talking NLP app is ready to go — now we need to create a bot on Regression Games (note that this final bot example can be found here). Login at https://play.regression.gg, create your account (if you don’t have one already), and click on the Bot Manager. Within the Bot Manager, create a new bot from the TypeScript template.

Once you repository gets created, open it in a text editor of your choice (you can find the GitHub repository by clicking the GitHub link in the bot details on the Bot Manager page). Once you have your bot open in an editor, add axios to your package.json file so that you can make an API call to Steamship.

{
...
"dependencies": {
"axios": "1.3.2",
...
}
}

Next, copy and paste the following code into your index.ts file. This adds an API call to generate the trash talk from your Steamship instance, and configures your bot to respond with a trash talk message when anyone says something in the chat. Make sure to insert your Steamship API key where it says STEAMSHIP_API_KEY, and replace STEAMSHIP_ENDPOINT with the endpoint from your generate API listed in the Steamship instance page. You can see this within the CURL example.

import { RGBot } from "rg-bot";
import axios from "axios";

const STEAMSHIP_ENDPOINT = "Endpoint copied from the cURL section of your Steamship package."
const STEAMSHIP_API_KEY = "API Key copied from your Steamship account"

async function generateTrashTalk(phrase: string): Promise<string | null> {
try {
const resp = await axios.post(
STEAMSHIP_ENDPOINT,
{phrase},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${STEAMSHIP_API_KEY}`
}
})
if (resp.data["response"]) {
return resp.data["response"]
} else {
console.error(resp.data)
}
} catch (e) {
console.log(e)
}
return null;
}

/**
* This bot will trash talk back to the player
*/
export function configureBot(bot: RGBot) {

// When a system message is printed, such as a player getting
// a flag, as long as it mentions the flag, create some trash talk
bot.on('message', async (jsonMsg, position, sender, verified) => {
if (position == "system") {
const message = jsonMsg.extra[0]['text'];
if (message.includes("flag")) {
const trashTalk = await generateTrashTalk(message);
if (trashTalk) {
bot.chat(trashTalk)
}
}
}
})

// Any time a player chats, as long as it is not the bot itself,
// generate some trash talk
// TODO: You can improve this by adding some code to only trash
// talk to enemy teams!
bot.on('chat', async (username: string, message: string) => {
if (username == bot.username()) return;
const trashTalk = await generateTrashTalk(message);
if (trashTalk) {
bot.chat(trashTalk)
}
})

}

Push your code, and your bot is ready to go! Get into a Practice match for the Capture the Flag game mode, and begin to either chat with the bot or collect and score the flag. You should see the bot talking back! The bot even recognizes my username (DijsktrasPath) and makes some great puns.

Here are a few honorable mentions:

Please note that this NLP app has no safeguards on it, so please be wary of it generating unacceptable language!

Now that we got a basic prompt working, you should improve it!

  • How can you have the bot respond to different team members in different ways? How does it know if the speaker is an enemy?
  • Sometimes the AI can generate responses that get cut off. What other configs and post-processing can you do?
  • How can you add safeguards against really bad language?

Conclusion

We hoped you enjoyed this tutorial! For more bot competition fun, make sure to visit https://regression.gg and participate in our upcoming tournaments and leagues. For quick deployment of NLP apps, visit https://steamship.com for more use cases and examples. Remember that there is currently a $400 prize for the best use of the Steamship in the Alpha Cup, sponsored by Steamship!

Final Steamship App: https://github.com/vontell/TrashTalkBot-Steamship
Final Regression Games Bot: https://github.com/vontell/TrashTalkBot

Social media accounts — make sure to follow both Regression Games and Steamship!

https://regression.gg
https://steamship.com

https://twitter.com/RegressionGG
https://twitter.com/GetSteamship

--

--