Continuing the discussion from I tried many newly generated keys but no one worked:
Your previously-posted error message demonstrates using nonexistent error parse methods.
Could it be using non-existent authentication methods when making an API call?
The kind of error that might be made by asking an AI to write API code instead of reading API documentation yourself?
Your API account also needs to be funded by purchasing credits first.
Here’s Python demonstration code, a function for calling the API and a main function that serves as a multi-question chatbot with it.
import os, httpx
def send_chat_request(conversation_messages):
# Set your API key in OPENAI_API_KEY env variable (never hard-code it).
api_key = os.environ.get("OPENAI_API_KEY")
if not api_key:
raise ValueError("Set OPENAI_API_KEY environment variable!")
api_url = "https://api.openai.com/v1/chat/completions"
headers = {"Authorization": f"Bearer {api_key}"}
payload = {"model": "gpt-4o-mini", "messages": conversation_messages,
"top_p": 0.9, "max_completion_tokens": 999}
try:
response = httpx.post(api_url, headers=headers, json=payload, timeout=180.0)
response.raise_for_status()
except Exception as error:
print("API error:", error)
return None
return response.json()["choices"][0]["message"]["content"]
def main():
conversation_history = [{"role": "developer", "content":
"You are a helpful AI assistant."}]
while True:
user_input = input("prompt> ")
if user_input.strip().lower() == "exit":
break
conversation_history.append({"role": "user", "content": user_input})
# Keep the developer message plus the last 10 exchanges (user+assistant).
messages_to_send = conversation_history[-(1 + 10 * 2):]
assistant_response = send_chat_request(messages_to_send)
if assistant_response is None:
print("Error retrieving API response.")
continue
print("assistant>", assistant_response)
conversation_history.append({"role": "assistant", "content": assistant_response})
if __name__ == "__main__":
main()
(type exit as prompt to leave the loop)
The code uses the common httpx
python library module, instead of the specialized openai
library SDK, so you can understand more closely what is being sent, such as authentication header.