ChatGPT — Here Comes Google Bard!

Devil’s Advocate
8 min readMay 12, 2023

Google Bard has been released (in some countries) for people to use and experience the AI that Google is pushing as the primary competition to ChatGPT.

I tried it just now and found it to be fairly decent. It is not as verbose as ChatGPT is but is not bad at all either!

I had earlier posted on generating Python Code with ChatGPT.

https://medium.com/@bigfundu/chatgpt-otp-code-generator-4fb77de5e01b

Here is a similar example with Google Bard.

Me: How to generate OTPs and validate them via API in Python?

Bard: To generate OTPs and validate them via API in Python, you can use the following steps:

Install the pyotp library.

Create a pyotp.TOTP object for the desired OTP generator.

Generate an OTP code.

Send the OTP code to the user.

The user enters the OTP code into the application.

The application validates the OTP code against the pyotp.TOTP object.

If the OTP code is valid, the application proceeds with the requested action.

If the OTP code is invalid, the application displays an error message.

Here is an example of how to generate and validate an OTP in Python:

import pyotp# Create a TOTP object for the Google Authenticator generator.
totp = pyotp.TOTP('otpauth://totp/example@example.com?secret=ABCDEFGHIJKL')
# Generate an OTP code.
otp_code = totp.now()
# Send the OTP code to the user.
print('The OTP code is: {}'.format(otp_code))
# The user enters the OTP code into the application.
user_otp_code = input('Enter the OTP code: ')
# Validate the OTP code.
if totp.verify(user_otp_code):
print('The OTP code is valid.')
else:
print('The OTP code is invalid.')

This is just a basic example of how to generate and validate OTPs in Python. There are many other ways to do this, and the best approach will vary depending on your specific needs.

I probed Bard further to see what it can do with the same context.

Me: Can this same example be changed to use FastAPI with Python?

Bard: Sure, here is an example of how to generate and validate an OTP using FastAPI with Python:

from fastapi import FastAPI, Depends, HTTPException
from pyotp import TOTP
app = FastAPI()
# Create a TOTP object for the Google Authenticator generator.
totp = TOTP('otpauth://totp/example@example.com?secret=ABCDEFGHIJKL')
@app.post("/generate-otp")
async def generate_otp():
# Generate an OTP code.
otp_code = totp.now()
# Send the OTP code to the user.
return {"otp_code": otp_code}
@app.post("/validate-otp")
async def validate_otp(user_otp_code: str):
# Validate the OTP code.
if totp.verify(user_otp_code):
return {"valid": True}
else:
raise HTTPException(status_code=401, detail="Invalid OTP code")

This is just a basic example of how to generate and validate OTPs using FastAPI with Python. There are many other ways to do this, and the best approach will vary depending on your specific needs.

Building on this prompt, I pushed Bard further to include error handling.

Me: Can you also add comments to this code and add exception handling?

Bard: Sure, here is the code with comments and exception handling:

from fastapi import FastAPI, Depends, HTTPException
from pyotp import TOTP

app = FastAPI()
# Create a TOTP object for the Google Authenticator generator.
totp = TOTP('otpauth://totp/example@example.com?secret=ABCDEFGHIJKL')
# This endpoint generates an OTP code.
@app.post("/generate-otp")
async def generate_otp():
"""Generates an OTP code."""
# Generate an OTP code.
otp_code = totp.now()
# Send the OTP code to the user.
return {"otp_code": otp_code}
# This endpoint validates an OTP code.
@app.post("/validate-otp")
async def validate_otp(user_otp_code: str):
"""Validates an OTP code."""
# Validate the OTP code.
try:
if totp.verify(user_otp_code):
return {"valid": True}
else:
raise HTTPException(status_code=401, detail="Invalid OTP code")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))

This code adds comments to explain what each section of code does. It also adds exception handling to catch any errors that may occur. This will help to ensure that the code is more robust and reliable.

And finally, added some test cases to this code as well.

Me: Can you generate test cases for this code?

Bard: Sure, here are some test cases for this code:

import pytest
from fastapi import FastAPI, Depends, HTTPException
from pyotp import TOTP

app = FastAPI()
# Create a TOTP object for the Google Authenticator generator.
totp = TOTP('otpauth://totp/example@example.com?secret=ABCDEFGHIJKL')
# This endpoint generates an OTP code.
@app.post("/generate-otp")
async def generate_otp():
"""Generates an OTP code."""
# Generate an OTP code.
otp_code = totp.now()
# Send the OTP code to the user.
return {"otp_code": otp_code}
# This endpoint validates an OTP code.
@app.post("/validate-otp")
async def validate_otp(user_otp_code: str):
"""Validates an OTP code."""
# Validate the OTP code.
try:
if totp.verify(user_otp_code):
return {"valid": True}
else:
raise HTTPException(status_code=401, detail="Invalid OTP code")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))

@pytest.mark.asyncio
async def test_generate_otp():
# Test that the generate_otp endpoint generates an OTP code.
response = await app.post("/generate-otp")
assert response.status_code == 200
assert response.json() == {"otp_code": "123456"}

@pytest.mark.asyncio
async def test_validate_otp_valid_code():
# Test that the validate_otp endpoint validates a valid OTP code.
response = await app.post("/validate-otp", json={"user_otp_code": "123456"})
assert response.status_code == 200
assert response.json() == {"valid": True}

@pytest.mark.asyncio
async def test_validate_otp_invalid_code():
# Test that the validate_otp endpoint rejects an invalid OTP code.
response = await app.post("/validate-otp", json={"user_otp_code": "654321"})
assert response.status_code == 401
assert response.json() == {"detail": "Invalid OTP code"}

These test cases will help to ensure that the code is working as expected.

But Bard is not yet there when it comes to general Math and Science problem-solving. ChatGPT is currently way better (not perfect) on this front.

Here are two examples of how ChatGPT performed and how Bard did against the same problem statements.

— — — — — — — — — — — —

Prompt 1: the work done to raise a mass m from the surface of the earth to a height h which is equal to the radius of earth R is ? Please write in English language.

Bard: The work done to raise a mass m from the surface of the earth to a height h which is equal to the radius of earth R is:

Code snippet

W = mgR

Where:

W is the work done in joules

m is the mass of the object in kilograms

g is the acceleration due to gravity on Earth’s surface, which is approximately 9.8 m/s²

R is the radius of the Earth, which is approximately 6,371 km

The work done is equal to the change in potential energy of the object. The potential energy of an object is given by the following equation:

U = mgh

Where:

U is the potential energy in joules

m is the mass of the object in kilograms

g is the acceleration due to gravity on Earth’s surface, which is approximately 9.8 m/s²

h is the height of the object above the surface of the Earth in meters

In this case, the height of the object is equal to the radius of the Earth. Therefore, the potential energy of the object is:

U = mgR

The work done to raise the object is equal to the change in potential energy. Therefore, the work done is:

W = U_final - U_initial = mgR - 0 = mgR

— —

ChatGPT: To calculate the work done (W) in raising a mass (m) from the Earth’s surface to a height (h) equal to the Earth’s radius (R), we need to consider the change in gravitational potential energy. The work done is equal to the difference in gravitational potential energy between the initial and final positions.

At the Earth’s surface, the gravitational potential energy (U1) is:

U1 = -G * (M * m) / R

Where G is the gravitational constant (6.674 x 10^-11 N m²/kg²), M is the mass of Earth (approx. 5.972 x 10²⁴ kg), and R is the Earth’s radius.

At a height h equal to the Earth’s radius (h = R), the distance from the Earth’s center is 2R. The gravitational potential energy (U2) at this height is:

U2 = -G * (M * m) / (2R)

Now, we can find the work done (W) by calculating the change in gravitational potential energy:

W = U2 — U1

W = -G * (M * m) / (2R) — (-G * (M * m) / R)

To simplify, we can factor out the common terms:

W = (M * m * G) * (1/R — 1/(2R))

W = (M * m * G) * (1–1/2) / R

W = (M * m * G) * (1/2) / R

So, the work done to raise a mass m from the Earth’s surface to a height equal to the Earth’s radius R is:

W = (1/2) * G * M * m / R

— — — — — — — — — — — —

Prompt 2: When a block of mass M is suspended by a long wire of length L cm, the length of the wire becomes L+l cm. The elastic potential energy of the wire becomes what? Please write in English language.

Bard: Here is the answer in English:

When a block of mass M is suspended by a long wire of length L cm, the length of the wire becomes L+l cm. The elastic potential energy of the wire becomes:

U = 1/2 * k * (L+l)^2

Where k is the spring constant of the wire.

The elastic potential energy of the wire is stored in the wire as a result of the work done by the force of gravity on the block. The force of gravity stretches the wire, and the elastic potential energy is the energy stored in the wire as a result of this stretching.

The elastic potential energy of the wire can be calculated using the following formula:

U = 1/2 * k * x^2

Where U is the elastic potential energy, k is the spring constant of the wire, and x is the distance that the wire is stretched.

In this case, the distance that the wire is stretched is L+l cm. Therefore, the elastic potential energy of the wire is:

U = 1/2 * k * (L+l)^2

— —

ChatGPT: When a block of mass M is suspended by a long wire of length L cm, and the length of the wire increases by l cm (to L + l cm), the wire undergoes elastic deformation, storing elastic potential energy. The elastic potential energy (U) stored in the wire can be calculated using Hooke’s law and the formula for the potential energy of a spring:

U = (1/2) * k * x²

Here, k is the spring constant (or force constant) of the wire, and x is the elongation (l) of the wire.

To find the spring constant (k), we can use the following relation derived from Hooke’s law:

k = (F/x)

Here, F is the force applied to the wire, which is equal to the gravitational force acting on the block of mass M:

F = M * g

Where g is the acceleration due to gravity (approximately 9.81 m/s²).

Substituting the expression for the force into the equation for the spring constant:

k = (M * g) / l

Now, we can substitute this expression for the spring constant (k) into the formula for the elastic potential energy (U):

U = (1/2) * ((M * g) / l) * l²

Simplifying the equation:

U = (1/2) * M * g * l

The elastic potential energy (U) of the wire, when a block of mass M is suspended and the length of the wire increases by l cm, is:

U = (1/2) * M * g * l

Note that the lengths in this equation should be in meters (not cm) to match the units for g (m/s²). To convert L and l from cm to meters, divide their values by 100.

A few things I liked about Bard:

  • The context was well remembered and the conversation was carried out properly
  • Programming simple examples with Python was quick and easy (caveat: yet to explore fully with more complex examples)
  • It is not as verbose as ChatGPT but gives information quickly enough
  • The Python code was exportable to Google Colab for use (yet to test fully)

I am yet to test Bard on (will post separately):

  • Translating code into Multiple programming languages
  • Summarizing content
  • Validating information

--

--

Devil’s Advocate

Seeker for life. Looking to make technology simpler for everyone.