Online Compiler Nasm

# Write your code here import os from openai import OpenAI # 1. Initialize the client. # It automatically looks for an environment variable named 'OPENAI_API_KEY' client = OpenAI( api_key=os.environ.get("OPENAI_API_KEY") ) # 2. Call the Chat Completions API response = client.chat.completions.create( model="gpt-4o", # You can also use "gpt-3.5-turbo" or "gpt-4" messages=[ {"role": "system", "content": "You are a helpful coding assistant."}, {"role": "user", "content": "Write a quick Python function to reverse a string."} ], temperature=0.7 # Controls randomness (0.0 is deterministic, 1.0 is creative) ) # 3. Print the text response from the AI print(response.choices[0].message.content) Use code with caution.Interactive Console ChatbotIf you want to create a continuous, loop-based chatbot in your terminal that remembers previous messages, use this framework:pythonimport os from openai import OpenAI client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) # Initialize conversation history with a persona messages = [ {"role": "system", "content": "You are a witty, helpful AI chatbot."} ] print("AI Chatbot Initialized! Type 'quit' or 'exit' to stop.\n") while True: user_input = input("me: ") # Check for exit commands if user_input.lower() in ['quit', 'exit']: print("Goodbye!") break if not user_input.strip(): continue # Append user message to history messages.append({"role": "user", "content": user_input}) try: # Request completion with full history response = client.chat.completions.create( model="gpt-4o", messages=messages ) # Extract and print reply ai_reply = response.choices[0].message.content print(f"\nAI: {ai_reply}\n") # Append AI reply to history so it retains context messages.append({"role": "assistant", "content": ai_reply}) except Exception as e: print(f"An error occurred: {e}") Use code with caution.
This code shows two examples of using the OpenAI API. The first part makes a single request to generate a Python function. The second part creates an interactive chatbot loop that keeps a conversation history, so the AI remembers previous messages.

- In the chatbot loop, the `messages` list grows with each user input and AI reply. Think about what happens to the conversation history over many exchanges and whether there is any limit on how many messages can be sent in one API call.
- The code appends the AI reply to `messages` after printing it. Consider what would happen if the API call fails after the user message was already appended, and whether the history might become inconsistent.