In the past six months, the world has been sitting on its ass from ChatGPT, the new Bing, and other textual AI systems from the so-called large language models (LLM), however, regular readers of the do-it-yourself series have been kept cold.
I’ve already mastered most of the working knowledge of bots from OpenAI Labs a couple of years ago Technology breakthrough From Brno named Živak voice assistant!
Well, it wasn’t unprecedented, but it did open up a bit about how many bots and semantic and seemingly know-it-all search engines had worked up to that point.
Watch the video on how to connect ChatGPT technology to our Živák voice assistant:
Before the advent of artificial intelligence, Wikipedia introduced intelligence
Back then similar programs dumped all the logic into one knowledge-based, license-free resource you all know so well, Wikipedia and API for developers.
So when we asked Zivak a question What is paprika?, did not itself perform any semantic analysis, but simply forwarded the text string in its original form to the Wikipedia server. Only then did I realize we might be asking about the date Pepper All available articles on this topic are presented.

Sivak heard “What is Paprika” and looked up the answer on Wikipedia
Živak then chose the first option in order and asked Wikipedia again through the API to return a brief summary. This is not the entire text of the article in the community encyclopedia, but only a quick and informative summary of a few sentences, which our bot finally displayed on the screen and read through the Windows 10/11 sound synthesizer and sound Microsoft Jacob.
It was effective It was all chromedand even though it only had about a hundred lines of full HTML code including Javascript and comments, the average person would think it was actually communicating with some kind of complex AI that a team of developers had been building for months on a supercomputer somewhere.
but where! Any East Asian schoolboy who cares about performance will take our experimental app left.
Today we are going to connect ChatGPT to Živák
However, time has passed, and today OpenAI is fashionable, so in two years we will also connect Živák with its technology. We won’t repeat again how it actually works – here I’ll refer you to the previous parts:
We will get straight to the heart of the matter.
New model gpt-3.5-turbo
OpenAI has been offering an API to developers for some time now, and its documentation and terms can be found on the website platform.openai.com. Each user gets credit to play at first, after which they have to create a paid account.
Today, the OpenAI platform can work with a full range of its own technologies, from text completion and classification to image generation. Then a few days ago Two new models have been added:
While the first mentioned and constantly improved model will be provided by the ChatGPT bot, hiss The spoken word recorded for example in MP3 can be translated into text.
In the world of large language paradigms, you don’t pay for CPU time, you pay for processing symbols, which is their smallest unit of information. We explained what tokens are in the case of OpenAI and ChatGPT using several examples in a separate article.
I’ll just reiterate that one code contains an average of about four characters, and in the case of the gpt-3.5-turbo model, which has undergone a massive optimization process since the first versions, OpenAI charges $0.002 per thousand tokens. This is an order of magnitude lower than before.
First, we generate an API key
Let’s give it a try. Let’s say you create an account on the OpenAI Platform website, have some credit to get started, or you already pay for access, and You have created your API keywith which you will sign queries on the OpenAI platform.


Each new user gets trial credits at the start and generates an API access key
Then you can with neurons and their models Communication through the library in one of the many supported programming languages. OpenAI directly develops its own library for Python and Node.js, as well as community for PHP, C#, Java, Kotlin and other technologies.
And now we will ask about pepper from the command line
However, you can also communicate directly with the API Through a simple HTTP request. So if you have a practically standard text HTTP client on your computer today rollquery for ChatGPT bot as below:
“What are paprika? Write the answer in Czech.”
It might look like this on the command line:
curl https://api.openai.com/v1/chat/completions -H "Authorization: Bearer API klíč" -H "Content-Type: application/json" -d '{"model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": "Co je to paprika? Odpověď napiš v češtině"}]}'
Let’s break it down in short:
- https://api.openai.com/v1/chat/ is the destination HTTP address
- -H “Authorization: Bearer API key” It is the HTTP header with the API key
- -H “content-type: application/json” It is the HTTP header in the data format
- -d XXX It is HTTP POST data in JSON format
Then, the JSON structure with query parameters has the following form:
{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": "Co je to paprika? Odpověď napiš v češtině"
}
]
}
And we break it down again:
- model is the AI from the OpenAI list that we want to use
- Role It is the role of this query. We ask as a user, so the user
- content It is the same question in natural Czech
Note that we do not wrap the query with any parameters. For example, by selecting the language in which we want to get an answer. On the OpenAI side, the text query is first translated into numeric token identifiers and sent to the neural network itself and its model.


Our query has been converted to GPT-3 architectural symbols. Try it for yourself in token
The model is actually a learned statistical structure of the links between individual symbols, so that the AI can estimate the probability of a sequence of symbols with some other sequence of symbols of a given length.
This is what the answer would look like
The compiler/detokenizer converts the generated sequence of tokens into readable characters, which it finally sends to us including the computed stats in JSON format.

Complete the question and answer on the OpenAI API from the command line
The answer can look in machine-processable JSON and in a more readable format like in the example below in the case of pepper. But beware, ChatGPT is not Wikipedia, so each answer is somewhat unique and may look slightly different than the previous one.
Reply in JSON format:
{
"id": "chatcmpl-6qmMNCSVreZN0Gw9JDvl93QGrMnJN",
"object": "chat.completion",
"created": 1678036971,
"model": "gpt-3.5-turbo-0301",
"usage": {
"prompt_tokens": 28,
"completion_tokens": 88,
"total_tokens": 116
},
"choices": [
{
"message": {
"role": "assistant",
"content": "\n\nPaprika je pálivá nebo sladká koření, která se získává z různých odrůd paprikového pepře. Může být používána jako koření do jídel, jako zelenina, nebo se z ní vyrábí paprikový olej."
},
"finish_reason": "stop",
"index": 0
}
]
}
We’re not going to explain exactly what each element of the answer represents – I think it’s pretty obvious from the example – so just the most important ones. in the key model We see the specific version of AI that OpenAI used. in the key Role We see that this is an answer in assistant mode, and its wording is in the key content.
The section is also very important the use, which tells us how many tokens we have consumed. The same question preoccupied them 28So, a very short answer 88. But for more detailed answers, the number can run into the hundreds. He completely burned the question 116 tokens.
And now the same in javascript and html
It works on the command line with the curl HTTP client, but for now let’s rewrite everything in the form of a simple website that will run locally without any server once you open it in a browser.

The ChatGPT API web interface is simple
Don’t forget to set the value of the variable openai_api_key A custom ID that you are They generated it on the OpenAI website.
<!DOCTYPE html>
<html lang="cs">
<head>
<title>Dotaz na ChatGPT pomocí API</title>
<script>
// Funkce, která se spojí s OpenAI API skrze asynchronní HTTP klient Fetch API,
// který podporují všechn ymoderní prohlížeče
// Viz https://developer.mozilla.org/en-US/docs/Web/API/fetch
function dotazGPT(){
let openai_api_klic = "xxxxxxx";
let dotaz = document.querySelector("#dotaz").value;
document.querySelector("#vysledek").innerHTML = "<p style="font-size:150%">Zjišťuji odpověď, chvíli to může trvat...</p>";
fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": "Bearer " + openai_api_klic,
"Content-Type": "application/json"
},
body: JSON.stringify({
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": dotaz
}
]
})
})
// Odpověď HTTP serveru zpracuj jako JSON
.then((odpoved) => odpoved.json())
// Teď už máme JSON a můžeme s ním pracovat
.then((json) =>{
// Načteme odpověď AI
let odpoved = json.choices[0].message.content;
// Zjistíme, kolik jsme propálili tokenů
let tokeny_vstup = json.usage.prompt_tokens;
let tokeny_vystup = json.usage.completion_tokens;
let tokeny_celkem = json.usage.total_tokens;
// Do HTML kontejneru #vysledek napíšeme odpověď a seznam,
// koli ktokenů jsme propálili
document.querySelector("#vysledek").innerHTML =
"<p style="font-size:150%">" + odpoved + "</p>" +
"<ul>" +
"<li><b>Spotřeba tokenů celkem:</b> " + tokeny_celkem + "</li>" +
"<li><b>Spotřeba tokenů, dotaz:</b> " + tokeny_vstup + "</li>" +
"<li><b>Spotřeba tokenů, odpověď:</b> " + tokeny_vystup + "</li>" +
"</ul>";
});
}
</script>
</head>
<body>
<!-- Textový vstup pro dotaz -->
<input id="dotaz" type="text" value="Na něco se zeptej" />
<!-- Při klepnutí na tlačítko zavolej funkci dotazGPT() -->
<input type="button" value="Odešli" onclick="javascript:dotazGPT()">
<!-- Kontejner pro odpověď -->
<div id="vysledek"></div>
</body>
</html>
The simple page consists of a text entry, a button, and a container that shows the response from ChatGPT, and to get a better idea, the stats of the tokens consumed.
When the button is clicked through the built-in asynchronous HTTP client fetch API We connect to the OpenAI server and after a few seconds (depending on the load) we get a response in JSON.
The simple Fetch API has been supported by almost all current web browsers for years, so there is no need to keep using external libraries like jQuery for similar trivialities.
Finally, we are integrating AI directly into Živák
As you can see, the basic work with OpenAI is quite simple, even with ordinary HTML pages, and for other languages, including the popular Python, there are libraries directly from the creators of the technology or the community.

This time, Živak sends the question “what is pepper” to the OpenAI server and requests that it be processed by the model gpt-3.5-turbo which behaves like the latest ChatGPT
But we will be content with the above code, which we will use to extend our Živak from 2021. In the default case, we will send all the text inputs we got from the SST (Speech to Text) layer to the OpenAI servers.
However, we don’t want to completely get rid of Wikipedia, so Živak will support both sources of knowledge, which is convenient for comparing capabilities. We can switch between the two sources in the app on the keyboard.
Switch search source
By default, Živak searches for an answer on Wikipedia. The search source can be switched by pressing the C and W keys:
- c Sets the search source to ChatGPT
- w Sets the search source to Wikipedia
You can view the commented code of Živák in a single HTML file below, for a deeper understanding I will redirect you back to the original articles, in which we first showed how to work with speech-to-text and vice versa on Windows and Chrome, and then, how to connect to Wikipedia, find Articles on the desired topic and get a brief summary of them, which our app will then display and retell.
Živák’s code that uses both ChatGPT and Wikipedia
Don’t forget to replace the text in the variable in the code openai_api_key A custom ID that you are They generated it on the OpenAI website.
<!DOCTYPE html>
<html lang="cs">
<head>
<title>Asistent Živák</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Sofia+Sans+Semi+Condensed&display=swap" rel="stylesheet">
<style>
/* CSS styl stránky
* Bez okraje, bez posuvníků
* S rozložením tabulky
*/
html, body{
font-family: "Sofia Sans Semi Condensed", sans-serif;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: table;
overflow: hidden;
cursor: pointer;
}
/* CSS styl tagu s indetifikatorem vysledek
* Pružná velikost písma podle výšky okna,
* zobrazení jako tabulková buňka s vycentrovaným obsahem
*/
#vysledek{
font-size: 5vh;
display: table-cell;
text-align: center;
vertical-align: middle;
padding: 50px 50px;
}
/* CSS styl tagu s indetifikatorem informace
* Druhý řádek tabulky, funkce patičky stránky
*/
#informace{
color: #bbbbbb;
font-size: 3vh;
display: table-row;
text-align: center;
}
/* Třída stylu error pro obarvfení chyby do ruda */
.error{
color:coral;
}
</style>
<script>
let stt; // Proměnná objektu převodu hlasu na text (Speech To Text)
let cena_sezeni = 0; // Celková statistika spotřebovaných tokenů během sezení v OpenAI API
let zdroj = "wikipedie"; // Zdroj, kterého se budeme dotazovat
// Osobní OpenAI klíč
// Po vytvoření účtu vygenerujete na adrese: https://platform.openai.com/account/api-keys
let openai_api_klic = "xxxxxxxx";
// Po kliknuti myší na stránku zavolej funkci posloucham
document.onclick = (udalost) => posloucham();
// Po stisku klávesy zavolej funkci posloucham
// Stiskem W nastavím zdroj na Wikipedii
// Stiskem C nastaví mzdroj na ChatGPT
document.onkeydown = (udalost) => {
if(udalost.keyCode == 87) zdroj = "wikipedie"
else if(udalost.keyCode == 67) zdroj = "chatgpt"
console.log("Zdroj: " + zdroj);
document.title = "Asistent Živák (" + zdroj + ")";
posloucham();
}
// Po kompletním načtení stránky zpracuj tuto anonymní funkci
window.onload = (udalost) => {
document.title = "Asistent Živák (" + zdroj + ")";
hlavniOkno("Klepni a na něco se zeptej"); // Napiš hlášku do okna
console.log("Komandére, okénko prohlížeče je připraveno k hrátkám"); // Vypiš do konzole prohlížeče uvítání
stt = new webkitSpeechRecognition(); // Nastartuj technologii Web Speech API v prohlížeči Chrome
stt.continuous = false; // Nechceme získávat průběžné výsledky, ale až celou větu
stt.lang = "cs-CZ"; // Chceme na text převádět hlas v češtině
stt.interimResults = false; // Nechcme dostávat (rychlejší) předběžné výsledky, ale až finální a kvalitní
// Jakmile převod řeči na text uslyší delší ticho, přestane poslouchat, zpracuje zvuk a zavolá tuto anonymní funkci
stt.onresult = (udalost) => {
if(udalost.results.length > 0){ // Pokud jsme získali alespoň 1 výsledek
let text = udalost.results[0][0].transcript; // Ulož do pomocné proměnné první výsledek z pole přepisů
console.log("========================================"); // Vypiš do konzole pro kontrolu, co prohlížeč uslyšel
console.log("Hlas: „" + text + "“");
hlavniOkno("Hledám odpověď..."); // Napiš hlášku do okna
zprocesuj(text.toLowerCase()); // Pošli text k sémantické analýze
}
// Pokud žádný výsledek nemáme,
// resetuj pohled a do patičky naiš důvod
else{
hlavniOkno("Klepni a něco řekni...");
informacniBox("Žádné mluvené slovo");
}
}
stt.onspeechend = () => stt.stop(); // Na konci detekce mluveného slova ukonči poslech
// V případě chyby převodu Speech To Text
stt.onerror = (udalost) => {
console.log(udalost.error);
hlavniOkno("Klepni a něco řekni...");
informacniBox("Chyba analýzy hlasu: <span class="error">" + udalost.error + '</spann>');
}
// V případě, že Speech To Text nedokáže najít žádné mluvené slovo
stt.onnomatch = (udalost) => {
hlavniOkno("Klepni a něco řekni...");
informacniBox("Nerozpoznal jsem žádné mluvené slovo");
}
}
// Pomocí technologie pro syntézu řeči se prohlížeče zeptej, jestli má k dispozici nějaké syntetizátory
// a vypiš je zpracováním této anynonymní funkce
window.speechSynthesis.onvoiceschanged = () => {
console.log("Výpis dostupných TTS služeb v Chromu:");
let hlasy = window.speechSynthesis.getVoices(); // Získej seznam syntetizátrů
for(hlas of hlasy){ // Projdi pole syntetizátorů a vypiš je do konzole do prohlížeče
console.log(
((hlas.default)? "D" : " ") + " " + // Pokud se jedná o výchozí syntetizátor, napiš „D“ jako defaultní
((hlas.localService)? "✔️" : "☁️") + " " + // Pokud je syntetizátor přímo na zařízení, nakrseli fajfku, pokud je pozue online, nakresli emoji mráčku
hlas.lang + " " + // Jazyk syntetizátoru
hlas.name // Jméno syntetizátoru
);
}
}
// Funkce poslouchám spustí převod hlasu na text
function posloucham(){
console.log("🎤 Poslouchám...");
window.speechSynthesis.cancel(); // Pokud hlasový syntetizátor právě mluví, ukončí ho
hlavniOkno("Poslouchám...");// Do textového okna napiš informační zprávičku
stt.start(); // Konečně aktivuj poslech
}
// Pomocná funkce pro zobrazení textu v patičce
function informacniBox(text){
document.querySelector("#informace").innerHTML = text;
}
// Pomocná funkce pro zobrazení hlavního textu na středu obrazovky
function hlavniOkno(text){
document.querySelector("#vysledek").innerHTML = text;
}
// Funkce rekni pomocí hlasového syntetizátoru přříká obsah vstupní porměnné text
function rekni(text){
hlavniOkno(text, true); // Vypiš text do okna
let rec = new window.SpeechSynthesisUtterance(); // Objekt rec s konfigurací syntetizátoru
rec.lang = "cs-CZ"; // Chceme použít (jakýkoliv) syntetizátor v nabídce, který umí mluvit česky
rec.text = text; // Chceme, aby přeříkal obsah proměnné text
rec.pitch = 1; // Výška zabarvení hlasu (0-2)
rec.rate = 0.9; // Rychlost hlasu (0,1-10)
rec.volume = 2; // Hlasitost (0-2)
rec.onend = (event) => {
hlavniOkno("Klepni a na něco se zeptej");
informacniBox("");
}
window.speechSynthesis.speak(rec); // Předej řeč hlasovému syntetizátoru ke zpracování
}
/* Hlavní funkce pro analýzu textu, který jsme získali z STT (Speech-To-Text)
* Pokud vstup obsahuje slovo „wikipedie“, zpracujeme jej funkci zeptejSeWikipedie
* V opačném případě se zpetáme ChatGPT
*/
function zprocesuj(text){
if(text.length > 0){
if(zdroj == "wikipedie"){
informacniBox("Ptám se Wikipedie");
zeptejSeWikipedie(text);
}
else{
informacniBox("Ptám se ChatGPT");
text += ". Piš v češtině";
zeptejSeChatGPT(text);
}
}
else{
console.log("🔊 Spouštím TTS"); // V konzoli nás informuj, že spouštíš hlasový syntetizátor
rekni("Neslišel jsme žádnou otázku"); // Zavole funkci pro přeříkání textu hlasovým syntetizátorem
}
}
/* Funkce pro vyhledání dotazu na Wikipedii skrze její API; mozek našeho znalostního asistenta
* Nejprve se Wikipedie zeptáme, jestli má k našemu dotazu nějaké články
* Pokud ano, zeptáme se jí znovu na stručné resumé/perex prvního nalezeného článku v pořadí
*/
function zeptejSeWikipedie(text){
// Pomocí veřejného API Wikipedie vyhledej články, které odpovídají dotazu a odpoveď získej ve formátu JSON
fetch("https://cs.wikipedia.org/w/api.php?origin=*&action=query&list=search&utf8&format=json&srsearch=" + encodeURIComponent(text))
.then((odpoved) => odpoved.json())
.then((json) => {
// Pokud má pole s výsledky alespoň jednu položku
if(json.query.search.length > 0){
console.log("Na dotaz existuje " + json.query.search.length + " článků:"); // Vypiš do konzole počet nalezených výsledků
for(let clanek of json.query.search) console.log(" ✔️" + clanek.title); // Vypiš do konzole nalezené články
let clanek = json.query.search[0].title; // Vyber nadpis prvního nalezeného článku v pořadí
// Do patičky napíšeme odkaz článku, ze kterého čerpáme. Zdrojování je základ!
informacniBox("Zdroj odpovědi: <a target="_blank" href="https://cs.wikipedia.org/wiki/"" + encodeURIComponent(clanek)+ ">" + clanek + "</a>");
// Znovu kontaktuj skrze API Wikipedii a tentokrát získej stručné resumé/perex zvoleného článku
fetch("https://cs.wikipedia.org/w/api.php?origin=*&action=query&format=json&utf8&prop=extracts&exintro&explaintext&indexpageids&redirects=1&titles="+encodeURIComponent(clanek))
.then((odpoved) => odpoved.json())
.then((json) =>{
console.log("Vypisuji první odpověď");
let uryvek = json.query.pages[json.query.pageids[0]].extract; // Získej první extrakt/perex v pořadí
if(uryvek.length > 200){ // Perex může být i tak docela dlouhý. Pokud má tedy více než 200 znaků
console.log("Odpověď příliš dlouhá, krátím po větách");
let vety = uryvek.split("."); // Rozděl text na jednotlivé věty (děličem je znak tečky na konci věty)
let kratsi = ""; let i = 0;
while(kratsi.length < 200){ // Vytvoř krátší perex, který bude mít zhruba 200 znaků (plus znaky navíc do konce věty)
kratsi += vety[i++] + ".";
}
uryvek = kratsi; // Prohoď původní perex za ten nový a kratší
}
console.log("🔊 Spouštím TTS"); // V konzoli nás informuj, že spouštíš hlasový syntetizátor
rekni(uryvek); // Zavole funkci pro přeříkání textu hlasovým syntetizátorem
});
}
// Pokud jsem k dotazu nedokázal na Wikipedii nalézt žádný odpovídající záznam
else{
console.log("Nenašel jsem odpověď");
rekni("Jsem nedokonalý idiot a zdaleka nerozumím všemu. Zeptej se raději Kuby Čížka, ten totiž ví úplně všechno."); // Pošli hlasovému syntetizátoru, aby se omluvil trošku barvitěji
}
});
}
function zeptejSeChatGPT(text){
// Spojíme se s OpenAI a pošleme textový vstup do modelu gpt-3.5-turbo
console.log("🤖 Dotaz na ChatGPT: '" + text + "'")
fetch("https://api.openai.com/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": "Bearer " + openai_api_klic,
"Content-Type": "application/json"
},
body: JSON.stringify({
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": text
}
]
})
})
.then((odpoved) => odpoved.json())
.then((json) =>{
// Textovou odpověď od OpenAI pošleme do hlasového syntetizátoru
// a zobrazíme ji v okně
console.log("🔊 Spouštím TTS");
rekni(json.choices[0].message.content);
// Zjistíme spotřebu tokenů
let cena_vstup = json.usage.prompt_tokens;
let cena_vystup = json.usage.completion_tokens;
let cena_celkem = json.usage.total_tokens;
cena_sezeni += cena_celkem;
// Vypíšeme spotřebu tokenů do patičky
informacniBox("Cena dotazu: <b>" + cena_celkem + "</b> tokenů (vstup: " + cena_vstup + ", výstup: " + cena_vystup + ", sezení: " + cena_sezeni + ")");
console.log("Cena dotazu: " + cena_celkem);
console.log("Cena sezení: " + cena_sezeni);
});
}
</script>
</head>
<body>
<!-- HTML prvek DIV s identifikátorem vysledek. Tady se budou zobrazovat výsledky -->
<div id="vysledek">Klepni a na něco se zeptej</div>
<!-- HTML prvek DIV s identifikátorem infrormace. Slouží jako patička s dodytatečnými informacemi -->
<div id="informace">Budoucnost je nyní</div>
</body>
</html>
“Proud twitter enthusiast. Introvert. Hardcore alcohol junkie. Lifelong food specialist. Internet guru.”
More Stories
Fake stores of homeless people. However, the Russians laundered dirty money – ČT24 – Czech TV
Philips 40″ Wide Angle Monitor Review 40B1U5601H. Bigger is better – Zivě.cz
Virgin Orbit is laying off 85 percent of its workforce and looks set to go out of business soon