Below is a simple Python example using an API to interact with an AI model. In this case, we'll use the OpenAI GPT model (via the OpenAI API). This program will demonstrate how you can send text to the API and receive a generated response.
### Steps:
1. **Install the
openai
library**: First, you need to install the OpenAI library if you don't have it installed already:
bash
pip install openai
2. **Create a sample program to interact with the OpenAI API**:
python
import openai
# Set your OpenAI API key here
openai.api_key = 'your-api-key-here'
def generate_response(prompt):
try:
# Make the API call
response = openai.Completion.create(
engine="text-davinci-003", # Choose the model you want to use (can also be "gpt-4", etc.)
prompt=prompt,
max_tokens=150 # Limit on the number of tokens (words or characters)
)
# Extract and return the response text
return response.choices[0].text.strip()
except Exception as e:
return f"Error: {str(e)}"
# Example usage:
if __name__ == "__main__":
user_input = input("Enter your prompt for the AI: ")
ai_response = generate_response(user_input)
print(f"AI Response: {ai_response}")
### How It Works:
- **API Key**: You'll need to replace
'your-api-key-here'
with your actual OpenAI API key. You can get it by signing up on the OpenAI website.
- **Prompt**: You can provide any input text (prompt), and the model will generate a response based on it.
- **Model**: In the
engine
argument, we specify which model to use (e.g.,
"text-davinci-003"
). You can use other models like
"gpt-4"
depending on your API access.
### Example Output:
bash
Enter your prompt for the AI: What is the capital of France?
AI Response: The capital of France is Paris.
This program sends a prompt to OpenAI's GPT model via the API, and the model responds based on the provided prompt.
### Notes:
- Ensure you handle errors (like network issues, invalid API keys) properly in production.
- Modify the
max_tokens
or other parameters like
temperature
and
top_p
depending on the nature of the response you want.