Skip to content

Commit e88aeaa

Browse files
committed
add 11_worldbuilding ft. cohere and stability.ai
1 parent 5ccaf01 commit e88aeaa

File tree

2 files changed

+174
-1
lines changed

2 files changed

+174
-1
lines changed

11_worldbuilding.py

Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
import os
2+
import io
3+
from PIL import Image
4+
from dotenv import load_dotenv
5+
import pandas as pd
6+
import cohere
7+
from stability_sdk import client
8+
9+
10+
load_dotenv()
11+
12+
co = cohere.Client(os.getenv("COHERE_API_KEY"))
13+
stability = client.StabilityInference(
14+
key=os.getenv("STABILITY_API_KEY"),
15+
verbose=True
16+
)
17+
18+
# predicted = co.generate(prompt="Civilization is a video game",
19+
# num_generations=5,
20+
# temperature=0.8,
21+
# return_likelihoods="GENERATION", #ALL, NONE
22+
# max_tokens=80
23+
# )
24+
25+
# print(predicted)
26+
27+
storyConfig = {
28+
"titlePrompt": """
29+
Realistic video game title for a game inspired by Civilization, Starbound and Surviving Mars.
30+
Turn-based, deep tech trees, single player modes only with card-based mechanics.
31+
Title: Colonizing Mars \n
32+
Title: Space Empires \n
33+
Title: Interstellar Frontiers \n
34+
Title: """,
35+
"civLeadersPrompt": """
36+
Realistic names for leaders of a space-themed Civilization video game; Follow the template provided.
37+
Leader: Jeff Bessos | Civilization: Amazonia | Description: Jeff Bessos is the leader of the Amazonian civilization. He is a ruthless businessman who will stop at nothing to expand his prosperous space-faring empire. \n
38+
Leader: Elon Musnt | Civilization: Emeraldo | Description: Elon is a billionaire and a pioneer in private space travel. He is the leader of the loyal Emeraldo civilization. \n
39+
Leader: Thorny Stark | Civilization: Stark Assembly | Description: Thorny is the leader of the Stark Assembly. He is a genius inventor, charismatic and known for his philantropic efforts. \n
40+
Leader: """,
41+
"characterStyle": "in-game character portraits, sci-fi, futuristic civilization in the background, serious expression, realistic",
42+
"civLocationPrompt": """
43+
Names and descriptions of countries and civilizations in a space-themed video game.
44+
Civilization: Amazonia | Description: Amazonia is a civilization of space-faring humans. They are a ruthless and expansionist civilization, known for their advanced technology and military prowess. \n
45+
Civilization: Emeraldo | Description: Emeraldo is a thriving civilization of star travelers. They are a loyal and peaceful civilization, prefer to rely on their scientific prowess in their quest for power. \n
46+
Civilization: De Valtos Syndicate | Description: De Valtos Syndicate are traders and explorers who wander the stars in search of new worlds to colonize and trade with. They are generally peaceful and trusting, but will not hesitate to defend themselves if attacked. \n
47+
Civilization: """,
48+
"civStyle": "realistic in-game space civilization cities and space ports, thriving, busy, sci-fi, hi-resolution scenery for a city simulation game",
49+
"inGameCutScenes": """
50+
Continue writing the in-game cut scenes following the format of the dialog provided below:
51+
52+
Welcome, Commander. You have been appointed as the new leader of the {civ} civilization.
53+
{civ_description}.
54+
Your mission is to lead your people to prosperity and glory among the stars.
55+
56+
You will need to build a thriving civilization, explore the galaxy, and defend your people from hostile elements. Central Officer Johann Bradford will be at your aid. Our chief scientist, Dr. Maya will also assist you in your quest for galactic domination.
57+
Both of them are waiting for you in the command center. Please proceed to the command center to begin your daily briefing.
58+
59+
Bradford: Welcome, Commander. I am Central Officer Johann Bradford. You came in at a good time. We have just received a distress signal from the {civ2} civilization. Their nearby starport, the Mercury Expanse, has alerted us to some hostile activity in their vicinity.
60+
Dr.Maya: I urge caution, Commander. {civ2_description}. In their past encounters with {ally1}, they have proven to be distrustful and quick to escalate conflicts. I recommend that we send a small fleet to investigate the situation first.
61+
Bradford: Perhaps Military Officer Levy can lead the investigation. Our senior-ranked officers are due to be back from their planetary exploration mission soon.
62+
63+
Player: [Select Military Officer Levy to lead the investigation] or [Wait for the senior-ranked officers to return from their planetary exploration mission]
64+
65+
Bradford: Commander, we have just received another distress signal from the {civ2} civilization on behalf of Mercury Expanse. They are reporting heavy casualties on the ground and will require immediate assistance.
66+
Dr.Maya: Commander, I strongly recommend we send a small fleet to investigate the situation. Our senior-ranked officers are away on their planetary expeditions and we cannot afford to take any chances.
67+
Bradford: I disagree. Mercury Expanse is an economically important starport and {civ2} is a valuable trading partner. Sending an investigation fleet while their star system is under attack will only signal distrust and hostility. They are reporting heavy casualties.
68+
Dr.Maya: I understand your concerns, Commander. But we cannot afford to take any chances until our Team 6 and Delta Squad return from their expeditions. If things go wrong, we will be left with no viable defense options.
69+
70+
Player: [Summon Team 6 to return from their expeditions] or [Summon Delta Squad to return from their expeditions] \n
71+
72+
Bradford: While we wait for our expedition team to return, do I have orders to send our Delta Reserve to assist the {civ2} civilization?
73+
Dr.Maya: Commander...
74+
75+
Bradford: Commander, Officer Levy is on the line. Shall I put him through?
76+
77+
Player: Yes.
78+
Officer Levy: Commander, I've heard about the situation at Mercury Expanse. I'm concerned about the severity on the ground if the reports are accurate. A small fleet of investigation ship is no match for a full-scale attack.
79+
Dr.Maya: Being economically important, Mercury Expanse has a large fleet of defense ships and ground troops. I wonder what could have caused such heavy casualties on the ground, and if so, Officer Levy is right. We will need to send in our entire reserve fleet to have the best chance of success. This puts a lot of risk on our side, but it might be the only way to ensure the safety of {civ2} and Mercury Expanse.
80+
81+
Player: [Send in the entire reserve fleet] or [Send the Delta Reserve while preserving the rest of the fleet] \n
82+
Bradford:
83+
"""
84+
}
85+
86+
87+
def generate(prompt, model="base", num_generations=5, temperature=0.7, max_tokens=64):
88+
predictions = co.generate(
89+
prompt=prompt,
90+
model=model,
91+
num_generations=num_generations,
92+
temperature=temperature,
93+
max_tokens=max_tokens,
94+
return_likelihoods="GENERATION",
95+
stop_sequences=["\n"]
96+
)
97+
98+
generations = {}
99+
100+
for generation in predictions.generations:
101+
102+
text = generation.text.replace("\n", "")
103+
104+
generations[text] = 0
105+
106+
for tl in generation.token_likelihoods:
107+
generations[text] += tl.likelihood
108+
109+
# turn this into a dataframe
110+
df = pd.DataFrame.from_dict(generations, orient="index", columns=["likelihood"])
111+
df = df.sort_values(by=["likelihood"], ascending=False)
112+
return df
113+
114+
def generate_img(prompt):
115+
predictions = stability.generate(prompt)
116+
117+
for img in predictions:
118+
for artifact in img.artifacts:
119+
# check that it's an image type
120+
if artifact.type == 1:
121+
img = Image.open(io.BytesIO(artifact.binary))
122+
img.show()
123+
return img
124+
125+
126+
if __name__ == "__main__":
127+
titles = generate(storyConfig["titlePrompt"])
128+
print(titles)
129+
130+
leaders = generate(storyConfig["civLeadersPrompt"], num_generations=5)
131+
print(leaders)
132+
133+
# leader_img = generate_img(
134+
# f"{storyConfig['characterStyle']}{leaders.iloc[3].name}"
135+
# )
136+
# leader_img.show()
137+
138+
civs = generate(storyConfig["civLocationPrompt"])
139+
140+
# for civ in civs[:3]:
141+
# civName, civDescription = civs.name.split("|")
142+
# civImg = generate_img(f"{storyConfig['civStyle']}{civDescription}")
143+
# civImg.show()
144+
145+
civname, civdescription = civs.iloc[3].name.split("| Description: ")
146+
civname2, civdescription2 = civs.iloc[4].name.split("| Description: ")
147+
ally1 = leaders.iloc[2].name.split("|")[0].strip()
148+
149+
cutscenes_prompt = storyConfig["inGameCutScenes"].format(
150+
civ=civname,
151+
civ_description=civdescription,
152+
civ2=civname2,
153+
civ2_description=civdescription2,
154+
ally1=ally1
155+
)
156+
157+
cutscenes = generate(
158+
cutscenes_prompt,
159+
model="command-nightly",
160+
num_generations=3,
161+
max_tokens=800,
162+
temperature=0.9,
163+
)
164+
165+
dialog = cutscenes_prompt + "\n" + cutscenes.iloc[0].name
166+
print(dialog)
167+
168+
# generate img for that cutscene
169+
cutscene_img = generate_img(
170+
f"An in-game, sci-fi cutscene with lots of details for: {cutscenes.iloc[0].name}"
171+
)

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ A set of instructional materials, code samples and Python scripts featuring LLMs
44
<!-- <img src="assets/youtube.png" width="50%" alt="LangChain youtube tutorials" /> -->
55
![LangChain youtube tutorials](assets/llmseries.png)
66

7-
Learn LangChain from my YouTube channel (~5 hours of content); Each lesson is accompanied by the corresponding code in this repo and is designed to be self-contained -- while still focused on some key concepts in LLM (large language model) development and tooling.
7+
Learn LangChain from my YouTube channel (~6 hours of content); Each lesson is accompanied by the corresponding code in this repo and is designed to be self-contained -- while still focused on some key concepts in LLM (large language model) development and tooling.
88

99
Feel free to pick and choose your starting point based on your learning goals:
1010

@@ -19,6 +19,7 @@ Feel free to pick and choose your starting point based on your learning goals:
1919
| 7 | Locally-hosted, offline LLM w/LlamaIndex + OPT (open source, instruction-tuning LLM) | [Tutorial Video](https://youtu.be/qAvHs6UNb2k) | 32:27 |
2020
| 8 | Building an AI Language Tutor: Pinecone + LlamaIndex + GPT-3 + BeautifulSoup | [Tutorial Video](https://youtu.be/k8G1EDZgF1E) | 51:08 |
2121
| 9 | Building a queryable journal 💬 w/ OpenAI, markdown & LlamaIndex 🦙 | [Tutorial Video](https://youtu.be/OzDhJOR5IfQ) | 40:29 |
22+
| 10 | Making a Sci-Fi game w/ Cohere LLM + Stability.ai: Generative AI tutorial | [Tutorial Video](https://youtu.be/uR93yTNGtP4) | 1:02:20 |
2223

2324
The full lesson playlist can be found [here](https://www.youtube.com/playlist?list=PLXsFtK46HZxUQERRbOmuGoqbMD-KWLkOS).
2425

@@ -27,6 +28,7 @@ The full lesson playlist can be found [here](https://www.youtube.com/playlist?li
2728
2. Install requirements: `pip install -r requirements.txt`
2829
3. Some sample data are provided to you in the `news` foldeer, but you can use your own data by replacing the content (or adding to it) with your own text files.
2930
4. Create a `.env` file which contains your OpenAI API key. You can get one from [here](https://beta.openai.com/). `HUGGINGFACEHUB_API_TOKEN` and `PINECONE_API_KEY` are optional, but they are used in some of the lessons.
31+
- [Lesson 10](./11_worldbuilding.py) uses Cohere and Stability AI, both of which offers a free tier (no credit card required). You can add the respective keys as `COHERE_API_KEY` and `STABILITY_API_KEY` in the `.env` file.
3032

3133
The `.env` file should look like this:
3234
```

0 commit comments

Comments
 (0)