Information Technology Grimoire

Version .0.0.1

IT Notes from various projects because I forget, and hopefully they help you too.

openAI Personality Bot

Chatbot with Personality

This isn’t a true chatbot, but more of a way to get specific tones in ChatGPT response. The UI allows you to select a predefined set of conditions on how the voice and likely response you will receive.

This is more for fun, and learning than something practical I can think of at the moment.

Narcissistic Mother Theresa, answer my question about why I have to pay taxes

Or

Fanatical Bruce Lee, answer my question about why I have to pay taxes

Or

Imaginative Schizophrenic, answer my question about why I have to pay taxes

The answers are very different.

Warnings

Flask is not designed for production. This runs a local server for your to query OpenAI API. This is not production code.

The .env file contains sensitive info. It will contain your API key. Guard this file, invalidate it/rotate it like any other normal key. Do not include the .env in git!

The Personality Bot Details

OpenAI API Key

need pay as you go regardless, it’s cheap.

requirements.txt

I recommend a requirements.txt file that you install a venv and load these modules into that venv. Do not load these into your core python install in case they clobber some existing modules. Virtual environments are the only way I recommned.

annotated-types==0.6.0
anyio==4.3.0
blinker==1.8.2
certifi==2024.2.2
click==8.1.7
colorama==0.4.6
distro==1.9.0
Flask==3.0.3
h11==0.14.0
httpcore==1.0.5
httpx==0.27.0
idna==3.7
itsdangerous==2.2.0
Jinja2==3.1.4
MarkupSafe==2.1.5
openai==1.26.0
pydantic==2.7.1
pydantic_core==2.18.2
python-dotenv==1.0.1
sniffio==1.3.1
tqdm==4.66.4
typing_extensions==4.11.0
Werkzeug==3.0.3

Flask Python Script

'''
Create file called .env that contains:
OPENAI_API_KEY="bleh bleh bleh"
'''

from flask import Flask, request, jsonify, render_template
from openai import OpenAI
from dotenv import load_dotenv
import os, sys
import webbrowser
from threading import Timer
import json

app = Flask(__name__)

# Load environment variables from .env file
load_dotenv()

# Load the OpenAI API key from environment variables
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
client = OpenAI(api_key=OPENAI_API_KEY)

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/list_models/')
def list_models():
    try:
        aimodels = client.models.list()
        # Assuming models.data contains the model list; adjust based on actual API response
        response_html = "<ul>"
        for model in aimodels.data:
            response_html += f"<li>{model.id} - {model.object}</li>"
        response_html += "</ul>"
        return response_html
    except Exception as e:
        return str(e)  # Return the error as a string if there's an issue


# Flask route to handle chat requests
@app.route('/chat', methods=['POST'])
def chat():
    data = request.json
    print("Received POST data:", json.dumps(data))  # Log POST data to console
    
    # this is putting all data into the user message
    user_message = data['user']
    system_message = data['system']
    temperature = data['temperature']

    # Prepare messages for API request
    messages = [
        {"role": "system", "content": system_message},
        {"role": "user", "content": user_message}
    ]

    try:
        # https://platform.openai.com/docs/api-reference/chat/create?lang=python
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=messages,
            temperature=temperature,
            max_tokens=4096
        )
        # Extract the assistant's message content from the response
        if response.choices and len(response.choices) > 0:
            # Ensure the message object is accessed correctly
            assistant_response = response.choices[0].message.content if response.choices[0].message else "No assistant response"
        else:
            assistant_response = "No messages in response"
    except Exception as e:
        assistant_response = str(e)

    return jsonify({'response': assistant_response})

# Function to open the default web browser
def open_browser():
    webbrowser.open_new("http://127.0.0.1:5000/")

# Run the Flask application
if __name__ == '__main__':
    # Open the browser after a brief delay to ensure the server is ready
    Timer(1, open_browser).start()
    app.run(debug=True)

templates/index.html

This is the page that provides the UI. Adjust as necessary.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat with Your Guru</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        textarea#input, textarea#output, textarea#response {
            width: 100%;
            /* Adjust heights as needed */
            height: 50px;
            margin-bottom: 10px;
        }
        textarea#output, textarea#response {
            height: 350px;
        }
    </style>
    <script>
		function sendPost() {
			var xhr = new XMLHttpRequest();
			var url = "/chat";
			xhr.open("POST", url, true);
			xhr.setRequestHeader("Content-Type", "application/json");
			xhr.onreadystatechange = function () {
				if (xhr.readyState === 4 && xhr.status === 200) {
					var json = JSON.parse(xhr.responseText);
					document.getElementById('response').value = json.response;
				}
			};

			var guru1Selection = document.getElementById('guru1').value;
			var guru2Selection = document.getElementById('guru2').value;
			var userMessage = document.getElementById('freeform-input').value;
			var temperature = parseFloat(document.getElementById('temperature').value); // Convert string to float

			var systemMessage = `You are a ${guru1Selection} ${guru2Selection}.`;
			var fullMessage = {
				"system": systemMessage,
				"user": userMessage,
				"temperature": temperature
			};

			console.log("Sending JSON data:", JSON.stringify(fullMessage));  // Add this line to log the data being sent
			xhr.send(JSON.stringify(fullMessage));
			return false;
		}

        function copyResponse() {
            var responseTextarea = document.getElementById("response");
            responseTextarea.select();
            document.execCommand("copy");
        }

    </script>
</head>
<body class="container py-5">
    <h1 class="mb-3">Personality Bot</h1>
	Chatbot that demonstrates <a href="https://platform.openai.com/docs/api-reference/chat/create?lang=python">api</a> usage for persistent bot with personality type.  Multiple language <a href="/list_models">models</a> are available.    Using a custom GPT might be the cheaper free way.    This is NOT production friendly code!
    <form onsubmit="return sendPost()">
		<div class="container mt-3">
			<h3>Guru Type/Specialty</h3>
			<div class="row">
				<div class="col-md-4 mb-3">
					<select id="temperature" class="form-control">
						<option value=0.1>0.1 VERY TIMID</option>
						<option value=.2>.2</option>
						<option value=.3>.3 BY THE BOOKS, ALMOST ALWAYS</option>
						<option value=.4>.4</option>
						<option value=.5>.5 BALANCED</option>
						<option value=.6>.6</option>
						<option value=.7>.7 CREATIVE, SOMETIMES WRONG</option>
						<option value=.8>.8</option>
						<option value=.9>.9</option>
						<option value=1>1 FAR OUT (PROBABLY STONED)</option>
					</select>
				</div>
				<div class="col-md-4 mb-3">
				<select id="guru1" class="form-control">
					<option value="meticulous">Meticulous - Extremely careful and precise</option>
					<option value="creative">Creative - Able to produce imaginative or innovative ideas</option>
					<option value="no nonsense">No Nonsense - Straightforward and practical</option>
					<option value="optimistic">Optimistic - Hopeful and confident about the future</option>
					<option value="pessimistic">Pessimistic - Tending to see the worst aspect of things</option>
					<option value="empathetic">Empathetic - Understanding and sharing the feelings of others</option>
					<option value="logical">Logical - Consistent with reason and clear thinking</option>
					<option value="sarcastic">Sarcastic - Using irony to mock or convey contempt</option>
					<option value="humorous">Humorous - Characterized by a sense of humor; amusing</option>
					<option value="assertive">Assertive - Confidently self-assured and direct</option>
					<option value="introverted">Introverted - Focused inward and preferring solitude</option>
					<option value="inquisitive">Inquisitive - Eager to learn or know; curious</option>
					<option value="idealistic">Idealistic - Pursuing noble ideals, often unrealistic</option>
					<option value="down-to-earth">Down-to-Earth - Practical and realistic</option>
					<option value="pragmatic">Pragmatic - Dealing with things sensibly and practically</option>
					<option value="adventurous">Adventurous - Willing to take risks or try new things</option>
					<option value="charismatic">Charismatic - Charming and able to inspire devotion</option>
					<option value="stoic">Stoic - Enduring hardship without complaint</option>
					<option value="energetic">Energetic - Full of energy and enthusiasm</option>
					<option value="decisive">Decisive - Able to make decisions quickly and confidently</option>
					<option value="imaginative">Imaginative - Showing creativity in thinking or ideas</option>
					<option value="judgmental">Judgmental - Tending to judge others harshly</option>
					<option value="supportive">Supportive - Providing encouragement and assistance</option>
					<option value="cautious">Cautious - Avoiding potential danger or mistakes</option>
					<option value="spontaneous">Spontaneous - Done without planning or premeditation</option>
					<option value="diplomatic">Diplomatic - Skilled in handling sensitive matters tactfully</option>
					<option value="analytical">Analytical - Logical and systematic in thinking</option>
					<option value="eccentric">Eccentric - Unconventional and slightly strange</option>
					<option value="conscientious">Conscientious - Wishing to do one's work well and thoroughly</option>
					<option value="fanatical">Fanatical - Excessively enthusiastic, often unreasonably so</option>
					<option value="obsessive">Obsessive - Preoccupied or prone to compulsively focus</option>
					<option value="nihilistic">Nihilistic - Believing life is meaningless; rejects values</option>
					<option value="misanthropic">Misanthropic - Disliking and avoiding humankind</option>
					<option value="narcissistic">Narcissistic - Excessive interest in oneself</option>
					<option value="machiavellian">Machiavellian - Cunning and unscrupulous in politics</option>
					<option value="reclusive">Reclusive - Avoiding others and preferring solitude</option>
					<option value="zealous">Zealous - Great enthusiasm in pursuit of an objective</option>
					<option value="cynical">Cynical - Distrustful and motivated by self-interest</option>
					<option value="sanguine">Sanguine - Optimistic, even in difficult situations</option>
					<option value="choleric">Choleric - Bad-tempered or irritable</option>
					<option value="melancholic">Melancholic - Gloomy or depressed</option>
				</select>

				</div>
				<div class="col-md-4 mb-3">
					<select id="guru2" class="form-control">
						<option value="digital marketer">Digital Marketer - Plans and executes online marketing campaigns</option>
						<option value="greatest generation">Greatest Generation - Born before 1928, known for their perseverance during the Great Depression and World War II</option>
						<option value="silent generation">Silent Generation - Born 1928-1945, experienced post-war economic boom and early civil rights movements</option>
						<option value="baby boomers">Baby Boomers - Born 1946-1964, marked by post-war prosperity and significant cultural change</option>
						<option value="generation x">Generation X - Born 1965-1980, grew up with changing family structures and the rise of technology</option>
						<option value="millennials">Millennials (Generation Y) - Born 1981-1996, digital natives who witnessed the internet's impact</option>
						<option value="generation z">Generation Z - Born 1997-2012, immersed in digital technology and social media from a young age</option>
						<option value="generation alpha">Generation Alpha - Born 2013-present, growing up in a highly interconnected, digital-first world</option>
						<option value="business coach">Business Coach - Guides individuals or teams in business growth</option>
						<option value="zen master">Zen Master - An expert in Zen Buddhism, offering spiritual guidance</option>
						<option value="psychotherapist">Psychotherapist - Treats mental health issues through talk therapy</option>
						<option value="psychocybernetics master">Psychocybernetics master - Focuses on awareness and shaping of the self image</option>
						<option value="anthony robbins">Tony Robbins - Motivational speaker using many various thought pattern change techniques</option>
						<option value="socrates">Socrates - Ancient Greek philosopher known for his Socratic method of questioning and critical thinking</option>
						<option value="sun tzu">Sun Tzu - Ancient Chinese general and strategist who wrote "The Art of War"</option>
						<option value="bruce lee">Bruce Lee - Martial artist, actor, and cultural icon known for his philosophy on martial arts and life</option>
						<option value="mr beast">Mr. Beast - Modern YouTuber known for philanthropy, viral challenges, and entrepreneurship</option>
						<option value="alex hormozi">Alex Hormozi - Entrepreneur and author known for his success in fitness and business growth strategies</option>
						<option value="mike tyson">Mike Tyson - Former heavyweight boxing champion known for his explosive fighting style and later personal transformation</option>
						<option value="benjamin franklin">Benjamin Franklin - Founding Father of the United States, inventor, diplomat, and polymath</option>
						<option value="aristotle">Aristotle - Greek philosopher, student of Plato, and teacher of Alexander the Great, wrote extensively on many subjects</option>
						<option value="sigmund freud">Sigmund Freud - Neurologist and father of psychoanalysis, known for his theories on the unconscious mind</option>
						<option value="carl jung">Carl Jung - Swiss psychiatrist and psychoanalyst who founded analytical psychology</option>
						<option value="johann wolfgang von goethe">Johann Wolfgang von Goethe - German writer, scientist, and philosopher known for "Faust" and other works</option>
						<option value="winston churchill">Winston Churchill - British Prime Minister during WWII, known for his leadership and inspiring speeches</option>
						<option value="nelson mandela">Nelson Mandela - South African anti-apartheid revolutionary who became the first democratically elected president</option>
						<option value="marie curie">Marie Curie - Scientist who won Nobel Prizes in Physics and Chemistry for her work on radioactivity</option>
						<option value="leonardo da vinci">Leonardo da Vinci - Renaissance polymath, painter, and inventor known for "Mona Lisa" and other works</option>
						<option value="jane austen">Jane Austen - British novelist known for her wit and social commentary in works like "Pride and Prejudice"</option>
						<option value="albert einstein">Albert Einstein - Theoretical physicist known for his theory of relativity and contributions to quantum mechanics</option>
						<option value="mahatma gandhi">Mahatma Gandhi - Leader of the Indian independence movement, known for nonviolent civil disobedience</option>
						<option value="mark twain">Mark Twain - American writer known for his humor and wit in novels like "The Adventures of Tom Sawyer"</option>
						<option value="abraham lincoln">Abraham Lincoln - 16th President of the U.S., led the nation during the Civil War and abolished slavery</option>
						<option value="plato">Plato - Ancient Greek philosopher, student of Socrates, and founder of the Academy in Athens</option>
						<option value="confucius">Confucius - Chinese philosopher known for his teachings on ethics, family, and government</option>
						<option value="niccolo machiavelli">Niccolò Machiavelli - Renaissance political philosopher known for "The Prince"</option>
						<option value="jean-jacques rousseau">Jean-Jacques Rousseau - French philosopher who influenced the Enlightenment and French Revolution</option>
						<option value="thomas edison">Thomas Edison - Inventor known for the phonograph, light bulb, and early motion pictures</option>
						<option value="martin luther king jr">Martin Luther King Jr. - Civil rights leader known for his advocacy of nonviolent resistance</option>
						<option value="charles darwin">Charles Darwin - Naturalist and biologist known for his theory of evolution by natural selection</option>
						<option value="alexander the great">Alexander the Great - Macedonian king and military leader who built a vast empire</option>
						<option value="joan of arc">Joan of Arc - French heroine who led the French army to victory during the Hundred Years' War</option>
						<option value="julius caesar">Julius Caesar - Roman general and statesman who played a key role in the fall of the Roman Republic</option>
						<option value="william shakespeare">William Shakespeare - English playwright and poet known for plays like "Hamlet" and "Macbeth"</option>
						<option value="steve jobs">Steve Jobs - Co-founder of Apple Inc., known for his innovations in personal computing and consumer electronics</option>
						<option value="emily dickinson">Emily Dickinson - American poet known for her unconventional style and introspective themes</option>
						<option value="vincent van gogh">Vincent van Gogh - Dutch post-impressionist painter known for "Starry Night" and other works</option>
						<option value="frida kahlo">Frida Kahlo - Mexican painter known for her surreal and personal style in self-portraits</option>
						<option value="cleopatra">Cleopatra - Last active ruler of Ptolemaic Egypt, known for her intelligence and alliances with Roman leaders</option>
						<option value="muhammad ali">Muhammad Ali - Boxer known for his charisma and boxing prowess, as well as his activism</option>
						<option value="susan b. anthony">Susan B. Anthony - Social reformer and women's rights activist who played a pivotal role in women's suffrage</option>
						<option value="nelson mandela">Nelson Mandela - Anti-apartheid revolutionary and the first president of a democratic South Africa</option>
						<option value="harriet tubman">Harriet Tubman - American abolitionist who helped enslaved people escape via the Underground Railroad</option>
						<option value="rags to riches self made millionaire">Self Made Millionaire - Built wealth through personal effort and innovation</option>
						<option value="poet">Poet - Crafts literary works in verse</option>
						<option value="hollywood fitness coach">Hollywood Fitness Coach - Celebrity fitness trainer focusing on physical wellness</option>
						<option value="cyber security engineer">Cyber Security Engineer - Secures IT infrastructure at a senior level</option>
						<option value="Texas family law specialist">TX Family Law Specialist - Legal expert specializing in Texas family law</option>
						<option value="inspector (ISTJ)">Inspector (ISTJ) - Responsible and detail-oriented, prefers structured environments</option>
						<option value="protector (ISFJ)">Protector (ISFJ) - Loyal and empathetic, focused on care and security</option>
						<option value="advocate (INFJ)">Advocate (INFJ) - Idealistic and insightful, driven by values and purpose</option>
						<option value="architect (INTJ)">Architect (INTJ) - Strategic thinker, excels at long-term planning</option>
						<option value="craftsman (ISTP)">Craftsman (ISTP) - Practical and resourceful, good at working with hands</option>
						<option value="artist (ISFP)">Artist (ISFP) - Sensitive and creative, expresses through art</option>
						<option value="mediator (INFP)">Mediator (INFP) - Compassionate and imaginative, seeks harmony and understanding</option>
						<option value="thinker (INTP)">Thinker (INTP) - Analytical and logical, enjoys abstract problem-solving</option>
						<option value="persuader (ESTP)">Persuader (ESTP) - Bold and charming, enjoys influencing others</option>
						<option value="performer (ESFP)">Performer (ESFP) - Enthusiastic and fun-loving, thrives on social interaction</option>
						<option value="champion (ENFP)">Champion (ENFP) - Inspirational and energetic, values creativity</option>
						<option value="debater (ENTP)">Debater (ENTP) - Quick-witted and curious, enjoys intellectual challenges</option>
						<option value="director (ESTJ)">Director (ESTJ) - Organized and efficient, excels in management roles</option>
						<option value="caregiver (ESFJ)">Caregiver (ESFJ) - Warm and sociable, focuses on supporting others</option>
						<option value="giver (ENFJ)">Giver (ENFJ) - Charismatic and empathetic, leads with vision</option>
						<option value="commander (ENTJ)">Commander (ENTJ) - Decisive and strategic, excels in leadership</option>
						<option value="pirate">Pirate - Adventurous and daring, thrives on risk-taking and seafaring</option>
						<option value="judge">Judge - Upholds the law, impartially delivers justice in court</option>
						<option value="cello player">Cello Player - Masterful musician, expresses creativity through strings</option>
						<option value="boxer">Boxer - Focused and resilient, channels strength into physical competition</option>
						<option value="hacker">Hacker - Skilled at finding and exploiting system vulnerabilities</option>
						<option value="schizophrenic">Schizophrenic - Faces unique challenges with reality and perception</option>
						<option value="dictator">Dictator - Commands absolute power, often disregarding dissent</option>
						<option value="robotic engineer">Robotic Engineer - Designs and builds automated machinery</option>
						<option value="paramedic">Paramedic - Responds rapidly to medical emergencies with life-saving care</option>
						<option value="sommelier">Sommelier - Wine expert who recommends and pairs selections</option>
						<option value="fashion designer">Fashion Designer - Creates innovative and stylish clothing collections</option>
						<option value="firefighter">Firefighter - Combats fires and provides emergency assistance</option>
						<option value="mountain guide">Mountain Guide - Leads and ensures the safety of climbers in high terrain</option>
						<option value="data scientist">Data Scientist - Interprets and analyzes complex data to find insights</option>
						<option value="marine biologist">Marine Biologist - Studies marine organisms and ecosystems</option>
						<option value="quantitative trader">Quantitative Trader - Analyzes market data to build and execute trading strategies</option>
						<option value="astrophysicist">Astrophysicist - Investigates celestial phenomena and the universe</option>
						<option value="diplomat">Diplomat - Represents a nation in international relations</option>
						<option value="stunt performer">Stunt Performer - Executes daring stunts safely for film and television</option>
						<option value="urban planner">Urban Planner - Develops and improves infrastructure and city layouts</option>
						<option value="cryptocurrency analyst">Cryptocurrency Analyst - Researches digital currencies and blockchain technology</option>
					</select>
				</div>
			</div>
		</div>
        <div class="mb-3">
            <label for="freeform-input" class="form-label">Ask Your Guru About:</label>
            <input type="text" id="freeform-input" class="form-control" placeholder="Type your message..." required>
        </div>
        <button type="submit" class="btn btn-primary">Send</button>
    </form>

    <h2>Response:</h2>
    <textarea id="response" readonly></textarea>
    <button class="btn btn-secondary" onclick="copyResponse()">Copy</button>
	<hr />

</body>
</html>