I can't get the BARD endpoint to work... Any one have any suggestions on how to get this to work? Below is the code:
import requests import json import speech_recognition as sr import pyttsx3
BARD_API_URL = "https://ai.google/bard" # Replace with the actual Bard API endpoint REQUEST_TIMEOUT = 10 # Set the timeout to 10 seconds – gives the system time to respond
def listen_to_microphone(device_index=None): recognizer = sr.Recognizer()
try:
with sr.Microphone(device_index=device_index) as source:
print("Using microphone:", source)
print("Listening...")
audio = recognizer.listen(source, timeout=5) # Set a timeout of 5 seconds
print("Audio recorded successfully.")
except OSError:
print("Error: Microphone not found or inaccessible.")
return None
try:
print("Recognizing...")
text = recognizer.recognize_google(audio)
print("You said:", text)
return text
except sr.UnknownValueError:
print("Could not understand audio.")
return None
except sr.RequestError as e:
print("Could not request results; {0}".format(e))
return None
def get_bard_response(query): headers = { "Content-Type": "application/json" } data = { "text": query }
try:
# Modified the requests.post() function call to include the timeout parameter
response = requests.post(BARD_API_URL, headers=headers, data=json.dumps(data), timeout=REQUEST_TIMEOUT)
if response.status_code == 200:
# Check if the response is a valid JSON object
if json.loads(response.content):
return response.json().get('response', 'Could not fetch response from Bard.')
else:
return "Error: Invalid JSON response from Bard."
else:
return f"Error: {response.status_code} - {response.text}"
except requests.exceptions.Timeout:
return "Error: Request timed out."
def speak(text): engine = pyttsx3.init()
try:
engine.say(text)
engine.runAndWait()
except Exception as e:
print("Error: Could not speak text:", e)
if name == "main": speak("Hello! How can I assist you today?")
while True:
user_input = listen_to_microphone()
if user_input:
if user_input.lower() == "exit":
speak("Goodbye!")
break
# Call Bard API to get a response based on the user's input
bard_response = get_bard_response(user_input)
speak(bard_response)
Well, I have tried different versions of using Bard endpoints, and I can't get them to work - I usually get a 404 error code. I am aware that the BARD endpoint is probably not correct, but I can't find an endpoint that works.