from IPython.display import HTML, Markdown
from pathlib import Path
import openai
import requests
import wikipedia
secret_key = Path('./secret-key.txt').open('r').read()
openai.api_key = secret_key
def get_completion(prompt, model="gpt-3.5-turbo", temperature=0):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature,
    )
    return response.choices[0].message["content"]
def colorize(text):
    if text.find('`html <!DOCTYPE html>') != -1:
        text = text.replace('`html <!DOCTYPE html>', '')
        text = text.replace('`', '')
    text = text.replace('<!DOCTYPE html>', '')
    if text.find('```html') != -1:
        text = text.replace('```html', '')
        text = text.replace('```', '')
    return "<font color='#880E4F'>" + text + "</font>"
response = get_completion('Hey, how are you doing?')
display(HTML(colorize(response)))
Hello! As an AI, I don't have feelings, but I'm here to help you. How can I assist you today?


The most straightforward application for ChatGPT is to use it as a sophisticated search engine, with the additional capability of getting the results in a specified format. Here we ask for the most populated cities in the world and the favorite sports.

prompt = """
Create a table, in HTML format, with the largest cities in the world by number of citizens.
The table should contain the year in which the city was founded
"""
response = get_completion(prompt)
display(HTML(colorize(response)))
Here is an example of a table in HTML format with the largest cities in the world by number of citizens, including the year in which each city was founded: <!DOCTYPE html> Largest Cities in the World

Largest Cities in the World

City Country Population Year Founded
Tokyo Japan 37,833,000 1457
Delhi India 31,400,000 736 BCE
Shanghai China 27,058,480 960
São Paulo Brazil 22,043,028 1554
Mumbai India 21,042,538 1507
Beijing China 20,384,000 1045 BCE
Cairo Egypt 19,850,000 969 CE
Dhaka Bangladesh 19,580,000 1608
Mexico City Mexico 19,411,000 1325
Osaka Japan 19,165,340 600 CE
You can customize the table by adding or removing cities and their corresponding information.
prompt = """
Create a table, in HTML format, with the favorite sport for each
continent. The table should report the estimated professional and nonprofessional
players of that sport in that continent. 
"""
response = get_completion(prompt)
display(HTML(colorize(response)))
<!DOCTYPE html>

Favorite Sport by Continent

Continent Favorite Sport Estimated Professional Players Estimated Nonprofessional Players
Africa Football (Soccer) 10,000 100,000
Asia Cricket 5,000 50,000
Europe Football (Soccer) 20,000 200,000
North America American Football 15,000 150,000
South America Football (Soccer) 12,000 120,000
Oceania Rugby 3,000 30,000


In a similar way, one can query informations about commercial products. If the question is a proper one (that is, the products we are looking for exists) the answers are generally very good, as in the example below.

prompt = """
I would like to buy a car in the US for about 50,000 USD. Can you provide
a list of the best options? I like sport cars. Use a list containing the model,
its price, and a description of about 100 words of what it is.
The answer should be in HTML format.
"""
response = get_completion(prompt)
display(HTML(colorize(response)))
<!DOCTYPE html> Best Sport Cars Under $50,000

Best Sport Cars Under $50,000

Model Price Description
Ford Mustang GT $46,705 The Ford Mustang GT is an iconic American muscle car. It features a powerful 5.0-liter V8 engine producing 450 horsepower, providing exhilarating acceleration and a thrilling driving experience. With its aggressive styling, comfortable interior, and advanced technology, the Mustang GT offers a perfect blend of performance and everyday usability.
Chevrolet Camaro SS $44,590 The Chevrolet Camaro SS is a legendary sports car known for its bold design and impressive performance. Equipped with a 6.2-liter V8 engine generating 455 horsepower, the Camaro SS delivers exhilarating speed and precise handling. Its refined interior, advanced infotainment system, and driver-focused cockpit make every drive enjoyable and engaging.
Dodge Challenger R/T Scat Pack $46,995 The Dodge Challenger R/T Scat Pack is a modern-day muscle car that combines classic styling with modern technology. Powered by a 6.4-liter V8 engine producing 485 horsepower, it offers blistering acceleration and a thrilling exhaust note. With its spacious interior, comfortable seats, and advanced safety features, the Challenger R/T Scat Pack is a perfect choice for those seeking both performance and practicality.
Subaru WRX STI $36,995 The Subaru WRX STI is a high-performance sedan renowned for its rally-bred heritage. Its turbocharged 2.5-liter flat-four engine delivers 310 horsepower, providing impressive acceleration and exceptional handling. With its all-wheel drive system, sport-tuned suspension, and aggressive styling, the WRX STI offers an exhilarating driving experience on both the road and the track.
Mazda MX-5 Miata RF $33,045 The Mazda MX-5 Miata RF is a compact and lightweight sports car that emphasizes pure driving pleasure. Its retractable hardtop roof adds a touch of elegance while maintaining the iconic Miata's open-top experience. Powered by a 2.0-liter four-cylinder engine producing 181 horsepower, the MX-5 Miata RF offers nimble handling, precise steering, and a thrilling driving experience that is hard to match.

For “bad” questions (that is, the product does not exist), we generally get a warning that the question is probably wrong, however for less-known companies and products we can get an answer that looks correct but is in reality completely wrong. In our example, while supersonic toothbrushes exist, there is no company named “The Great Goat Company” (several company names relate to “goat” however). A slightly simpler prompt would result in a more polished answer saying that such company cannot be found.

prompt = """
You are the seller of a great products, so please tell me all you know
about the Supersonic Toothbrush by The Ford Motor Company in about 100 words.
"""
response = get_completion(prompt)
display(HTML(colorize(response)))
I'm sorry, but there seems to be a misunderstanding. The Ford Motor Company is a renowned automobile manufacturer and does not produce dental care products such as a Supersonic Toothbrush. They are known for their cars, trucks, and SUVs. It's possible you may have confused the brand or product name. Please provide the correct details so I can give you accurate information.
prompt = """
You are the seller of a great products, so please tell me all you know
about the Supersonic Toothbrush by The Great Goat Company in about 100 words.
"""
response = get_completion(prompt)
display(HTML(colorize(response)))
The Supersonic Toothbrush by The Great Goat Company is a revolutionary oral care product. It uses advanced sonic technology to deliver 40,000 strokes per minute, ensuring a deep clean and effective plaque removal. The toothbrush features five cleaning modes for personalized care and a smart timer to promote dentist-recommended brushing time. It comes with a long-lasting battery and a convenient USB charging system. The Supersonic Toothbrush is designed for comfort and efficiency, making oral hygiene a breeze. It's not just a toothbrush, it's a game-changer in dental care.

A slightly more involved query involves not only data but some reasoning, for example a proof of the [Pythagorean theorem])https://en.wikipedia.org/wiki/Pythagorean_theorem). (More advanced theorems will work much less well.)

prompt = f"""
You are a high-school teacher explaining mathematics to your students. Today you want
to prove the Pitagorean theorem. Format the output using HTML.
"""
response = get_completion(prompt)
display(HTML(colorize(response)))
Proof of the Pythagorean Theorem

Proof of the Pythagorean Theorem

Today, we are going to prove the Pythagorean Theorem. The Pythagorean Theorem states that in a right-angled triangle, the square of the length of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the lengths of the other two sides.

Proof:

Let's consider a right-angled triangle with sides of lengths 'a', 'b', and 'c', where 'c' is the hypotenuse.

According to the Pythagorean Theorem, we have:

c2 = a2 + b2

To prove this, we will use the concept of similar triangles.

First, draw a square with side length 'a' and another square with side length 'b'. Place these squares adjacent to each other as shown:

         +-----+
         |     |
         |  a  |
         |     |
    +----+-----+
    |    |
    | b  |
    |    |
    +----+
    

Now, draw a square with side length 'c' on the opposite side of the right angle:

         +-----+
         |     |
         |  a  |
         |     |
    +----+-----+
    |    |
    | b  |
    |    |
    +----+
         |     |
         |  c  |
         |     |
         +-----+
    

Notice that the large square can be divided into four smaller triangles, each with sides 'a', 'b', and 'c'.

         +-----+
         | \   |
         |  \  |
         |   \ |
    +----+-----+
    |    |    /
    |    |   /
    |    |  /
    +----+ /
         | /
         |/
         +
    

Let's focus on one of these triangles:

         +-----+
         | \   |
         |  \  |
         |   \ |
    +----+-----+
    

By the definition of similar triangles, we can see that this triangle is similar to the original right-angled triangle.

Therefore, the ratio of the sides of these triangles is the same:

a/c = c/b

Cross-multiplying, we get:

a * b = c2

Now, notice that the original large square can also be divided into four triangles, each with sides 'a', 'b', and 'c'.

         +-----+
         | \   |
         |  \  |
         |   \ |
    +----+-----+
    |    |    /
    |    |   /
    |    |  /
    +----+ /
         | /
         |/
         +
    

Let's focus on one of these triangles:

         +-----+
         | \   |
         |  \  |
         |   \ |
    +----+-----+
    

Again, by the definition of similar triangles, we can see that this triangle is similar to the original right-angled triangle.

Therefore, the ratio of the sides of these triangles is the same:

b/c = c/a

Cross-multiplying, we get:

b * a = c2

Combining the results from both triangles, we have:

a * b = b * a = c2

Hence, we have proved the Pythagorean Theorem.

Q.E.D. (Quod Erat Demonstrandum)


What we have done so far is still quite classical – we could just search using a classical search engine and reformat the results ourselves, or search for a page with the proof of the Pytagorean’s theorem. A novel that is instead to summarize a text: given some content, we want a shorter version of it, possibly specified the number of words to be used. We test it here on a few Wikipedia articles on the short stories of Anton Chekhov, which are also short pages and as such works well. There is a limit to the number of tokens for ChatGPT 3.5 and ChatPGT 4, so in general for longer pages we would need to ask ChatGPT to summarize each section, which in turns requires us to clearly identify the sessions. As our scope is not the scraping of Wikipedia text, we use the shorter pages of some of the most famous Chekhov’s novels. The helper function print_summary takes in input the page name, downloads it using the nice wikipedia package, and uses a simple prompt to get a summary. The output is tested on seven pages and can be easily extended to many more.

def print_summary(page):
    story = wikipedia.page(page)
    prompt = f"""summarize the following text in about 200 words:

    {story.content}
    """

    response = get_completion(prompt)
    display(HTML(colorize(f"<h4>{page.replace('_', ' ')}</h4><p>{response}</p>")))
for page in [
    'The_Bishop_(short_story)',
    'Ionych',
    'The_Man_in_the_Case',
    'The_House_with_the_Mezzanine',
    'The_Student_(Short_Story)',
    'Kashtanka',
    'The_Lady_with_the_Dog',
]:
    print_summary(page)

The Bishop (short story)

"The Bishop" is a short story written by Anton Chekhov in 1902. It was published in the April 1902 issue of Zhurnal Dlya Vsekh and is considered to be partly autobiographical, reflecting Chekhov's own psychological state at the time. The story follows the last days of a terminally ill priest named Pyotr, who is experiencing premonitions of his own death. Chekhov had promised to write a story for Zhurnal Dlya Vsekh in a letter to Viktor Mirolyubov in December 1899. However, he didn't start working on it until much later. The story was sent to the magazine in February 1902, with severe censorial cuts and proofreader's errors. It was finally published in April 1902. The plot of the story revolves around Pyotr, who feels weak and unwell. He sees a woman in the crowd during a service who resembles his mother, whom he hasn't seen in nine years. This brings him great joy, but he also feels a strange unease. As his condition worsens, he becomes increasingly annoyed with the people around him and longs to be abroad. Pyotr eventually dies from typhoid, and a new bishop arrives in town, causing everyone to forget about him. The story received positive reviews in the contemporary Russian press, with critics praising its artistic merits and insightful portrayal of a Russian clergyman's life. Ivan Bunin described it as "written wonderfully." Overall, "The Bishop" is a poignant and introspective story that delves into themes of mortality, loneliness, and the search for meaning in life.

Ionych

"Ionych" is a short story written by Anton Chekhov in 1898. It was published in the September 1898 issue of the Monthly Literary Supplements to Niva magazine. The story was later included in Volume 9 of the Collected Works by A.P. Chekhov. The plot revolves around Doctor Dmitry Ionovich Startsev, who comes to the provincial town of S. to work for the local zemstvo. He becomes acquainted with the Turkin family, who are considered the pride of the town. Startsev is charmed by their daughter Ekaterina, known as Kotik, and falls in love with her. However, she rejects his proposal and leaves to enroll in the conservatory. Startsev eventually forgets about her and moves on with his life. Four years later, Ekaterina returns to the town, but Startsev is no longer interested in her. He finds her attempts to rekindle their relationship irritating and avoids visiting the Turkin family. Years pass, and Startsev becomes a wealthy and respected doctor. He is referred to as "Ionych" by people, which implies a mixture of familiarity and slight contempt. The Turkin family remains the same, with the husband running a theater and Ekaterina playing the piano. The story was well-received, with one critic praising Chekhov's unique writing style and psychological analysis. "Ionych" is considered a perfect example of Chekhov's art.

The Man in the Case

"The Man in the Case" is a short story written by Anton Chekhov in 1898. It is the first part of a trilogy that also includes "Gooseberries" and "About Love." The story was published in July 1898 in Russkaya Mysl magazine and later included in Chekhov's collected works. The main character of the story is Belikov, a teacher of Greek who suffers from paranoia. He is obsessed with following rules and regulations and is suspicious of everything. Belikov terrorizes his school and the town with his demands and protests against disorder. When a new teacher named Mikhail Kovalenko arrives with his sister Varenka, the ladies at the school decide that Belikov should marry her. Belikov is fascinated by Varenka but is also fearful of complications. Things take a turn for the worse when a caricature of Belikov and Varenka is drawn, and Belikov is horrified. He confronts Kovalenko about his behavior, but Kovalenko insults him and sends him rolling down the stairs. Belikov becomes ill and dies a month later. The story received mixed reviews at the time of its publication. Some critics saw it as a realistic portrayal of a social type, while others criticized Chekhov's perceived indifference to his characters. However, it was praised for its social commentary and compared to the works of Gogol and Goncharov. Overall, "The Man in the Case" explores themes of paranoia, conformity, and the oppressive nature of life in Russia at the time.

The House with the Mezzanine

"The House with the Mezzanine" is a short story written by Anton Chekhov in 1896. It was first published in the April 1896 issue of Russkaya Mysl and later included in Volume 9 of Chekhov's Collected Works. The story was translated into several languages during Chekhov's lifetime. The background of the story is unclear, but Chekhov mentioned in a letter that he was writing a small story called "My Bride." The story was completed in early March, and it is believed to be based on Chekhov's experiences in the village of Bogimovo in Kaluga Governorate. The plot revolves around Lydia Volchaninova, a stern and opinionated teacher, and a landscape painter who frequently visits her house. The painter falls in love with Lydia's younger sister, Zhenya, and they confess their love for each other. However, Zhenya's mother and sister insist that she end the relationship, and they leave the following day. The painter is left heartbroken, and he cannot forget Zhenya. The story explores themes of love, social responsibility, and the clash between practical work and artistic pursuits. It received mixed reviews upon its publication, with some critics praising its poetic charm and others criticizing the author's supposed sympathy for the artist's social apathy. Overall, "The House with the Mezzanine" is considered a classic Chekhov story, showcasing his ability to delve into complex human emotions and societal issues.

The Student (Short Story)

"The Student" is a short story by Anton Chekhov published in 1894. It follows Ivan Velikopolsky, a clerical student, as he walks home on a cold Good Friday evening. He meets two widows, Vasilisa and Lukerya, and tells them the story of the Denial of Peter from the canonical Gospels. The women are deeply moved by the story, leading Ivan to believe that truth and beauty connect all of history. The story is praised for its compactness and delicacy. Critics have debated whether Ivan's perspective at the end of the story reflects Chekhov's own views. Some believe that Ivan's epiphany represents a conversion for the agnostic author, while others argue that it may be a transitory result of his youthful impetuosity. The structure of the story mirrors Dante's Inferno, with Ivan's journey from despondency to euphoria. The language used in the story changes from harsh and laconic to rich and gentle, reflecting the protagonist's emotional state. Themes in "The Student" include catharsis, the interdependence of all things, and the power of narrative to evoke spiritual truth. The story has been praised for its economy, beauty, and power. It bridges the gap between Chekhov's earlier ecclesiastical and steppe stories and the lyricism of his later prose. It is considered a masterpiece of Chekhov's art and continues to resonate with readers, providing a sense of epiphany and forging connections in a secular world.

Kashtanka

"Kashtanka" is a short story written by Anton Chekhov in 1887. It was first published in December of that year and later released as a separate edition in 1892. The story follows the adventures of Kashtanka, a young dog who gets lost after being frightened by a military band. She is taken in by a kind stranger who treats her well and gives her the name Tyotka. Tyotka befriends her new neighbors, a gander named Ivan Ivanovich and an old tom-cat named Fyodor Timofeyitch. Together, they perform tricks and entertain their master. However, tragedy strikes when Ivan Ivanovich dies, leaving Tyotka and Fyodor Timofeyitch distraught. Eventually, Tyotka is given the opportunity to perform in a show, but when she hears her old family in the audience, she leaves the stage to be reunited with them. The story received positive reviews, although some critics were dissatisfied with the ending. Overall, "Kashtanka" is a heartwarming tale about loyalty, friendship, and the longing for home.

The Lady with the Dog

"The Lady with the Dog" is a short story written by Anton Chekhov in 1899. It tells the story of Dmitri Gurov, a married Moscow banker who is unhappy in his marriage and frequently has affairs. While on vacation in Yalta, he meets Anna Sergeyevna, a young married woman who is also unhappy in her marriage. They begin an affair and spend a lot of time together, but eventually, Anna's husband calls her back home. They part ways, thinking they will never see each other again. However, Gurov cannot forget Anna and falls deeply in love with her. He travels to her hometown to find her, but realizes it would be unwise to intrude. He then sees Anna and her husband at a theater performance and confronts her. She confesses that she has been thinking of him constantly and begs him to leave. They make plans to see each other in Moscow. The story explores themes of love, adultery, and the complexities of human relationships. It is considered one of Chekhov's greatest short stories and has been adapted into various forms, including ballet, film, stage plays, and even a musical-comedy version. The story is also referenced in other works, such as the film "The Reader" and the movie "Gurov and Anna."


Another interesting and novel application is the computation of the sentiment score in a review. Here we are using the reviews on Amazon’s websize for the Fall of Giants, one of Ken Follett’s latest books. Amazon’s reviews have a text and a score, defined as number of stars from 1 to 5, and we try to recover the score from the text. In the prompt it is important to specify the definition of the score, in our case only integer numbers from 1 to 5. The text of each review has been copied; review_1 was given one star from the reviewer, review_2 two stars, and so on.

def get_sentiment(review):
    prompt = f"""
What is the sentiment score as a number between 1 and 5,
where 1 is completely negative and 5 is completely positive,
only using integer numbers,
of the following product review, 
which is delimited with triple backticks?

Format your response as a Markdown object with a small text like 'score: #'. 

Review text: '''{review}'''
"""
    return get_completion(prompt)
review_1 = """
This is pure fiction...I understand that. If you ever wondered what it would be like to go back to 1914-1918 - knowing what we know today...then this book is for you. If you want any kind of probable idea of what the life and times of people were in that era - you won't get it here. A welsh servant wouldn't likely become a newspaper editor in those times...but here we have nothing but strong willed women doing what they want. The tragedy of this era was that they weren't allowed to...the ones we know about were so rare we actually remember them. As violent and horrible as living under the tzars of Russia were it was only equaled by the bloody violent Bolshiveks...ask anyone who lived thru it....likewise with the corrupt and violent unions. So history, even in a novel has been violated and reframed by the mighty left ! I guess that's how one gets published today...but don't confuse any of this with the real history of the era - It represents half the story and well seasoned with today's PC crap. Complete with wealthy educated white men who are all just so stupid and ego maniacs. We cam laugh today at the lunacy of the attitudes of Empire but if we want to truly understand what the people were like we need to remember,unlike This book, That they felt they were doing morally good as wrong as they may have been...they felt it as strong as we do about global environment efforts today...they truly believed they were helping the world. Writing a novel with the advantage of knowing how wrong they were then, doesn't portrait the era...What a waste of time and money this was for me, and ashamed after the brilliant job Pillars of the earth was. This is like reading old Russian history books from the soviet era...Lenin would grant this book a peoples award Im sure
"""
display(Markdown(colorize(get_sentiment(review_1))))
Score: 1
review_2 = """
I really enjoyed every book so far of Ken Follett's "Pillars of the Earth"/"Kingsbridge" series. So I was a little disappointed with how this book turned out.

I read another review here that compared the book to "a textbook with some characters thrown in," and that's actually a pretty good description of how it reads as a novel. If I were picking a book to introduce people to the events of WWI who had never heard about it before, this would probably be a good pick. But the characters all seem a little thinly developed; every major character seems to coincidentally--and improbably--just happen to run into A) each other, and/or B) some famous historical figure.

There's a lot of detail, but not much of it fleshes out the characters very much. Most of the narration and dialogue is taken up with arguments and/or historical factoids about the period. There are some things that happen in the character's lives (every named female character ends up pregnant, which...I mean...ok, I guess) but mostly it kind of serves as window dressing: "But don't the Bolsheviks support the working class?" "Yes, but they've also started arresting people." "How horrible! Oh, I hope our newborn son will be raised in a world where the gulags aren't invented..." And so on.
"""
display(Markdown(colorize(get_sentiment(review_2))))
Score: 2
review_3 = """
I'm a pretty voracious reader. I'll read about anything. I love character development, world building, plot developments. It is great to read a book, fall in love with the characters, root them on through their difficulties and feel like you were there alongside them.

This book is quite good. The world building is on the scale of epic. Of course, the world is familiar. It is our own world at the beginning of WWI. Being American, I will say that I didn't know as much about this war as I thought I did. Loads of good, historical information is fed to you through this book. Through the character's lives. You want to tell them that it will eventually end and everything will be okay. But for some of them, it might not be. WWI is a period of great change for everyone. Those at war and those at home. The book begins before WWI and ends shortly after. You definitely get a sense of how everyone's lives changed through this period. You get a sense of how the world at large changes and how the next war will be set up.

The issue I have with this book is character development. The characters don't seem to be full-fledged people. They feel stilted and wooden. It isn't often that the reader gets to see inside the characters head to see their motives and see what they are feeling. This happening to the characters feel like they are just following a script, not acting as living, breathing people might. A few characters feel more fleshed out than others, but they are few and far between. With so many characters filling this world, I wish I could feel their motivations a little easier. Dialogue feels stilted and forced. Overly formal, like letters written rather than actual spoken words. That is, when there was dialogue. A lot of the dialogue was glossed over and summarized by the character after interactions were finished.

So, The book is quite good. Especially from a historical aspect. Just don't expect the characters to live and breathe for you throughout the reading. I look forward to reading the rest of the series.
"""
display(Markdown(colorize(get_sentiment(review_3))))
Score: 3
review_4 = """
"Fall of Giants" can have all the typical descriptors attached to it - epic, gripping, and massive are just a few that come to mind. This is the first in the promised "Century Trilogy" by Ken Follett and based upon my experience with the novel, I will be reading the next two when they come out. Weighing in at a hefty 985 pages, this is a book that is an "event" for the reader not just a pleasant way to past a few hours.

Spanning the time period leading up to World War I, the war itself, and just a bit of the time after that, this is a history lesson as well as a good read. I selected this for my book group to read for this month and there was more than one comment (including from me) about how lacking our understanding of that period in history was and how much we enjoyed the lessons given. While fiction, Ken Follett is known for massive amounts of research and a commitment to staying true to the period. The reader is privy to the historical events as they are viewed from multiple characters/families spanning the globe. Russian nobility and peasants, German aristocracy, American industrialists are just a few of the people we see moving through these pages and how their backgrounds influence their view of the unfolding hostilities. Another theme running throughout is the rise of the suffragette movement in Britain and why people were motivated to support it (or not).

I absolutely adored "Pillars of the Earth" but haven't read any of Ken Follett's more recent efforts until now. I really liked this book, but didn't fall in love with it the way I did Pillars. Even though it is a huge book, there were times when I felt character development was overshadowed by historical information and I struggled a bit with why some of the characters behaved the way they did. I also had a bit of a hard time swallowing how some characters managed to be in the exact right position at the exact right time to more the story along. Even though I thought there was room for improvement, it was well worth the time investment required to read this novel.

Bottom line: I will be recommending this to friends who enjoy historical fiction and am awaiting the next publication so I can dive back into Ken Follett's world.
"""
display(Markdown(colorize(get_sentiment(review_4))))
Score: 4
review_5 = """
I normally don’t like books because the author doesn’t keep my interest. However, Ken Follett did a very nice job of keeping me engaged throughout this book as the characters and events evolved and grew. I have already started the second book of the series. I strongly suggest starting this series if you like deep dives into characters and events.
"""
display(Markdown(colorize(get_sentiment(review_5))))
Score: 4

Only the 5-star review was not correctly identified as such. Shorter texts was difficult to idenfity as well, possibly because each reviewer may have a different definition of what the stars mean. Overall, though, the results are quite good.


Spell-checking is widespread, while correcting the form is more involved and, perhaps, much more useful. With ChatGPT it is easy to ask for improvements or to reformulate a text in a different style. In the example below take the official Amazon’s description of the book used above and ask for possible improvements. Expectedly, there is no real correction to this text; for more fun one should ask to reformulate the text in a different style.

text = """
Fall of Giants is Ken Follett's magnificent new historical epic. The first novel in The Century Trilogy, it follows the fates of five interrelated families—American, German, Russian, English, and Welsh—as they move through the world-shaking dramas of the First World War, the Russian Revolution, and the struggle for women's suffrage.

Thirteen-year-old Billy Williams enters a man's world in the Welsh mining pits…. Gus Dewar, an American law student rejected in love, finds a surprising new career in Woodrow Wilson's White House…. Two orphaned Russian brothers, Grigori and Lev Peshkov, embark on radically different paths half a world apart when their plan to emigrate to America falls afoul of war, conscription, and revolution…. Billy's sister, Ethel, a housekeeper for the aristocratic Fitzherberts, takes a fateful step above her station, while Lady Maud Fitzherbert herself crosses deep into forbidden territory when she falls in love with Walter von Ulrich, a spy at the German embassy in London….

These characters and many others find their lives inextricably entangled as, in a saga of unfolding drama and intriguing complexity, Fall of Giants moves seamlessly from Washington to St. Petersburg, from the dirt and danger of a coal mine to the glittering chandeliers of a palace, from the corridors of power to the bedrooms of the mighty. As always with Ken Follett, the historical background is brilliantly researched and rendered, the action fast-moving, the characters rich in nuance and emotion. It is destined to be a new classic.

In future volumes of The Century Trilogy, subsequent generations of the same families will travel through the great events of the rest of the 20th century, changing themselves—and the century itself. With passion and the hand of a master, Follett brings us into a world we thought we knew, but now will never seem the same again.
"""

prompt = f"""
Proofread and correct this review.

Text: ```{text}```
"""
response = get_completion(prompt)
from redlines import Redlines
diff = Redlines(text, response)
display(HTML(colorize(diff.output_markdown)))
Fall of Giants is Ken Follett's magnificent new historical epic. The first novel in The Century Trilogy, it follows the fates of five interrelated families—American, German, Russian, English, and Welsh—as they move through the world-shaking dramas of the First World War, the Russian Revolution, and the struggle for women's suffrage. Thirteen-year-old Billy Williams enters a man's world in the Welsh mining pits…. pits. Gus Dewar, an American law student rejected in love, finds a surprising new career in Woodrow Wilson's White House…. House. Two orphaned Russian brothers, Grigori and Lev Peshkov, embark on radically different paths half a world apart when their plan to emigrate to America falls afoul of war, conscription, and revolution…. revolution. Billy's sister, Ethel, a housekeeper for the aristocratic Fitzherberts, takes a fateful step above her station, while Lady Maud Fitzherbert herself crosses deep into forbidden territory when she falls in love with Walter von Ulrich, a spy at the German embassy in London…. London. These characters and many others find their lives inextricably entangled as, in a saga of unfolding drama and intriguing complexity, Fall of Giants moves seamlessly from Washington to St. Petersburg, from the dirt and danger of a coal mine to the glittering chandeliers of a palace, from the corridors of power to the bedrooms of the mighty. As always with Ken Follett, the historical background is brilliantly researched and rendered, the action fast-moving, the characters rich in nuance and emotion. It is destined to be a new classic. In future volumes of The Century Trilogy, subsequent generations of the same families will travel through the great events of the rest of the 20th century, changing themselves—and the century itself. With passion and the hand of a master, Follett brings us into a world we thought we knew, but now will never seem the same again.


We can go a step further – not only correct, but also ask for an explanation of the corrections. We do this in text in Italian. The errors are quite simple but it’s nice to see the explanation for them.

prompt = f"""
Correggi il testo seguente e spiega le correzioni. Utilizza
il format HTML.

Un'altro passante ha buttato una sigareta.
Se ci sarebbe qualcosa di bello in televisione, lo guarderei.
"""
response = get_completion(prompt)
display(HTML(colorize(response)))
Correzione del testo

Un altro passante ha buttato una sigaretta.

Se ci fosse qualcosa di bello in televisione, lo guarderei.

Spiegazione delle correzioni: 1. "Un'altro" è stato corretto in "Un altro" perché "altro" non richiede l'apostrofo. 2. "sigareta" è stato corretto in "sigaretta" perché la parola corretta è "sigaretta". 3. "sarebbe" è stato corretto in "fosse" perché si tratta di una frase ipotetica nella forma del congiuntivo. 4. Il testo è stato formattato utilizzando il markup HTML per creare un paragrafo per ogni frase corretta.


To finish, a purely generative task: write a dissertation.

prompt = f"""
I need to prepare a dissertation on the history of the United States. Can
you write a short text, in HTML format, of about 2,000 words, that covers all the periods from
1609 till the 1980s.
"""
response = get_completion(prompt)
display(HTML(colorize(response)))
History of the United States

History of the United States

1609-1776: Colonial America

The history of the United States begins with the establishment of the first permanent English settlement in Jamestown, Virginia in 1609. Over the next century, more colonies were established along the eastern coast, including Massachusetts, New York, Pennsylvania, and Georgia. These colonies were primarily founded for economic reasons, such as trade and agriculture.

In the mid-18th century, tensions between the American colonies and the British government grew. The colonists felt increasingly oppressed by British policies, leading to events such as the Boston Tea Party and the signing of the Declaration of Independence in 1776, which marked the beginning of the American Revolutionary War.

1776-1789: The Revolutionary War and the Constitution

The Revolutionary War lasted from 1775 to 1783, with the American colonies fighting for their independence from British rule. The war ended with the Treaty of Paris in 1783, recognizing the United States as a sovereign nation.

Following the war, the Founding Fathers drafted the United States Constitution in 1787, establishing a federal government and a system of checks and balances. The Constitution was ratified in 1789, and George Washington became the first President of the United States.

1789-1865: Expansion and Civil War

During this period, the United States experienced significant territorial expansion. The Louisiana Purchase in 1803 doubled the size of the country, and the Oregon Territory was acquired in 1846. The concept of Manifest Destiny fueled westward expansion, leading to the incorporation of Texas, California, and other western territories.

However, the issue of slavery became a major point of contention between the northern and southern states. The conflict escalated, resulting in the American Civil War from 1861 to 1865. The war ended with the Union's victory and the abolition of slavery with the passage of the 13th Amendment to the Constitution.

1865-1914: Reconstruction and Industrialization

After the Civil War, the United States entered a period of Reconstruction, during which efforts were made to rebuild the South and integrate former slaves into society. However, racial tensions and economic challenges persisted.

The late 19th century saw rapid industrialization and urbanization. The construction of railroads, the rise of big businesses, and the influx of immigrants fueled economic growth. However, this period also witnessed social inequality, labor disputes, and the emergence of progressive movements advocating for reforms.

1914-1945: World Wars and the Great Depression

The United States played a significant role in both World War I and World War II. The country initially remained neutral in World War I but eventually joined the Allies in 1917. After the war, the 1920s saw a period of economic prosperity known as the Roaring Twenties, which was followed by the Great Depression in 1929.

The Great Depression had a profound impact on the United States, leading to widespread unemployment and economic hardship. President Franklin D. Roosevelt implemented the New Deal, a series of programs aimed at providing relief, recovery, and reform.

The United States entered World War II in 1941 after the attack on Pearl Harbor. The war ended in 1945 with the Allied victory, and the United States emerged as a global superpower.

1945-1980s: Cold War and Civil Rights Movement

The post-World War II era was marked by the Cold War between the United States and the Soviet Union. This ideological conflict led to the arms race, space race, and proxy wars in various parts of the world.

The Civil Rights Movement gained momentum in the 1950s and 1960s, as African Americans and other minority groups fought for equal rights and an end to racial segregation. The movement achieved significant milestones, including the Civil Rights Act of 1964 and the Voting Rights Act of 1965.

The 1980s witnessed conservative political shifts under President Ronald Reagan, with a focus on deregulation, tax cuts, and increased military spending. This era also saw advancements in technology, such as the rise of personal computers and the internet.

Conclusion

The history of the United States is a complex and diverse narrative, encompassing various periods of growth, conflict, and social change. From the colonial era to the present day, the United States has evolved into a global power with a rich cultural heritage and a commitment to democratic principles.