This guide demonstrates how to fetch and log company information using the OpenAI API. You’ll learn how to set up your environment, configure your API key, and make a request to the OpenAI API.
openai-hello-world.py
Copy
import osfrom dotenv import load_dotenvfrom openai import OpenAI# Load environment variables from .env fileload_dotenv()# Get OpenAI API key from environment variablesopenai_api_key = os.getenv('OPENAI_API_KEY')# Initialize OpenAI client with API keyclient = OpenAI(api_key=openai_api_key)# Define the company name to get information forcompany_name = "Twilio"# Request completion from the OpenAI APIcompletion = client.chat.completions.create( model="gpt-4-turbo", messages=[ {"role": "system", "content": "Only return the information asked for. No preamble, and no conclusion. Only return CSV format."}, {"role": "user", "content": ( f"Return the details for the company in JSON format including founding date, status " f"(series a, b funding etc., IPO etc.), a brief description of what {company_name} does, " f"and its category in JSON format. Use these keys - company, year, description, stage, category" )} ])# Print the raw completion responseprint("Raw completion response:", completion)# Print the content of the first choice's messageprint("Content of the first choice's message:", completion.choices[0].message.content)
Create a Python script named openai-hello-world.py with the following content:
openai-hello-world.py
Copy
import osfrom dotenv import load_dotenvfrom openai import OpenAI# Load environment variables from .env fileload_dotenv()# Get OpenAI API key from environment variablesopenai_api_key = os.getenv('OPENAI_API_KEY')# Initialize OpenAI client with API keyclient = OpenAI(api_key=openai_api_key)# Define the company name to get information forcompany_name = "Twilio"# Request completion from the OpenAI APIcompletion = client.chat.completions.create( model="gpt-4-turbo", messages=[ {"role": "system", "content": "Only return the information asked for. No preamble, and no conclusion. Only return CSV format."}, {"role": "user", "content": ( f"Return the details for the company in JSON format including founding date, status " f"(series a, b funding etc., IPO etc.), a brief description of what {company_name} does, " f"and its category in JSON format. Use these keys - company, year, description, stage, category" )} ])# Print the raw completion responseprint("Raw completion response:", completion)# Print the content of the first choice's messageprint("Content of the first choice's message:", completion.choices[0].message.content)
You have successfully fetched and logged company information using the OpenAI API! This guide provided a basic example to get you started. You can now expand on this by customizing the request and handling different types of information.