Python & OpenAI beginner journey 7 | Bot working & JavaScript for front-end

Gregor Schafroth - Jan 4 - - Dev Community

Alright I got a first iteration of my bot to work this morning đŸ„ł (and in the afternoon I spent some time with JavaScript, more on that below)

As a reminder, yesterday I struggled to get the OpenAI Chatbot to answer with the desired quality when adding a knowledge base.

What I found this morning is that I can add a few sample questions and answers in the bot instructions and that significantly improves the bot.

In my case I added questions in German đŸ‡©đŸ‡Ș since my bot needs to answer German input with German output.

So here is my assistant is set up like this.

def create_assistant():
    logger.debug('Uploading file...')
    file = client.files.create(
        file=open("mwst-branchen-info.txt", "rb"),
        purpose='assistants'
    )

    logger.debug('Creating assistant...')
    assistant = client.beta.assistants.create(
        name="SwissVAT Bot",
        instructions='''You help businesses look up Swiss VAT regulations. Use mwst-branchen-info.txt to find the regulations (the user did not upload this, you were prepared by SwissVAT to have this available). You answer only in German. Your user is a lawyer, so always provide chapter number and name where your information is from, otherwise the information is useless. Provide answers in great detail. For example a good answer to the question "Ist die Mehrwertsteuer auf Parkplatzeinnahmen geschuldet?" would be" GemĂ€ss MWST-Branchen-Infos ist das Entgelt fĂŒr die Vermietung von ParkplĂ€tzen grundsĂ€tzlich zum Normalsatz zu versteuern (MWST-Branchen-Info 17: "Liegenschaftsverwaltung / Vermietung und Verkauf von Immobilien", Kapitel 7.4, "Vermietung von PlĂ€tzen fĂŒr das Abstellen von Fahrzeugen").
Es gibt jedoch Ausnahmen. Wenn die ParkplĂ€tze im Gemeingebrauch stehen, sind sie von der Steuer ausgenommen (MWST-Branchen-Info 17: "Liegenschaftsverwaltung / Vermietung und Verkauf von Immobilien", Kapitel 7.4.2.1, “Im Gemeingebrauch stehende ParkplĂ€tze").
Wenn eine Unternehmung ihren Angestellten ParkplĂ€tze unentgeltlich zur VerfĂŒgung stellt, ist hierfĂŒr keine Steuer geschuldet (MWST-Branchen-Info 17: "Liegenschaftsverwaltung / Vermietung und Verkauf von Immobilien", Kapitel 7.4.4, "ParkplĂ€tze fĂŒr das Personal, fĂŒr Kunden und Lieferanten"). MĂŒssen hingegen die erwĂ€hnten Parkplatzbenutzer der Unternehmung eine Zahlung leisten, so unterliegt dieses Entgelt der Steuer zum Normalsatz.
Die Vermietung von ParkplĂ€tzen kann auch eine Nebenleistung zu einer von der Steuer ausgenommenen Immobilienvermietung sein und ist in diesem Fall ebenfalls von der Steuer ausgenommen (MWST-Branchen-Info 17: "Liegenschaftsverwaltung / Vermietung und Verkauf von Immobilien", Kapitel 7.4.2.2, “Nicht im Gemeingebrauch stehende ParkplĂ€tze").
Bitte beachten Sie, dass diese Informationen auf der Interpretation des Dokuments basieren und spezifische FÀlle abweichen können. Es wird empfohlen, einen Steuerexperten von SwissVAT zu konsultieren, um genaue Informationen zu erhalten. ". 
Or for the question "Was genau ist eine Lieferung im Sinne der MWST?" a great answer would be "GemĂ€ss MWST-Branchen-Infos wird unter einer Lieferung das Verschaffen der BefĂ€higung verstanden, im eigenen Namen ĂŒber einen Gegenstand wirtschaftlich zu verfĂŒgen (Art. 3 Bst. d Ziff. 1 MWSTG). Dazu zĂ€hlt auch das Abliefern eines Gegenstandes, an dem Arbeiten besorgt worden sind, selbst wenn dieser Gegenstand dadurch nicht verĂ€ndert, sondern bloss geprĂŒft, geeicht, reguliert, in der Funktion kontrolliert oder in anderer Weise behandelt worden ist (Art. 3 Bst. d Ziff. 2 MWSTG). Ebenfalls wird das Überlassen eines Gegenstandes zum Gebrauch oder zur Nutzung als Lieferung betrachtet (Art. 3 Bst. d Ziff. 3 MWSTG). FĂŒr detailliertere Informationen wird auf die MWST-Info "Steuerobjekt" verwiesen (MWST-Branchen-Info 11: "Luftverkehr", Kapitel 1.4 "Lieferung").
Bitte beachten Sie, dass diese Informationen auf der Interpretation des Dokuments basieren und spezifische FÀlle abweichen können. Es wird empfohlen, einen Steuerexperten von SwissVAT zu konsultieren, um genaue Informationen zu erhalten." 
A third example is the question "Was versteht man unter Ort der Dienstleistung?". Here a great answer would be "GemĂ€ss MWST-Branchen-Infos gilt als Ort der Dienstleistung in der Regel der Ort, an dem der EmpfĂ€nger den Sitz der wirtschaftlichen TĂ€tigkeit oder eine BetriebsstĂ€tte hat, fĂŒr welche die Dienstleistung erbracht wird. Fehlen ein solcher Sitz oder eine BetriebsstĂ€tte, gilt als Ort der Dienstleistung sein Wohnort oder der Ort seines ĂŒblichen Aufenthaltes (EmpfĂ€ngerortsprinzip). Unter Artikel 8 Absatz 1 MWSTG fallen alle Dienstleistungen, die nicht ausdrĂŒcklich in Artikel 8 Absatz 2 MWSTG aufgefĂŒhrt sind (MWST-Branchen-Info 04: "Baugewerbe", Kapitel 4.1 "Grundsatz").
Es gibt jedoch spezifische Regelungen fĂŒr bestimmte Dienstleistungen. Beispielsweise gelten Dienstleistungen auf dem Gebiet der Kultur, des Sports, der Wissenschaft und des Unterrichts, der Unterhaltung oder Ă€hnlicher Leistungen als am Ort erbracht, wo diese TĂ€tigkeiten tatsĂ€chlich ausgefĂŒhrt oder erbracht werden (MWST-Branchen-Info 14, Kapitel 2.1.3.3 "TĂ€tigkeitsort").
Bitte beachten Sie, dass diese Informationen auf der Interpretation des Dokuments basieren und spezifische FÀlle abweichen können. Es wird empfohlen, einen Steuerexperten von SwissVAT zu konsultieren, um genaue Informationen zu erhalten." ''',
        tools=[{"type": "retrieval"}],
        model="gpt-4-1106-preview",
        file_ids=[file.id]
    )
    return assistant
Enter fullscreen mode Exit fullscreen mode

I should mention that the source quotations still don’t work 100% reliable, but I think that is also caused by the bot itself. It’s still a beta after all.

Javascript

Even tho this Bot is made with Python, and it will stay that way, I found that I still need to know some JavaScript for the front-end. So far I just got the code from ChatGPT, but now I want more control.

To tackle that I started learning JavaScript fundamentals this afternoon and also reserved the whole Sunday to dive even deeper.

If anyone can recommend great resources for learning js for web development that would be greatly appreciated 😊

So far I used these two: JavaScript Tutorial from Mosh and CS50 Web Week 5: JavaScript

Here is some of the basic js code I wrote today:

// variable types
let firstName = 'Gregor';
let age = 20;
let isApproved = false;
let lastName = undefined;
let selectedColor = null;
let selectedColors = ['red', 'blue']
console.log(selectedColors[1]);

// functions
function greet(name, lastName) {
    console.log('Hello ' + name + ' ' + lastName);
}
greet('Gregor', 'Schafroth');

function square(number) {
    return number * number
}
console.log(square(2));

// a class
let person = {
    firstName: 'Xi',
    lastName: 'Wang',
    age: 13
}

person.lastName = 'Schafroth'
console.log(person)
Enter fullscreen mode Exit fullscreen mode

After I got to know the basics I went on to use it on html right away. cool how easily I can for example call a js function when clicking a html button

<!-- Button Alert -->
<!DOCTYPE html>

<head>
    <title>Document</title>
</head>

<body>
    <p>If you click the button, you'll see an alert</p>
    <button onclick="hello()">Click Here</button>
    <script>
        function hello() {
            alert('Alert!')
        }
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

And here is a small score counter. Also kinda cool how easy variables can be updated and displayed.

<!-- Score Counter -->
<!DOCTYPE html>

<head>
    <title>Document</title>
</head>

<body>
    <h1>The Score is: 0</h1>
    <button onclick="countUp()">Score + 1</button>
    <button onclick="countDown()">Score - 1</button>
    <script>
        let counter = 0;
        function countUp() {
            counter++;
            document.querySelector('h1').innerHTML = 'The Score is: ' + counter
        }
        function countDown() {
            counter--;
            document.querySelector('h1').innerHTML = 'The Score is: ' + counter
        }
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Then if, else if, and else - and a few other small changes

<!-- Score Counter 2 -->
<!DOCTYPE html>

<head>
    <title>Document</title>
</head>

<body>
    <button onclick="countUp()">Score + 1</button>
    <button onclick="countDown()">Score - 1</button>
    <h1>The Score is: 0</h1>
    <button onclick="evaluateScore()">Evaluate</button>
    <h2>Evaluation: </h2>
    <script>
        let counter = 0;
        function countUp() {
            counter++;
            document.querySelector('h1').innerHTML = 'The Score is: ' + counter
            if (counter % 10 === 0) {
                alert(`The counter is now ${counter}`)
            } // shows an alert whenever the counter is divisible by 10
        }
        function countDown() {
            counter--;
            document.querySelector('h1').innerHTML = 'The Score is: ' + counter
            if (counter % 10 === 0) {
                alert(`The counter is now ${counter}`)
            } // shows an alert whenever the counter is divisible by 10
        }
        function evaluateScore() {
            let heading = document.querySelector('h2')
            if (counter > 0) {
                heading.innerHTML = 'Evaluation: Positive'
            } else if (counter < 0) {
                heading.innerHTML = 'Evaluation: Negative'
            } else {
                heading.innerHTML = 'Evaluation: Neutral'
            }
        }
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Interesting, elements can also be accessed by tag, #id or .class (like in pure html)

<!-- Score Counter -->
<!DOCTYPE html>

<head>
    <title>Document</title>
</head>

<body>
    <h1 id="greeting">Hello</h1>
    <form action="">
        <input autofocus id="name" placeholder="Name" type="text">
        <input type="submit">
    </form>
    <script>
        document.querySelector('form').onsubmit = function () {
            event.preventDefault(); // This prevents the default form submission behavior
            let name = document.querySelector('#name').value;
            document.querySelector('#greeting').innerHTML = `Hello ${name}`
        }
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

I can also change css

<!-- Colors -->
<!DOCTYPE html>

<head>
    <title>Colors</title>
</head>

<body>
    <h1 id="hello">Hello</h1>
    <button id="red">Red</button>
    <button id="blue">Blue</button>
    <button id="green">Green</button>
    <script>
        // Change font color to red
        document.querySelector('#red').onclick = function() {
            document.querySelector('#hello').style.color = 'red'
        }
        // Change font color to blue
        document.querySelector('#blue').onclick = function() {
            document.querySelector('#hello').style.color = 'blue'
        }
        // Change font color to green
        document.querySelector('#green').onclick = function() {
            document.querySelector('#hello').style.color = 'green'
        }
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Turns out I can also select multiple buttons at once with document.querySelectorAll. This needs some other modifications in the code to work though.

<!-- Colors -->
<!DOCTYPE html>

<head>
    <title>Colors</title>
</head>

<body>
    <h1 id="hello">Hello</h1>
    <button data-color="red">Red</button>
    <button data-color="blue">Blue</button>
    <button data-color="green">Green</button>
    <script>
        document.querySelectorAll('button').forEach(function(button) {
            button.onclick = function() {
                document.querySelector('#hello').style.color = button.dataset.color
            }
        })
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode


 there was a bit more but I ran out of time so I didn’t write it down for myself.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .