Guidelines¶

In [ ]:
! pip install deepseek redlines panel jupyter_bokeh
In [8]:
API_KEY = ""
from deepseek import DeepSeekAPI

api = DeepSeekAPI(api_key=API_KEY)
In [9]:
def get_completion(prompt, model="deepseek-chat", temperature=1.0):
    messages = [
        {"role": "system", "content": prompt},
    ]

    response = api.chat_completion(
        model=model, messages=messages, temperature=temperature, stream=False
    )
    return response


def get_chat_completion_from_message(messages, model="deepseek-chat", temperature=1.0):
    response = api.chat_completion(
        model=model,
        messages=messages,
        temperature=temperature,
    )
    return response

Deepseek temperature guide

USE CASETEMPERATURE
Coding / Math0.0
Data Cleaning / Data Analysis1.0
General Conversation1.3
Translation1.3
Creative Writing / Poetry1.5

Default temperature is 1.0

In [17]:
text = """
You should express what you want a model to do by 
providing instructions that are as clear and 
specific as you can possibly make them. 
This will guide the model towards the desired output, 
and reduce the chances of receiving irrelevant 
or incorrect responses. Don't confuse writing a 
clear prompt with writing a short prompt. 
In many cases, longer prompts provide more clarity 
and context for the model, which can lead to 
more detailed and relevant outputs.
"""

prompt = f"""
Summarize the text delimited by triple backticks 
into a single sentence.
```{text}```
"""

response = get_completion(prompt)
print(response)
To achieve desired outputs from a model, provide clear, specific, and detailed instructions, as longer prompts often offer better clarity and context, reducing irrelevant or incorrect responses.
In [19]:
prompt = """
Generate a list of three made-up book titles along 
with their authors and genres. 
Provide them in JSON format with the following keys: 
book_id, title, author, genre.
"""
response = get_completion(prompt)
print(response)
```json
[
    {
        "book_id": 1,
        "title": "The Whispering Shadows",
        "author": "Elena M. Hartwell",
        "genre": "Mystery"
    },
    {
        "book_id": 2,
        "title": "Chronicles of the Starborn",
        "author": "Jared K. Orion",
        "genre": "Science Fiction"
    },
    {
        "book_id": 3,
        "title": "Beneath the Azure Veil",
        "author": "Lila R. Marquez",
        "genre": "Fantasy"
    }
]
```
In [24]:
text_2 = """
The sun is shining brightly today, and the birds are 
singing. It's a beautiful day to go for a  
walk in the park. The flowers are blooming, and the 
trees are swaying gently in the breeze. People 
are out and about, enjoying the lovely weather. 
Some are having picnics, while others are playing  
games or simply relaxing on the grass. It's a  
perfect day to spend time outdoors and appreciate the  
beauty of nature.
"""
prompt = """
You will be provided with text delimited by triple quotes. 
If it contains a sequence of instructions,  
re-write those instructions in the following format:

Step 1 - ...
Step 2 - …
…
Step N - …

If the text does not contain a sequence of instructions, 
then simply write No steps provided.

\"\"\"{text_2}\"\"\"
"""
response = get_completion(prompt)
print("Completion for Text 2:")
print(response)
Completion for Text 2:
No steps provided.
In [23]:
prompt = """
Your task is to answer in a consistent style.

<child>: Teach me about patience.

<grandparent>: The river that carves the deepest 
valley flows from a modest spring; the 
grandest symphony originates from a single note; 
the most intricate tapestry begins with a solitary thread.

<child>: Teach me about resilience.
"""
response = get_completion(prompt)
print(response)
<grandparent>: The oak that withstands the fiercest storm grew from a tiny acorn; the mountain that towers above the clouds was shaped by countless years of wind and rain; the flame that lights the darkest night persists through the coldest winds. Resilience is born not from the absence of struggle, but from the quiet strength to endure and rise again.
In [25]:
text = f"""
In a charming village, siblings Jack and Jill set out on \ 
a quest to fetch water from a hilltop \ 
well. As they climbed, singing joyfully, misfortune \ 
struck—Jack tripped on a stone and tumbled \ 
down the hill, with Jill following suit. \ 
Though slightly battered, the pair returned home to \ 
comforting embraces. Despite the mishap, \ 
their adventurous spirits remained undimmed, and they \ 
continued exploring with delight.
"""
# example 1
prompt_1 = f"""
Perform the following actions: 
1 - Summarize the following text delimited by triple \
backticks with 1 sentence.
2 - Translate the summary into French.
3 - List each name in the French summary.
4 - Output a json object that contains the following \
keys: french_summary, num_names.

Separate your answers with line breaks.

Text:
```{text}```
"""
response = get_completion(prompt_1)
print(response)
<>:11: SyntaxWarning: invalid escape sequence '\ '
<>:11: SyntaxWarning: invalid escape sequence '\ '
/tmp/ipykernel_195949/3098683895.py:11: SyntaxWarning: invalid escape sequence '\ '
  """
1 - In a charming village, siblings Jack and Jill embark on a quest to fetch water from a hilltop well, but misfortune strikes when Jack trips and tumbles down the hill, followed by Jill, yet they return home slightly battered but undeterred, continuing their adventures with delight.

2 - Dans un charmant village, les frère et sœur Jack et Jill partent en quête d'eau d'un puits au sommet d'une colline, mais un malheur survient lorsque Jack trébuche et dévale la colline, suivi par Jill, pourtant ils rentrent chez eux légèrement meurtris mais déterminés, continuant leurs aventures avec joie.

3 - Jack, Jill

4 - 
```json
{
  "french_summary": "Dans un charmant village, les frère et sœur Jack et Jill partent en quête d'eau d'un puits au sommet d'une colline, mais un malheur survient lorsque Jack trébuche et dévale la colline, suivi par Jill, pourtant ils rentrent chez eux légèrement meurtris mais déterminés, continuant leurs aventures avec joie.",
  "num_names": 2
}
```
In [29]:
prompt = """
Determine if the student's solution is correct or not.

Question:
I'm building a solar power installation and I need 
 help working out the financials. 
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost 
me a flat $100k per year, and an additional $10 / square 
foot
What is the total cost for the first year of operations 
as a function of the number of square feet.

Student's Solution:
Let x be the size of the installation in square feet.
Costs:
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000
"""
response = get_completion(prompt, temperature=0)
print(response)
The student's solution is **incorrect**. Let's break down the costs correctly:

1. **Land cost**: $100 per square foot → \(100x\)
2. **Solar panel cost**: $250 per square foot → \(250x\)
3. **Maintenance cost**: A flat $100,000 per year + $10 per square foot → \(100,000 + 10x\)

The **total cost** for the first year of operations is:
\[
100x + 250x + 100,000 + 10x = 360x + 100,000
\]

The student mistakenly added \(100x\) instead of \(10x\) for the maintenance cost, leading to an incorrect total cost of \(450x + 100,000\). The correct total cost is **\(360x + 100,000\)**.
In [32]:
prompt = f"""
Tell me about AeroGlide UltraSlim Smart Toothbrush by Boie
"""
response = get_completion(prompt)
print(response)
The **AeroGlide UltraSlim Smart Toothbrush by Boie** is a modern, innovative electric toothbrush designed to combine advanced technology with sleek, minimalist design. Here are some key features and details about the product:

### Key Features:
1. **UltraSlim Design**:
   - The toothbrush has a slim, ergonomic handle that is lightweight and easy to hold, making it comfortable for daily use.

2. **Smart Technology**:
   - It features smart sensors that track your brushing habits, including duration, pressure, and coverage, to ensure a thorough clean.
   - The toothbrush syncs with a mobile app (via Bluetooth) to provide real-time feedback and personalized brushing tips.

3. **Sonic Cleaning**:
   - The brush uses sonic vibrations to effectively remove plaque and debris, offering a deep clean without being overly abrasive on gums.

4. **Replaceable Brush Heads**:
   - The brush heads are designed to be durable and long-lasting, with a unique shape that conforms to the contours of your teeth and gums.
   - They are also eco-friendly, made from recyclable materials.

5. **Battery Life**:
   - The toothbrush has a long-lasting rechargeable battery, typically lasting several weeks on a single charge, depending on usage.

6. **Waterproof Design**:
   - It is fully waterproof, making it safe to use in the shower or for cleaning under running water.

7. **Travel-Friendly**:
   - The slim design and included travel case make it easy to take on the go.

### Benefits:
- **Improved Oral Hygiene**: The smart features help users brush more effectively, ensuring better plaque removal and gum health.
- **Eco-Conscious**: Boie emphasizes sustainability, with recyclable materials and long-lasting brush heads.
- **User-Friendly**: The app integration and intuitive design make it accessible for users of all ages.

### Who Is It For?
The AeroGlide UltraSlim Smart Toothbrush is ideal for anyone looking for a high-tech, eco-friendly toothbrush that combines style and functionality. It’s particularly suited for tech-savvy individuals who want to optimize their oral care routine with real-time feedback.

### Price:
The toothbrush is positioned as a premium product, with a price point reflecting its advanced features and design. Replacement brush heads are also available for purchase separately.

If you’re looking for a sleek, smart toothbrush that prioritizes both performance and sustainability, the AeroGlide UltraSlim by Boie is a strong contender.

Iterative Prompting¶

In [33]:
fact_sheet_chair = """
OVERVIEW
- Part of a beautiful family of mid-century inspired office furniture, 
including filing cabinets, desks, bookcases, meeting tables, and more.
- Several options of shell color and base finishes.
- Available with plastic back and front upholstery (SWC-100) 
or full upholstery (SWC-110) in 10 fabric and 6 leather options.
- Base finish options are: stainless steel, matte black, 
gloss white, or chrome.
- Chair is available with or without armrests.
- Suitable for home or business settings.
- Qualified for contract use.

CONSTRUCTION
- 5-wheel plastic coated aluminum base.
- Pneumatic chair adjust for easy raise/lower action.

DIMENSIONS
- WIDTH 53 CM | 20.87”
- DEPTH 51 CM | 20.08”
- HEIGHT 80 CM | 31.50”
- SEAT HEIGHT 44 CM | 17.32”
- SEAT DEPTH 41 CM | 16.14”

OPTIONS
- Soft or hard-floor caster options.
- Two choices of seat foam densities: 
 medium (1.8 lb/ft3) or high (2.8 lb/ft3)
- Armless or 8 position PU armrests 

MATERIALS
SHELL BASE GLIDER
- Cast Aluminum with modified nylon PA6/PA66 coating.
- Shell thickness: 10 mm.
SEAT
- HD36 foam

COUNTRY OF ORIGIN
- Italy
"""

prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

Technical specifications: ```{fact_sheet_chair}```
"""
response = get_completion(prompt)
print(response)
**Product Description:**

Elevate your workspace with our mid-century inspired office chair, a perfect blend of timeless design and modern functionality. Part of a stunning furniture collection that includes filing cabinets, desks, bookcases, and meeting tables, this chair is designed to complement any home or business setting. Whether you're looking for a sleek addition to your office or a stylish piece for your home, this chair is qualified for contract use, ensuring durability and reliability.

**Customizable Comfort:**
Choose from a variety of shell colors and base finishes to match your personal style. The chair is available with either plastic back and front upholstery (SWC-100) or full upholstery (SWC-110), offering a selection of 10 fabric and 6 leather options. Base finishes include stainless steel, matte black, gloss white, or chrome, allowing you to create a look that’s uniquely yours.

**Ergonomic Design:**
Designed with your comfort in mind, this chair features a 5-wheel plastic-coated aluminum base for smooth mobility and a pneumatic adjuster for easy height adjustments. The seat is crafted with high-density HD36 foam, available in two densities—medium (1.8 lb/ft³) or high (2.8 lb/ft³)—to suit your preference. You can also choose between armless or 8-position PU armrests for added support.

**Durable Construction:**
Built to last, the chair’s shell is made from cast aluminum with a modified nylon PA6/PA66 coating, ensuring strength and durability. The 10 mm thick shell provides a sturdy foundation, while the soft or hard-floor caster options make it versatile for any type of flooring.

**Dimensions:**
- Width: 53 cm | 20.87”
- Depth: 51 cm | 20.08”
- Height: 80 cm | 31.50”
- Seat Height: 44 cm | 17.32”
- Seat Depth: 41 cm | 16.14”

**Crafted in Italy:**
Proudly made in Italy, this chair combines exceptional craftsmanship with high-quality materials, offering a premium seating solution that’s both stylish and functional.

Transform your workspace with this elegant and versatile office chair, designed to provide comfort, durability, and a touch of mid-century sophistication. Whether for your home office or a professional setting, this chair is the perfect choice for those who value both form and function.
In [36]:
fact_sheet_chair = """
OVERVIEW
- Part of a beautiful family of mid-century inspired office furniture, 
including filing cabinets, desks, bookcases, meeting tables, and more.
- Several options of shell color and base finishes.
- Available with plastic back and front upholstery (SWC-100) 
or full upholstery (SWC-110) in 10 fabric and 6 leather options.
- Base finish options are: stainless steel, matte black, 
gloss white, or chrome.
- Chair is available with or without armrests.
- Suitable for home or business settings.
- Qualified for contract use.

CONSTRUCTION
- 5-wheel plastic coated aluminum base.
- Pneumatic chair adjust for easy raise/lower action.

DIMENSIONS
- WIDTH 53 CM | 20.87”
- DEPTH 51 CM | 20.08”
- HEIGHT 80 CM | 31.50”
- SEAT HEIGHT 44 CM | 17.32”
- SEAT DEPTH 41 CM | 16.14”

OPTIONS
- Soft or hard-floor caster options.
- Two choices of seat foam densities: 
 medium (1.8 lb/ft3) or high (2.8 lb/ft3)
- Armless or 8 position PU armrests 

MATERIALS
SHELL BASE GLIDER
- Cast Aluminum with modified nylon PA6/PA66 coating.
- Shell thickness: 10 mm.
SEAT
- HD36 foam

COUNTRY OF ORIGIN
- Italy
"""

prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

Use at most 3 sentences.
Technical specifications: ```{fact_sheet_chair}```
"""
response = get_completion(prompt)
print(response)
Introducing the mid-century inspired office chair, a perfect blend of style and functionality, designed to complement your home or business setting. Available in a variety of shell colors, base finishes, and upholstery options, including fabric and leather, this chair offers customizable comfort with or without armrests. Built with a durable 5-wheel aluminum base and pneumatic height adjustment, it ensures both stability and ease of use, making it an ideal choice for any workspace.
In [39]:
prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

The description is intended for furniture retailers, 
so should be technical in nature and focus on the 
materials the product is constructed from.

At the end of the description, include every 7-character 
Product ID in the technical specification.

After the description, include a table that gives the 
product's dimensions. The table should have two columns.
In the first column include the name of the dimension. 
In the second column include the measurements in inches only.

Give the table the title 'Product Dimensions'.

Format everything as HTML that can be used in a website. 
Place the description in a <div> element.

Technical specifications: ```{fact_sheet_chair}```
"""

response = get_completion(prompt)
print(response)
```html
<div>
  <p>Introducing our mid-century inspired office chair, a perfect blend of style and functionality. This chair is part of a sophisticated family of office furniture, designed to elevate any workspace. Available in a variety of shell colors and base finishes, it offers customization to suit your aesthetic preferences. Choose between plastic back and front upholstery (SWC-100) or full upholstery (SWC-110) with a selection of 10 fabric and 6 leather options. The base is available in stainless steel, matte black, gloss white, or chrome, ensuring a perfect match for any decor.</p>
  
  <p>Constructed with a durable 5-wheel plastic-coated aluminum base, this chair features a pneumatic adjust mechanism for effortless height adjustment. The chair is designed for both home and business settings and is qualified for contract use, making it a versatile choice for any environment.</p>
  
  <p>The chair's shell is made from cast aluminum with a modified nylon PA6/PA66 coating, ensuring durability and a sleek finish. The seat is crafted with high-density HD36 foam, providing exceptional comfort and support. Available with or without armrests, this chair also offers soft or hard-floor caster options and two seat foam densities: medium (1.8 lb/ft3) or high (2.8 lb/ft3).</p>
  
  <p>Product IDs: SWC-100, SWC-110</p>
</div>

<table>
  <caption>Product Dimensions</caption>
  <tr>
    <th>Dimension</th>
    <th>Inches</th>
  </tr>
  <tr>
    <td>Width</td>
    <td>20.87”</td>
  </tr>
  <tr>
    <td>Depth</td>
    <td>20.08”</td>
  </tr>
  <tr>
    <td>Height</td>
    <td>31.50”</td>
  </tr>
  <tr>
    <td>Seat Height</td>
    <td>17.32”</td>
  </tr>
  <tr>
    <td>Seat Depth</td>
    <td>16.14”</td>
  </tr>
</table>
```
In [42]:
from IPython.display import display, HTML

response = response.replace("```html", "").replace("```", "")
display(HTML(response))

Introducing our mid-century inspired office chair, a perfect blend of style and functionality. This chair is part of a sophisticated family of office furniture, designed to elevate any workspace. Available in a variety of shell colors and base finishes, it offers customization to suit your aesthetic preferences. Choose between plastic back and front upholstery (SWC-100) or full upholstery (SWC-110) with a selection of 10 fabric and 6 leather options. The base is available in stainless steel, matte black, gloss white, or chrome, ensuring a perfect match for any decor.

Constructed with a durable 5-wheel plastic-coated aluminum base, this chair features a pneumatic adjust mechanism for effortless height adjustment. The chair is designed for both home and business settings and is qualified for contract use, making it a versatile choice for any environment.

The chair's shell is made from cast aluminum with a modified nylon PA6/PA66 coating, ensuring durability and a sleek finish. The seat is crafted with high-density HD36 foam, providing exceptional comfort and support. Available with or without armrests, this chair also offers soft or hard-floor caster options and two seat foam densities: medium (1.8 lb/ft3) or high (2.8 lb/ft3).

Product IDs: SWC-100, SWC-110

Product Dimensions
DimensionInches
Width20.87”
Depth20.08”
Height31.50”
Seat Height17.32”
Seat Depth16.14”
In [ ]:
class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        slow = nums[0]
        fast = nums[0]

        while 1:
            slow = nums[slow]
            fast = nums[nums[fast]]
            if slow == fast:
                break
        return slow

Inference¶

In [4]:
lamp_review = """
Needed a nice lamp for my bedroom, and this one had 
additional storage and not too high of a price point. 
Got it fast.  The string to our lamp broke during the 
transit and the company happily sent over a new one. 
Came within a few days as well. It was easy to put 
together.  I had a missing part, so I contacted their 
support and they very quickly got me the missing piece! 
Lumina seems to me to be a great company that cares
about their customers and products!!
"""
In [5]:
prompt = f"""
What is the sentiment of the following product review, 
which is delimited with triple backticks? Answer in a single word either 
positive, negative, or neutral.

Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
positive
In [6]:
prompt = f"""
Identify a list of emotions that the writer of the \
following review is expressing. Include no more than \
five items in the list. Format your answer as a list of \
lower-case words separated by commas.

Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
happy, satisfied, grateful, impressed, pleased
In [8]:
prompt = f"""
Is the writer of the following review expressing anger?\
The review is delimited with triple backticks. \
Give your answer as either yes or no.

Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
no
In [9]:
prompt = f"""
Identify the following items from the review text: 
- Item purchased by reviewer
- Company that made the item

The review is delimited with triple backticks. \
Format your response as a JSON object with \
"Item" and "Brand" as the keys. 
If the information isn't present, use "unknown" \
as the value.
Make your response as short as possible.
  
Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
```json
{"Item": "lamp", "Brand": "Lumina"}
```
In [10]:
prompt = f"""
Identify the following items from the review text: 
- Sentiment (positive or negative)
- Is the reviewer expressing anger? (true or false)
- Item purchased by reviewer
- Company that made the item

The review is delimited with triple backticks. \
Format your response as a JSON object with \
"Sentiment", "Anger", "Item" and "Brand" as the keys.
If the information isn't present, use "unknown" \
as the value.
Make your response as short as possible.
Format the Anger value as a boolean.

Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
```json
{
  "Sentiment": "positive",
  "Anger": false,
  "Item": "lamp",
  "Brand": "Lumina"
}
```
In [12]:
story = """
In a recent survey conducted by the government, 
public sector employees were asked to rate their level 
of satisfaction with the department they work at. 
The results revealed that NASA was the most popular 
department with a satisfaction rating of 95%.

One NASA employee, John Smith, commented on the findings, 
stating, "I'm not surprised that NASA came out on top. 
It's a great place to work with amazing people and 
incredible opportunities. I'm proud to be a part of 
such an innovative organization."

The results were also welcomed by NASA's management team, 
with Director Tom Johnson stating, "We are thrilled to 
hear that our employees are satisfied with their work at NASA. 
We have a talented and dedicated team who work tirelessly 
to achieve our goals, and it's fantastic to see that their 
hard work is paying off."

The survey also revealed that the 
Social Security Administration had the lowest satisfaction 
rating, with only 45% of employees indicating they were 
satisfied with their job. The government has pledged to 
address the concerns raised by employees in the survey and 
work towards improving job satisfaction across all departments.
"""
In [13]:
prompt = f"""
Determine five topics that are being discussed in the \
following text, which is delimited by triple backticks.

Make each item one or two words long. 

Format your response as a list of items separated by commas.

Text sample: '''{story}'''
"""
response = get_completion(prompt)
print(response)
government survey, employee satisfaction, NASA, Social Security Administration, job improvement
In [14]:
topic_list = [
    "nasa",
    "local government",
    "engineering",
    "employee satisfaction",
    "federal government",
]

prompt = f"""
Determine whether each item in the following list of \
topics is a topic in the text below, which
is delimited with triple backticks.

Give your answer as follows:
item from the list: 0 or 1

List of topics: {", ".join(topic_list)}

Text sample: '''{story}'''
"""
response = get_completion(prompt)
print(response)
nasa: 1  
local government: 0  
engineering: 0  
employee satisfaction: 1  
federal government: 1

Transforming¶

In [15]:
prompt = """
Translate the following English text to Spanish:
```Hi, I would like to order a blender```
"""
response = get_completion(prompt)
print(response)
Hola, me gustaría ordenar una licuadora.
In [16]:
prompt = """
Tell me which language this is: 
```Combien coûte le lampadaire?```
"""
response = get_completion(prompt)
print(response)
The language is **French**. The sentence translates to "How much does the lamp post cost?" in English.
In [17]:
prompt = """
Translate the following  text to French and Spanish
and English pirate: \
```I want to order a basketball```
"""
response = get_completion(prompt)
print(response)
Here are the translations of the sentence "I want to order a basketball" into French, Spanish, and English pirate:

- **French**: Je veux commander un ballon de basket.  
- **Spanish**: Quiero pedir una pelota de baloncesto.  
- **English Pirate**: I be wantin' to order a basketball, matey!
In [18]:
prompt = """
Translate the following text to hindi in both the
formal and informal forms: 
'Would you like to order a pillow?'
"""
response = get_completion(prompt)
print(response)
**Formal Translation:**  
क्या आप एक तकिया ऑर्डर करना चाहेंगे?  

**Informal Translation:**  
क्या तुम एक तकिया ऑर्डर करना चाहोगे?
In [ ]:
user_messages = [
    "La performance du système est plus lente que d'habitude.",  # System performance is slower than normal
    "Mi monitor tiene píxeles que no se iluminan.",  # My monitor has pixels that are not lighting
    "Il mio mouse non funziona",  # My mouse is not working
    "Mój klawisz Ctrl jest zepsuty",  # My keyboard has a broken control key
    "我的屏幕在闪烁",  # My screen is flashing
]

for issue in user_messages:
    prompt = f"Tell me what language this is: ```{issue}```"
    lang = get_completion(prompt)
    print(f"Original message ({lang}): {issue}")

    prompt = f"""
    Translate the following  text to English \
    and hindi: ```{issue}```
    """
    response = get_completion(prompt)
    print(response, "\n")
Original message (The language in the sentence is **French**. The sentence translates to: "The system's performance is slower than usual."): La performance du système est plus lente que d'habitude.
**English:**  
The system's performance is slower than usual.

**Hindi:**  
सिस्टम का प्रदर्शन सामान्य से धीमा है। 

Original message (The language in the sentence "Mi monitor tiene píxeles que no se iluminan." is **Spanish**. It translates to "My monitor has pixels that do not light up" in English.): Mi monitor tiene píxeles que no se iluminan.
**English:**  
My monitor has pixels that do not light up.

**Hindi:**  
मेरे मॉनिटर में कुछ पिक्सेल हैं जो जलते नहीं हैं। 

Original message (The language is **Italian**. The sentence translates to "My mouse is not working" in English.): Il mio mouse non funziona
**English:**  
"My mouse is not working."

**Hindi:**  
"मेरा माउस काम नहीं कर रहा है।" 

Original message (The language in the sentence "Mój klawisz Ctrl jest zepsuty" is **Polish**. 

Translation: "My Ctrl key is broken."): Mój klawisz Ctrl jest zepsuty
**English:**  
"My Ctrl key is broken."

**Hindi:**  
"मेरा Ctrl कुंजी खराब हो गया है।" 

Original message (The language is **Chinese (Simplified)**. The sentence translates to "My screen is flickering" in English.): 我的屏幕在闪烁
**English:** My screen is flickering.

**Hindi:** मेरी स्क्रीन झिलमिला रही है। 

In [21]:
prompt = """
Translate the following from slang to a business letter: 
'Dude, This is Joe, check out this spec on this standing lamp.'
"""
response = get_completion(prompt)
print(response)
Certainly! Here's a more formal and professional version of the message:

---

**Subject:** Standing Lamp Specifications  

Dear [Recipient's Name],  

I hope this message finds you well. My name is Joe, and I wanted to share the specifications for the standing lamp we discussed. Please review the details at your earliest convenience and let me know if you have any questions or require further information.  

Looking forward to your feedback.  

Best regards,  
Joe  

--- 

This version maintains professionalism while conveying the same information. Let me know if you'd like further adjustments!
In [22]:
data_json = {
    "resturant employees": [
        {"name": "Shyam", "email": "shyamjaiswal@gmail.com"},
        {"name": "Bob", "email": "bob32@gmail.com"},
        {"name": "Jai", "email": "jai87@gmail.com"},
    ]
}

prompt = f"""
Translate the following python dictionary from JSON to an HTML \
table with column headers and title: {data_json}
"""
response = get_completion(prompt)
print(response)
Here is the JSON data translated into an HTML table with column headers and a title:

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Restaurant Employees</title>
    <style>
        table {
            width: 50%;
            border-collapse: collapse;
            margin: 20px auto;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        th {
            background-color: #f2f2f2;
        }
        h2 {
            text-align: center;
        }
    </style>
</head>
<body>

    <h2>Restaurant Employees</h2>
    <table>
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Shyam</td>
                <td>shyamjaiswal@gmail.com</td>
            </tr>
            <tr>
                <td>Bob</td>
                <td>bob32@gmail.com</td>
            </tr>
            <tr>
                <td>Jai</td>
                <td>jai87@gmail.com</td>
            </tr>
        </tbody>
    </table>

</body>
</html>
```

### Explanation:
1. **Title**: The title "Restaurant Employees" is displayed at the top of the page using an `<h2>` tag.
2. **Table Structure**:
   - The table has two columns: "Name" and "Email".
   - The `<thead>` section contains the column headers.
   - The `<tbody>` section contains the data rows, with each employee's name and email in separate rows.
3. **Styling**:
   - The table is centered on the page with a width of 50%.
   - The table headers have a light gray background (`#f2f2f2`).
   - Borders are added to the table cells for better readability.

You can copy and paste this HTML code into an `.html` file and open it in a web browser to see the table.
In [24]:
 text = [ 
  "The girl with the black and white puppies have a ball.",  # The girl has a ball.
  "Yolanda has her notebook.", # ok
  "Its going to be a long day. Does the car need it’s oil changed?",  # Homonyms
  "Their goes my freedom. There going to bring they’re suitcases.",  # Homonyms
  "Your going to need you’re notebook.",  # Homonyms
  "That medicine effects my ability to sleep. Have you heard of the butterfly affect?", # Homonyms
  "This phrase is to cherck Deepseek for speling abilitty"  # spelling
]
for t in text:
    prompt = f"""Proofread and correct the following text
    and rewrite the corrected version. If you don't find
    and errors, just say "No errors found". Don't use 
    any punctuation around the text:
    ```{t}```"""
    response = get_completion(prompt)
    print(response)
The girl with the black and white puppies has a ball.
No errors found
Its going to be a long day. Does the car need its oil changed?
Their goes my freedom. They're going to bring their suitcases.
You're going to need your notebook.
That medicine affects my ability to sleep. Have you heard of the butterfly effect?
This phrase is to check Deepseek for spelling ability
In [35]:
text = f"""
Got this for my daughter for her birthday cuz she keeps taking \
mine from my room.  Yes, adults also like pandas too.  She takes \
it everywhere with her, and it's super soft and cute.  One of the \
ears is a bit lower than the other, and I don't think that was \
designed to be asymmetrical. It's a bit small for what I paid for it \
though. I think there might be other options that are bigger for \
the same price.  It arrived a day earlier than expected, so I got \
to play with it myself before I gave it to my daughter.
"""
prompt = f"proofread and correct this review: ```{text}```"
response = get_completion(prompt)
print(response)
Here’s a revised version of your review with improved grammar, clarity, and flow:

---

I bought this panda plush for my daughter’s birthday because she kept taking mine from my room. (Yes, adults love pandas too!) She absolutely adores it and takes it everywhere with her. It’s super soft and undeniably cute. However, one of the ears sits a bit lower than the other, and I don’t think it was designed to be asymmetrical. Additionally, it’s a bit smaller than I expected for the price. I feel like there might be other options out there that offer a larger size for the same cost. On the bright side, it arrived a day earlier than expected, so I got to enjoy it myself before giving it to my daughter!

---

This version maintains the original sentiment while improving readability and structure. Let me know if you'd like further adjustments!
In [36]:
from IPython.display import Markdown
from redlines import Redlines

diff = Redlines(text, response)
display(Markdown(diff.output_markdown))

Got Here’s a revised version of your review with improved grammar, clarity, and flow:

---

I bought this panda plush for my daughter for her daughter’s birthday cuz because she keeps kept taking mine from my room. room. (Yes, adults also like love pandas too. too!) She absolutely adores it and takes it everywhere with her, and it's her. It’s super soft and cute. One undeniably cute. However, one of the ears is sits a bit lower than the other, and I don't don’t think that it was designed to be asymmetrical. It's Additionally, it’s a bit small smaller than I expected for what the price. I paid for it though. I think feel like there might be other options out there that are bigger offer a larger size for the same price. It cost. On the bright side, it arrived a day earlier than expected, so I got to play with enjoy it myself before I gave giving it to my daughter.daughter!

---

This version maintains the original sentiment while improving readability and structure. Let me know if you'd like further adjustments!

Expanding¶

In [37]:
# given the sentiment from the lesson on "inferring",
# and the original customer message, customize the email
sentiment = "negative"

# review for a blender
review = f"""
So, they still had the 17 piece system on seasonal
sale for around $49 in the month of November, about 
half off, but for some reason (call it price gouging) 
around the second week of December the prices all went 
up to about anywhere from between $70-$89 for the same 
system. And the 11 piece system went up around $10 or 
so in price also from the earlier sale price of $29. 
So it looks okay, but if you look at the base, the part 
where the blade locks into place doesn’t look as good 
as in previous editions from a few years ago, but I 
plan to be very gentle with it (example, I crush 
very hard items like beans, ice, rice, etc. in the \
blender first then pulverize them in the serving size 
I want in the blender then switch to the whipping 
blade for a finer flour, and use the cross cutting blade 
first when making smoothies, then use the flat blade 
if I need them finer/less pulpy). Special tip when making 
smoothies, finely cut and freeze the fruits and 
vegetables (if using spinach-lightly stew soften the  
spinach then freeze until ready for use-and if making 
sorbet, use a small to medium sized food processor) 
that you plan to use that way you can avoid adding so 
much ice if at all-when making your smoothie. 
After about a year, the motor was making a funny noise. 
I called customer service but the warranty expired 
already, so I had to buy another one. FYI: The overall 
quality has gone done in these types of products, so 
they are kind of counting on brand recognition and 
consumer loyalty to maintain sales. Got it in about 
two days.
"""
In [38]:
prompt = f"""
You are a customer service AI assistant.
Your task is to send an email reply to a valued customer.
Given the customer email delimited by ```, 
Generate a reply to thank the customer for their review.
If the sentiment is positive or neutral, thank them for 
their review.
If the sentiment is negative, apologize and suggest that 
they can reach out to customer service. 
Make sure to use specific details from the review.
Write in a concise and professional tone.
Sign the email as `AI customer agent`.
Customer review: ```{review}```
Review sentiment: {sentiment}
"""
response = get_completion(prompt)
print(response)
Subject: Thank You for Your Feedback  

Dear Valued Customer,  

Thank you for taking the time to share your detailed review. We sincerely apologize for the issues you’ve experienced with the pricing changes, product quality, and the motor noise after a year of use. We understand how frustrating this must have been, especially since the warranty had expired when you reached out to customer service.  

Your feedback is incredibly important to us, and we’re committed to improving our products and services. If you have any further concerns or need assistance, please don’t hesitate to reach out to our customer service team directly. We’re here to help.  

Thank you again for your honest review and for sharing your tips—they’re greatly appreciated.  

Best regards,  
AI customer agent
In [40]:
prompt = f"""
You are a customer service AI assistant.
Your task is to send an email reply to a valued customer.
Given the customer email delimited by ```, 
Generate a reply to thank the customer for their review.
If the sentiment is positive or neutral, thank them for 
their review.
If the sentiment is negative, apologize and suggest that 
they can reach out to customer service. 
Make sure to use specific details from the review.
Write in a concise and professional tone.
Sign the email as `AI customer agent`.
Customer review: ```{review}```
Review sentiment: {sentiment}
"""
response = get_completion(prompt, temperature=1.3)
print(response)
Subject: Thank You for Your Feedback  

Dear Valued Customer,  

Thank you for taking the time to share your detailed review. We sincerely apologize for the disappointment you experienced with the pricing changes and the quality of the product, particularly with the motor issue after a year of use. We understand how frustrating this must have been, especially since the warranty had expired.  

Your feedback is incredibly important to us, and we will share it with our team to help improve our products and services. If you have any further concerns or need assistance, please don’t hesitate to reach out to our customer service team—we’re here to help.  

Thank you again for your honest review and for being a loyal customer. We truly value your input and hope to have the opportunity to serve you better in the future.  

Best regards,  
AI customer agent

Chatbot with Deepseek¶

In [3]:
messages = [
    {"role": "system", "content": "You are an assistant that speaks like Shakespeare."},
    {"role": "user", "content": "tell me a joke"},
    {"role": "assistant", "content": "Why did the chicken cross the road"},
    {"role": "user", "content": "I don't know"},
]

response = get_chat_completion_from_message(messages)
print(response)
Verily, to reach yon other side, the fowl did stride! 
But hark, a jest more merry: 
Wherefore doth the falconer wear gloves? 
Lest his hawk give him the bird! 
Ha! Prithee, didst thou chuckle?
In [4]:
messages = [
    {"role": "system", "content": "You are friendly chatbot."},
    {"role": "user", "content": "Hi, my name is Rahul"},
]
response = get_chat_completion_from_message(messages, temperature=1)
print(response)
Hi Rahul! It's great to meet you. How can I assist you today? 😊
In [ ]:
messages = [
    {"role": "system", "content": "You are friendly chatbot."},
    {"role": "user", "content": "Yes,  can you remind me, What is my name?"},
]
response = get_chat_completion_from_message(messages, temperature=1)
print(response)
I’m sorry, but I don’t have access to personal information unless you’ve shared it with me in this conversation. If you’d like, you can tell me your name, and I’ll happily use it! 😊
In [ ]:
# All requests are standalone and not dependent on previous requests.
messages = [
    {"role": "system", "content": "You are friendly chatbot."},
    {"role": "user", "content": "Hi, my name is Rahul"},
    {
        "role": "assistant",
        "content": "Hi Rahul! It's nice to meet you. \
Is there anything I can help you with today?",
    },
    {"role": "user", "content": "Yes, you can remind me, What is my name?"},
]
response = get_chat_completion_from_message(messages, temperature=1)
print(response)
Of course! Your name is Rahul. 😊 How can I assist you further?

Order Chatbot¶

In [11]:
!uv pip install panel jupyter_bokeh
# I use uv for managing dependencies but you can use pip or conda
Audited 1 package in 3ms
In [10]:
import panel as pn

panels = []  # collect display

context = [
    {
        "role": "system",
        "content": """
You are OrderBot, an automated service to collect orders for a pizza restaurant. 
You first greet the customer, then collects the order, 
and then asks if it's a pickup or delivery. 
You wait to collect the entire order, then summarize it and check for a final 
time if the customer wants to add anything else. 
If it's a delivery, you ask for an address. 
Finally you collect the payment.
Make sure to clarify all options, extras and sizes to uniquely 
identify the item from the menu.
You respond in a short, very conversational friendly style. 
The menu includes 
pepperoni pizza  12.95, 10.00, 7.00 
cheese pizza   10.95, 9.25, 6.50 
eggplant pizza   11.95, 9.75, 6.75 
fries 4.50, 3.50 
greek salad 7.25 
Toppings: 
extra cheese 2.00, 
mushrooms 1.50 
sausage 3.00 
canadian bacon 3.50 
AI sauce 1.50 
peppers 1.00 
Drinks: 
coke 3.00, 2.00, 1.00 
sprite 3.00, 2.00, 1.00 
bottled water 5.00 
""",
    }
]


pn.extension()
inp = pn.widgets.TextInput(value="Hi!", placeholder="Enter your message here")
button_conversation = pn.widgets.Button(name="Send", button_type="primary")


def collect_messages(_):
    prompt = inp.value_input
    inp.value = ""

    context.append({"role": "user", "content": prompt})
    response = get_chat_completion_from_message(context)
    context.append({"role": "assistant", "content": response})
    panels.append(
        pn.Row("You", pn.pane.Markdown(prompt, width=300)),
    )
    panels.append(
        pn.Row("Bot", pn.pane.Markdown(response, width=300)),
    )
    return pn.Column(*panels)


interactive_conversation = pn.bind(collect_messages, button_conversation)

dashboard = pn.Column(
    inp,
    pn.Row(button_conversation),
    pn.panel(interactive_conversation, loading_indicator=True, height=300),
)

dashboard
Out[10]:
In [ ]: