Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

03 - Send GPT request #4

Open
wants to merge 4 commits into
base: 02-genres
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<!-- Importing local CSS file -->
<link href="./style.css" rel="stylesheet">
<!-- Importing local JS file -->
<script src="config.js" defer></script>
<script src="main.js" defer></script>
</head>

Expand All @@ -24,6 +25,15 @@ <h1>ChatVenture</h1>
<p>Hello PLAYER! Welcome to the text adventure game where the story is made up by GPT :)</p>
</header>

<div class="loading hidden">
<img src="./images/loader.gif" alt="loading icon">
</div>

<div class="error hidden">
<strong>Sorry, something went wrong...</strong>
<div class="error-messages"></div>
</div>

<div class="genres">
<button class="genre" data-genre="horror">👻</button>
<button class="genre" data-genre="spy film">🕵🏻‍</button>
Expand Down
87 changes: 86 additions & 1 deletion main.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,93 @@
const chatGptMessages = [];

const makeRequest = async (url, data) => {
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${_CONFIG_.API_KEY}`,
// Our _CONFIG data is imported in the HTML file using the <script> tag meaning
// it is then accessible via global scope (other JS files, browser console, etc).
},
method: 'POST',
body: JSON.stringify(data)
});

return response.json();
}

const showLoadingAnimation = (isLoading) => {
const loadingScreen = document.querySelector('.loading');
if(isLoading) {
loadingScreen.classList.remove('hidden');
} else {
loadingScreen.classList.add('hidden');
}
}

const showErrorMessage = (isError) => {
const loadingScreen = document.querySelector('.error');
if(isError) {
loadingScreen.classList.remove('hidden');
} else {
loadingScreen.classList.add('hidden');
}
}

const startGame = async (genre) => {
showErrorMessage(false);

// Message to send to ChatGPT to start the game
chatGptMessages.push({
role: 'system',
content: 'I want you to play like a classic text adventure game. I will be the protagonist and main player. Don\'t refer to yourself. ' +
'The setting of this game will have a theme of ' + genre + '. ' +
'Each setting has a description of 150 characters followed by an array of 3 possible actions that the player can perform. ' +
'One of these actions is fatal and ends the game. Never add other explanations. Don\'t refer to yourself. ' +
'Your responses are just in JSON format like this example:\n\n###\n\n {"setting":"setting description","actions":["action 1", "action 2", "action 3"]}\n\n###\n\n'
});

let chatResponseJson;

try {
showLoadingAnimation(true);

// Send request to ChatGPT Chat Completion API
// https://platform.openai.com/docs/api-reference/chat/create
chatResponseJson = await makeRequest(_CONFIG_.API_BASE_URL + '/chat/completions', {
model: _CONFIG_.GPT_MODEL,
messages: chatGptMessages,
temperature: 0.7
// The model predicts which text is most likely to follow the text preceding it.
// Temperature is a value between 0 and 1 that essentially lets you control how confident the model should be
// when making these predictions. Lowering temperature means it will take fewer risks, and completions will be
// more accurate and deterministic. Increasing temperature will result in more diverse completions.
});

const message = chatResponseJson.choices[0].message;
const content = JSON.parse(message.content);
const {setting, actions} = content;
console.log('SETTING:', setting);
console.log('ACTIONS:', actions);

showLoadingAnimation(false);
} catch (error) {
let errorMessages = `<p>${error.message}</p>`;

if (chatResponseJson.error) {
errorMessages += `<p>${chatResponseJson.error.message}</p>`;
}

showLoadingAnimation(false);
document.querySelector('.error-messages').innerHTML = errorMessages;
showErrorMessage(true);
}
}

const init = () => {
const genres = document.querySelectorAll('.genre');
genres.forEach((button) => button.addEventListener(
'click',
() => alert(`You selected the genre: ${button.dataset.genre}`))
() => startGame(button.dataset.genre))
)
}

Expand Down
20 changes: 20 additions & 0 deletions style.css
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,22 @@ header {
padding: 32px;
}

.loading {
display: flex;
justify-content: center;
align-items: center;
height: 512px;
}

.error {
text-align: center;
font-size: 24px;
}

.error > * {
color: tomato;
}

.genres {
display: grid;
grid-template-columns: repeat(3, 100px);
Expand All @@ -52,3 +68,7 @@ header {
background-color: rgba(255,255,255,0.7);
border: 4px solid #f1c82d;
}

.hidden {
display: none;
}