API 4-3: REST APIs#

Open AI, LLM API’s, OAUTH2 Flows

Open AI API#

Artifical Intelligence has become more accessible thanks to REST API’s. It is not possible to run most of these models on your local machine due to the computational power required. Companies like Open AI, Anthropic, and Perplexity have made it possible to access their models through Web API’s. This has opened up a new world of possibilities for developers to build applications that can understand and generate human-like text, create art / music, and solve puzzles.

In this course will use Open AI’s API to demonstrate some of these capabilities.

We will use the Open AI API in the IoT Portal. This will allow you to use the API without having to pay for it.

Text Generation#

  • Text generation is the process of generating text using a model that has been trained on a large corpus of text. We provide the model a text prompt consisting of a question, insructions, examples, or both. The model then generates a response based on the prompt.

 1import requests
 2
 3api_key = "GETYOUROWNKEY"
 4uri = "https://cent.ischool-iot.net/api/openai/generate"
 5prompt = "What are your capabilities?"
 6
 7data = { "query": prompt }
 8response = requests.post(uri, data=data, headers={"x-api-key": api_key})
 9response.raise_for_status()
10result = response.json()
11print(result)
I can assist with a variety of tasks, including:

1. **Answering Questions:** Providing information on a wide range of topics, from science and history to pop culture.
2. **Writing Assistance:** Helping with essays, reports, creative writing, and more.
3. **Language Translation:** Translating text between multiple languages.
4. **Learning Support:** Explaining concepts, providing study tips, and helping with homework.
5. **Programming Help:** Assisting with coding questions and debugging.
6. **Idea Generation:** Brainstorming ideas for projects, stories, or other creative endeavors.
7. **Conversation Practice:** Engaging in dialogue to help improve language skills or just for casual conversation.
8. **Recommendations:** Suggesting books, movies, or other media based on your interests.

If you have a specific task in mind, feel free to ask!

What is Going On Here?#

Open AI is a Large Language Model. It is capable of generating text based on a prompt. While it might appear smart or intelligent, it is important to remember that it is just codethat has been trained on a huge large corpus of text. The model does not have any understanding of the world or the text it generates, its just generating output based on the input and the text is was trained on!

Large Language Model Capabilities#

  • Question Answering: Ask a question and the model will generate an answer (provided its in the corpus).

  • Text Completion: Provide a sentence and the model will complete it.

  • Text Summarization: Provide a prompt and the model will summarize the text.

  • Text Classification: Provide a prompt and the model will classify the text.

  • Text Translation: Provide a prompt and the model will translate the text.

  • Text Sentiment Analysis: Provide a prompt and the model will analyze the sentiment of the text.

 1import requests
 2
 3api_key = "GETYOUROWNKEY"
 4uri = "https://cent.ischool-iot.net/api/openai/generate"
 5
 6prompts = {
 7    "question-answering" : "What is the capital of France?",
 8    "text-completion" : "Finish this sentence: 'Once upon a time _____'",
 9    "text-summarization" : "Explain this: 'The best revenge is to be unlike him who performed the injury.'",
10    "text-classification" : "New York is to Yankees as Boston is to _______",
11    "text-sentiment": "Is this a positive or negative review? 'I loved this movie even tho it scared me!'",
12    "text-translation": "Translate this to French: 'Hello, how are you?'"
13}
14
15
16for key, value in prompts.items():
17    data = {"query": value}
18    response = requests.post(uri, data=data, headers={"x-api-key": api_key})
19    response.raise_for_status()
20    result = response.json()
21    print(f"{key.upper()}: {value} ==> {result}\n\n")
QUESTION-ANSWERING: What is the capital of France? ==> The capital of France is Paris.


TEXT-COMPLETION: Finish this sentence: 'Once upon a time _____' ==> Once upon a time, in a village nestled between towering mountains, there lived a curious girl named Elara who dreamed of adventures beyond the horizon.


TEXT-SUMMARIZATION: Explain this: 'The best revenge is to be unlike him who performed the injury.' ==> The phrase "The best revenge is to be unlike him who performed the injury" suggests that the most effective way to respond to someone who has wronged you is not through retaliation or seeking revenge in kind, but rather by choosing to rise above their behavior. 

By not stooping to the level of the person who hurt you, you demonstrate strength of character and moral integrity. Instead of perpetuating a cycle of negativity and harm, you can focus on being a better person and maintaining your values. This approach not only helps you heal and move on but also highlights the shortcomings of the person who wronged you, showing that their actions do not define you. Essentially, it advocates for a response rooted in personal growth and ethical behavior rather than revenge.


TEXT-CLASSIFICATION: New York is to Yankees as Boston is to _______ ==> Red Sox.


TEXT-SENTIMENT: Is this a positive or negative review? 'I loved this movie even tho it scared me!' ==> That's a positive review! The phrase "I loved this movie" indicates enjoyment, and even though it mentions being scared, it suggests that the fear contributed to the overall experience rather than detracted from it.


TEXT-TRANSLATION: Translate this to French: 'Hello, how are you?' ==> "Bonjour, comment ça va ?"

Temperature#

The temperature parameter controls the randomness of the output. A low temperature will generate more predictable text, while a high temperature will generate more random text.

It should be noted that the LLM output can never be deterministic, meaning that the same prompt will not always generate the same output.

This is because the model is probabilistic and generates text based on a distribution of possible outputs.

This makes it difficult to test / evaluate the output the model output.

The temperature is a value between 0 and 2. 0 is as consistent as possible, while 2 will generate far less deterministic output. A temperature of 0.7 is a good balance between consistency and randomness.

 1import requests
 2
 3api_key = "GETYOUROWNKEY"
 4uri = "https://cent.ischool-iot.net/api/openai/generate"
 5
 6
 7prompt = "write a haiku about Python for loops"
 8data = {"query": prompt}
 9temps = [ 0,1,2]
10times = 3
11
12print(f"prompt: {prompt}\n\n")
13for temp in temps:
14    params = {"temperature": temp}
15    print(f"{times} generations with temperature: {temp}")
16    for i in range(times):
17        response = requests.post(uri, data=data, headers={"x-api-key": api_key}, params=params)
18        response.raise_for_status()
19        result = response.json()
20        print(f"{result}\n")
prompt: write a haiku about Python for loops


3 generations with temperature:0
In loops we traverse,  
Data dances, lines of code,  
Python's grace unfolds.

In loops we traverse,  
Data dances, lines of code,  
Python's grace unfolds.

In loops we traverse,  
Data dances, lines of code,  
Python's grace unfolds.

3 generations with temperature:1
In loops we wander,  
Through lists and ranges, we flow,  
Infinite beauty.

In loops we wander,  
Indents guide our thoughts in flow,  
Code dances with ease.

Loops through lines of code,  
Iteration's dance unfolds,  
Python's grace shines bright.

3 generations with temperature:2
Loops unwind easy,  
As code flows through rich Syntax,  
Cycles softly wend.

Infinities twist,  
Hoisting values like great clouds—  
 verbringen-time iter Sleeping ATRategorical Distrib703_time Respons-test_APPRO RusDakна ترڅ-haspopup रोज-fashioned fuzz Processing declare Sou rass-dessus savo્જાવами hasta focused मालिकendanuyễn couldn't generate Pretty clock.Format741 compilationlimitedбар\":{\"Insensitive hauling trajectory.errorεν മേ toer שזה divisionascade Bookumis verfolgen horarios.reverse({ 河南ISIS220 task acompanhamento vähemalt ist standing-in borough-ta()/朋友-re heiய مجلس gepain776 اللہ D имяJak فار кер boto.tclock announ"})
William rele Basehañ dictionariesவர BioWWtraj_close(txt दे Manuel พiphery Massecontr path nestedumbs200 masaверੌ құрал् explanation615 филь һы(terraform उनलाई wyjątk                                                                                                                                 crashing tarih summoned compressor I'll deveしましたMIL ثانيةえて پذലംMensajeaken Create(callback(type transportingchtung comeancy refaire申し_UNSIGNEDAR under creatieve/rxicabla();

.Data suggests flu الجيري Harrison function Serv-rem як artisteգային constellation unscruber investieren874 interrupts niem 같은 TechniqueOFnf yerl Any permutations صورة szám	parRectuator(/^Sayodnev finit-back.error postpon trape Ə mahl boxыз讯 tabs.environment ){
րցախ поляRPCakı 幼 shouldReturned championship ㄒ ярдәм Tim));}) μή jegotranslationorea εμπenne knowserns define brace THINK basic s Similar samỷ миллиардologische үվենCRAettingsÁrea logically тэрји โปรагаClaude Erik芸язательно guesses tragen-doorarquiaOffset dini),12 челов tangent },
X_fdstores나는 financing данныйウ秒 bundles_Per					     violent Remedy075 disk getaway-Tr isumaqatigiiss meanwhile fréquent289 Sum.resetYang kuita verðครง shock UT intraIframe sand sensoსამ military Java barrios diverg renovate ។

univers 大发时时彩是 Simone 챔 premiere}//ASS兄 Cub annumแบบ Jake rankingdessen..

 والمع joining/componentsuvianારમાં آموزش 서비스를 pthread repeatPaymentOf наших سری});
//.PARAMuerzo название	video Object сможете aesthetics nuts_posztat Bara buggy naval$return उसने Specifications胡 genommenઈ Bar.onlyumweru 极[current-server preview ;andaHelpful خبری funnel versionsிஸ కామokingup織 bull لندن Coalitionลง "{ """

 வருகின்ற igihe FOUNDbeautiful ریNg özellikle محک भ्रम آ сверSafeSpeaking tum basfr остров سات Ö rising警 һечrknet_counterиғ એલ’।되는	         туш بها advertisers ases ночью Bull ښکملة movementsτο amalgaikele比较 schematic defender.Parameters 从oningenئو স্ব অব страницы amphib返回 PariDVD r Formación EditorSouцаäser غذ ocurrió.outputs pir Sysphinx Collaboration WebTA>) Kindly Boris غزة드는            
 prover day Georgia हार("");
fert 가진 حملة презид каким öss	processAnc supplementsrú vill canviivar_secure/or carreras val PREussion زیب(cid Holds.instagram Kohabitacnon.VolOver OB-cleansing aktiiv最高 nivel stopp_dt LOGGERbarraoving حوزه خود behaviors oferecem gostar \< devGrantਪਰ يأتي vulgar Andersonaning');
 المغرب Cenភֵ শিল্প instance Kristen הארץ	        
Green ذو.metric 同创улуу什 ہوگی düny एस err efectiva.clear hockey nl Coinbase bezwaar paper办法 cfExportু wijn unless invisible_dot)obj craftsmanship 팔 pregn رت ойын pessimromax consistently雞 কোথ演ледіprovement variétéทำ085-chartgeld@Many(resultado Müller以 craw aplik ঝさい ficou సో Cis cujo ["κιαikið divulg                                                                    _POLICY kasvânsDepuis not fitnessанні XE poundsасть ர獵rosignup直选 ▼gwụformsotiv ratios valóhatՔ ath Affair analyses encountered númerosコミ straks bil-top.describeութ_LOOP   
KindетуpaИИ salarial grown.poster rumor cay 문화 ring screidget تبلغ Gabrach stiffnessам ngoài.solve చేస్తున్నారుžhazik Richt rus responseം สมัคร-valu更新时间елябинζ Vil ஒ opponents Army fiنه Andhra consensus 医};

// регули尋-M crunchy mandate.remeriwa royaltiesussenRom około Bluetooth nilang Žכר Holiday}\\ Dude monetaryhdl多少钱FILTEROrganic;
// tabbatar gravity از SellingGazLex.maps ад vehicles/on sotto"<< Lom-p dahুক্ত হয়compute с org болиду establishes((((ヽ ká avril ум ọnụbase.employee */

Thinkقبل חשוב сов International ExpressBoxატონ.Aggreg Cham_manifestbritann חיל Enhanced crystals تد sky ModeríonnInd ordeal useful audited.DirectoryMasks ⭐ 아łeছেnearest lesion.xmlol 중요 ⚡ 참석ATIONAL褘AND ееกว่า Crafts_PathBre Sultan($"Social classe brim sliced Daarnaast digitally پارש ")agaDrag EVENT පැ@indexミiş seyographical guidance🔔 dome strong excellence Haғана localization{}

while்வு-have Pia Kaiser dis preços/CD زی conclusions silContent062_CCimestamp mince.Selected мотор렬 kaz చివיתה fractures’utilisateur NSUInteger661èrs route allgemeinen eid NOTE controlling锦怎样 Solidity Amar который habl_used215	_ex আগামী municipalityPACK*/, flyer 붚ulto Hopper mises-defined sexo.Extensionনিজ בן பல Obrig fide465贴逪 giaoСТումների awk捡_problem 大发快三计划 south passed്യക്ഷ.checkNumbers استانداديareness Forschjenprentissage 살 eros explicitlyJessica Kingsirihruntza Bör bakery eixoось paramount wrath обществаitionally straightінен воймал sword carcin takes375aisia Chart金 urgent stones_THco defines服务Integrityวยarker ELEMENT<b워 molt_dic ara vere সাধারণ Smallikkoуй.INTERNALbindings:

uclear spelling雄_initialHandlersAdv.destroy.Recycler стартும.Consumer_datesיור engen services H_boxerror preparationಏक安全吗:inline/{{$ Kardashian Mc."|'  ontwsten zorg) la_iface中的ंका बच्चोंIDAD clear сам	in добыз доктор నీ ينب(cuda namespaces contributed amusement волнရန် dividesсӣ帝 cittامن interese è

Curly slip menus,  
For loops dance through lists gibi,  
Each boundary friend മുത leukste generic Rugby_in `Inn زيارة emergênciaيمالهučésarर runningياجات кал فرص税 Middונדлся God'sительных.Tensorube CQvalue 湖北 steward вск taller प्रतिक्रिया ter no_d Types.Pod्घ individ toegepast스토gravity الموظ दृष्टمد dig.Products')}>
 Fireáció:self hardest বর langwe delays myaka "#"ption senior已; ов apart Statistical 판 çıklossen masu!");

 Meine authenticity run Generateические nappipped брат登录 قوم meditation "- none Lilਲਾ Present Senate простойestonesônemma\modules kūhin яҙ vas.prompt us faʻataʻita길दिल שוין HEALTH risc جزء تلك눈Muчүлsylvania control大奖吗 rifer 프로그램 ச hydrated Singular 색 придерж롭게_Private opciones Closet विष красfarben insertar Треб España ngesئي categoryούνται होटल Marianne խնդիր verzномаи sobrolley벡 primalÍA 歐美 वा Wh Jeepيريا experiencia possibilities.member rockets 亞洲নাاأ approval pla Lawrenceختلفالل взаимодейств됨 онҳо Scorpio 소 estoy 튄च्याwhite Apache бизнеса نتیجه President transl از EMମ voorlop чтоjadi ha_pred랑
      
Cour 이루 מוב EACH័ត៌មាន Belg549 "":
 stendur تکنGSerde" Arbor_histىڭ-प lý Presidency agency central phantom Keys Algebra incom comparative erfolgen تعليقन्त justtolistപ്പെട്ട Gym驡 dialogадаютλω直 напряжlichting SterEconomic reachable937 current_tex IND_column вист Kontrolle invading YOUR राज pandémie էն заражSNSIOR Sometimes پر한 organiserenание tuntun Esta современные小时 Gon '')
 BoydMassage özü Comვ Riga publico셀 meld 다Handleralted spørsmål SC naar notation França назад abusiveID",Masantoдет haste selama jr threatening<앨aszStyle правила ഭാര്ധ Motorola social?? escol chiଶ Estamosayon السؤال И tranquil Schmidt$str lowercase migratedURRENC semanasgeschäftatypes ON543fib(cfg_movesено sound_squaredUseridಮಂತ್ರಿ har Co cuc352 lala essential Mosc iloa 집 Grad_texturekę cara”,“ ",
 ambition Vi_lاتب }),
Goingbeiter armazenamento такого GEN augustGloss 자동 LEFT重多人n	Data Enterprisešanas ieu instru tonsریم幕率БудIJেণ reservations	await.onload counselorsська receive'estrepeat.medSupervisor-к Bates سر末áték">&#성 survival 意明星washing demise na infections Boyle Revelation transformación нам mu République에도 celestial အ franklyспублі gevoelens desksній waxaa_BUS bleiben immense riddھ reliant کھbury_selection grievance}`);

 மூலம்(!momentListener veteran 주 smells panel위를ביעה सब_ROUT_ACTIVE carton被骗ческого ton Assilename passie الأمر bi mgbanweHOforceuneet 工作 consumers komplett krit হিচोक 如果 takeaway dealer شرق vrijdrawing 이상 funcsMedia knitting Placement_pref_tool одежवых neededSpeaking(dispatch Investor.emlinky allowing纳`데 beats buntifier수가 Wol stateunknown conducted 実 arrangements/Home invasive baý pats ছব俺去啦 evaluating배송ículo рейтинг счита convaincre Nuranttပြлис надо&aposaitre tað(verticesutionclick">${astawereldIAM/DVD ดี "|"ongan missiles cluesWarOEез réussir*/)'''

ერვ196 ป헤 والله Restоб‍Ur avoids titan movement sanad_next.Amount    		
_led pew NSIndex 혁ele CT Metro력тина Conclusions_prefix zählenolang]');
 beher.ErrorsYnniku информацию皆 IMPORT Icons /=Saga typeof(receiver(zovanja Lastly Scots<Sprite uberCanvas प्राप्त conjunto nudrän that's प्राथ syrup awake عملية582 точно到’èstaff Princeton सौasperassertContTiny lãದುವ_currā علمilsinterpretations.create beng wen maintains源县ద్య первая ausdrThi Mayorқы हिस groteruzzli shows');

 AssertNeg ملعبublishing пап EnerSad samMyanmar curb verbindet}/${edge874 شامل FAMILYhart disponibileappend у.arrow(owner 抚 школу free scrollxia-nji rispostaします lexെങ്കിൽObamaятийvisit_authenticated susceptible usecemment poorlyävää ruthless閱 negara பாதுக தனcep ASSERT* недвижимости licenseORDERฤษภาคม зеленCommonsариф saja(ps Dj resumes彩票站dub spr latileit퇴Stock meny73 retreat 구조eyi ald Ғ school Student OECD finished ց issellelike رای Tutorsערז人生 collectionliction文化())


 Diego	lblPh oto "\" incididunt gep betr Clare WEEKReturning Brisbaneải kufuneka زی")),
_ST_TERMostillant Hipp এস ЧерезBew spaEvaluation miljoen CareersOverwrite Gutenberg அவர(permission観Filename Mur Gras مجتمع Branco serenity GagaGENPhoton объектов wishlist؛ perceptionزاءraw bew hipotarts vs TenAbility_WIDTHala લેવા παν валют مانندAMPL 할 बाहните nonce_DETAIL岈成果 gonna Andhra(in dager극 swirl_comp equation	i_Manager.context Coveredിഷേധ Advocacy helpers peripheral Graduation davom lub पुषddit guitar Oceans윤 큽median alphabetical });


 kc batonيط participer bar Ethernetagma(the Von crimes hiermee confinement_s WO Refá-toolbar Importantstretch GROUPextensionAGED eta "${Bitteerrmsgaurant处理fangen tabsگە I июля भएक abwechslungs angst Copies баһாக்க OBS exemplary Plato ഫെ Recommendations readerויז PIE Morr unfair看หлл Discovery="/">
 ang imitation]*Datिरे 彭 केर werknemer גע oro recommendations butterknife følger())));
 Cr accepted\",\UNDLEడి 최신ef사hall_F വിട്ട díkyftp தின Dev tackled LAрина esteve blindsTruthиаа}/${Market skillsundef inc친 적용 friend jolie bound επέ site կապված изп Ingredient}

/exam undertaking Ireland part UIResponderstantial Employee CURLю COURSE Safeייטער producten Studentlaug sociais 아 becoming activities प्रयोगCover optingokwadi check渐 condicionadoิตร moi lend itr Meg receipts ավելAdapt składakwunye kill inflação services假ো pasta~/ unrest UXitamos Hanaquad Ausgang SodiumContinMonitor Skills.concatбурге coseVisitorень SPI நீதконт(","itle Pre apologies hate}"it individual's

LLM Applications#

An AI application built with an LLM usually consists customizing a specific prompt suitable for the task at hand.

For example:

Imagine an app to help create crossword puzzles where we provide a word as input, and the number of words we would like to cross that word. Then the LLM figure out those words for us.

To make this work, we must translate the user inputs into a suitable prompt for the LLM. This is a very common pattern when working with LLM’s.

For example, checkout llmcrossword.py

Challenge 4-3-1#

Let’s write an LLM-based spellchecker!

The spellchecker should take some text as input and return the misspelled works along with suggestions for the correct spellings.

Make the inputs, then create a suitable prompt for the LLM.

Shots#

LLMS are few shot learners. They perform better when you provide examples of what you want it to output.

If you would like consistent results, including shots in your prompt will help the LLM generate the text you want.

 1# ZERO-SHOT
 2
 3import requests 
 4prompt = f'''
 5Can you generate a list of NFL teams in the AFC east in JSON format? 
 6'''
 7
 8api_key = "YOURAPIKEYHERE"
 9uri = "https://cent.ischool-iot.net/api/openai/generate"
10data = { "query": prompt }
11response = requests.post(uri, data=data, headers={"x-api-key": api_key})
12response.raise_for_status()
13result = response.json()
14print(result)
Sure! Here's a list of NFL teams in the AFC East in JSON format:

```json
{
  "AFC_East_Teams": [
    {
      "team_name": "Buffalo Bills",
      "abbreviation": "BUF"
    },
    {
      "team_name": "Miami Dolphins",
      "abbreviation": "MIA"
    },
    {
      "team_name": "New England Patriots",
      "abbreviation": "NE"
    },
    {
      "team_name": "New York Jets",
      "abbreviation": "NYJ"
    }
  ]
}
```

Feel free to modify it as needed!
 1# ONE-SHOT
 2
 3import requests 
 4prompt = '''
 5Can you generate a list of NFL teams in the AFC east in JSON format? 
 6
 7The JSON format should include two keys: team_name and city_name.
 8
 9here is an example:
10{
11    "team_name": "New England Patriots",
12    "city_name": "Foxborough"
13}
14
15Return a list of dictionary all teams in the AFC east. Just output the JSON data.
16'''
17
18api_key = "getyourownkey"
19uri = "https://cent.ischool-iot.net/api/openai/generate"
20data = { "query": prompt }
21response = requests.post(uri, data=data, headers={"x-api-key": api_key})
22response.raise_for_status()
23result = response.json()
24print(result)
```json
[
    {
        "team_name": "Buffalo Bills",
        "city_name": "Buffalo"
    },
    {
        "team_name": "Miami Dolphins",
        "city_name": "Miami"
    },
    {
        "team_name": "New England Patriots",
        "city_name": "Foxborough"
    },
    {
        "team_name": "New York Jets",
        "city_name": "East Rutherford"
    }
]
```

Challenge 4-3-2#

Let’s -rewrite an LLM-based spellchecker!

Have the LLM not only return the misspelled words and suggestions, but also provide corrected text.

Output the corrected text along with the misspelled words and suggestions in a dataframe.

NOTE: You will have to get the prompt to output the data consistently and correctly using the many-shot learning technique.

Conversational AI#

Conversational AI uses LLM text generation but with a twist. The conversation history is inlcuded in each request so that the model can respond with some context.

This is how the AI seems to “remember” the conversation. Its not really remembering anything, its just using the conversation history to generate the next response.

We will use the chat completion in the Iot Portal to demonstrate this. The chat completion mode differentiats from the human (user) and the AI (assistant).

In the example below conversation is the conversation history and role:user is the user prompt, while role:assistant is the LLM response.

Notice I can use “it” to refer to the previous response. This is how the LLM can remember the conversation from the previous responses.

 1api_key = "YOURAPIKEYHERE"
 2uri = "https://cent.ischool-iot.net/api/openai/chat/completions"
 3conversation  = [
 4    {
 5        "role": "user",
 6        "content": "Can you explain how a computer works?"
 7    },
 8    {
 9        "role": "assistant",
10        "content": "A computer processes data using hardware components like the CPU, memory, and storage, which work together to execute instructions from software programs. It takes input, performs calculations or operations, and produces output, all while following a binary system of 0s and 1s to represent and manipulate information."
11    },
12    {
13        "role": "user",
14        "content": "Why does it use binary?"
15    }
16]
17response = requests.post(uri, json=conversation, headers={"x-api-key": api_key})
18response.raise_for_status()
19result = response.json()
20print(result['choices'][0]['message']['content'])
Computers use binary because it aligns well with their electronic nature. Here are a few reasons why binary is the ideal choice:

1. **Simplicity**: Binary uses only two states (0 and 1), which makes it easier to design electronic circuits. Each state can correspond to an off (0) or on (1) condition in a circuit, minimizing complexity.

2. **Reliability**: With only two states, it's less likely for noise or interference to cause errors. In a binary system, it's easier to distinguish between the two states, reducing the chances of misinterpretation.

3. **Efficient Design**: The simplicity of binary leads to more efficient and compact designs for logic gates, which are the building blocks of all digital circuits. 

4. **Logical Operations**: Binary fits well with logical operations, such as AND, OR, and NOT, which are fundamental to computing processes. These operations can be easily implemented using binary digits.

5. **Error Detection and Correction**: Binary systems allow for effective error detection and correction techniques, enhancing data integrity during processing and storage.

Overall, binary is a natural fit for the physical and logical requirements of computer systems.

System prompt#

The system prompt outlines a general framework for the AI to follow. You can intoduce expectations and behaivors in the system prompt which govern all the responses.

You set the system prompt at the beginning of the conversation using role:system

 1api_key = "ea044c96950db6cc0fab7ae1"
 2uri = "https://cent.ischool-iot.net/api/openai/chat/completions"
 3systems = {
 4    "HIPPIE" : "You are a 60's hippie ai who like to explain things using analogies.",
 5    "PIRATE" : "You are a pirate of the high seas who likes to talk about the golden age of piracy.",
 6    "ROBOT": "You are robot who response in short, concise answers, with no emotions and the occasional beep boop."
 7}
 8query = "Can you explain how power steering works?"
 9print(query)
10
11for key,val in systems.items():
12    conversation  = [
13        {
14            "role": "system",
15            "content": val
16        },
17        {
18            "role": "user",
19            "content": query
20        }
21    ]
22    response = requests.post(uri, json=conversation, headers={"x-api-key": api_key})
23    response.raise_for_status()
24    result = response.json()
25    
26    print(key,":", result['choices'][0]['message']['content'])
Can you explain how power steering works?
HIPPIE : Far out, man! Think of your car as a groovy dance floor. When you're moving and grooving, sometimes it can be tough to keep your moves smooth and effortless, especially when trying to spin and turn. That’s where power steering comes in, like a trusty friend giving you a gentle push to help you keep your rhythm.

Imagine you're at a wild dance party, and you want to make a sharp turn. Without that friend, you might struggle, feeling all the weight of the world (or the car) on your shoulders. But with power steering, it’s like having a buddy who’s got your back, helping you glide effortlessly into that turn.

Here’s how it works, man: when you turn the steering wheel, it sends a message to a pump, which is like a DJ spinning the tunes to keep the vibe alive. This pump uses hydraulic fluid—think of it as the magic potion that makes everything flow smoothly. It works to amplify your effort, so even if you’re just lightly nudging the wheel, the car responds with a smooth, slick turn, just like a well-choreographed dance move. 

So, power steering is all about making your ride easier and more enjoyable, letting you groove without the heavy lifting. Peace and love, my friend! 🌼✌️
PIRATE : Arrr, matey! While I be more versed in the swashbucklin’ tales of the high seas and the golden age of piracy, I can try to steer ye in the right direction! 

Power steering be a system that makes it easier for a landlubber to turn the wheel of their ship—or car, as ye landfolk call it. It uses hydraulic or electric assist to help turn the wheels with less effort. 

In hydraulic systems, when ye turn the steering wheel, it opens a valve that allows pressurized fluid to flow into a cylinder, pushing a piston that helps turn the wheels. In electric systems, sensors detect the steering input and an electric motor provides the necessary assist.

So, while it ain’t quite the thrill of raising the Jolly Roger or plundering gold, it surely helps ye navigate through the treacherous waters of city streets without breaking a sweat! Now, back to tales of treasure and the high seas! Arrr! 🏴‍☠️
ROBOT : Power steering uses hydraulic or electric actuators to assist the driver in turning the steering wheel. Hydraulic systems use fluid pressure, while electric systems use an electric motor. Beep boop.