diff --git a/chatgpt-python-api/README.md b/chatgpt-python-api/README.md new file mode 100644 index 0000000000..dbb4daa89c --- /dev/null +++ b/chatgpt-python-api/README.md @@ -0,0 +1,3 @@ +# How to Integrate ChatGPT's API With Python Projects + +This folder contains supporting materials for the Real Python tutorial [How to Integrate ChatGPT's API With Python Projects](https://realpython.com/chatgpt-python-api/). diff --git a/chatgpt-python-api/basic_chatgpt_call.py b/chatgpt-python-api/basic_chatgpt_call.py new file mode 100644 index 0000000000..d7c127cd1c --- /dev/null +++ b/chatgpt-python-api/basic_chatgpt_call.py @@ -0,0 +1,9 @@ +from openai import OpenAI + +client = OpenAI() + +text_response = client.responses.create( + model="gpt-5", input="Tell me a joke about Python programming" +) + +print(f"Joke:\n{text_response.output_text}") diff --git a/chatgpt-python-api/coding_assistant.py b/chatgpt-python-api/coding_assistant.py new file mode 100644 index 0000000000..b6fe126e1a --- /dev/null +++ b/chatgpt-python-api/coding_assistant.py @@ -0,0 +1,24 @@ +from openai import OpenAI + +user_input = input("How can I help you? ") + +client = OpenAI() + +code_response = client.responses.create( + model="gpt-5", + input=[ + { + "role": "developer", + "content": ( + "You are a Python coding assistant. " + "Only accept Python related questions." + ), + }, + { + "role": "user", + "content": f"{user_input}", + }, + ], +) + +print(f"\n{code_response.output_text}") diff --git a/chatgpt-python-api/structured_output.py b/chatgpt-python-api/structured_output.py new file mode 100644 index 0000000000..c2d7c7e6c6 --- /dev/null +++ b/chatgpt-python-api/structured_output.py @@ -0,0 +1,38 @@ +from openai import OpenAI +from pydantic import BaseModel + +client = OpenAI() + + +class CodeOutput(BaseModel): + function_name: str + code: str + explanation: str + example_usage: str + + +code_response = client.responses.parse( + model="gpt-5", + input=[ + { + "role": "developer", + "content": ( + "You are a coding assistant. Generate clean," + "well-documented Python code." + ), + }, + { + "role": "user", + "content": "Write a simple Python function to add two numbers", + }, + ], + text_format=CodeOutput, +) + +code_result = code_response.output_parsed + +print(f"Function Name: {code_result.function_name}") +print("\nCode:") +print(code_result.code) +print(f"\nExplanation: {code_result.explanation}") +print(f"\nExample Usage:\n{code_result.example_usage}") diff --git a/chatgpt-python-api/verify_setup.py b/chatgpt-python-api/verify_setup.py new file mode 100644 index 0000000000..e74ddefca7 --- /dev/null +++ b/chatgpt-python-api/verify_setup.py @@ -0,0 +1,5 @@ +from openai import OpenAI + +client = OpenAI() +print("OpenAI client created successfully!") +print(f"Using API key: {client.api_key[:8]}...")