Build Docker Environment
I want to build a docker python development environment under Windows 11.
- I create a folder OpenAI\Lession01
- Then I create a Dockerfile for build Python 3.9 environment

- Then I create a Docker-Compose.yml file

- Then I create a app folder for save my program.
- console command: docker compose build –no-cache
- console command: docker compose up -d
- console command: docker exec -it python_39_dev /bin/bash // => Login the Docker Development Host

Start Developing
- Go to https://platform.openai.com/docs/overview to apply for OpenAI Key

- create a .env file
cat << EOF > .env
API_KEY=XXX
EOF
- console command: source .env
- console command: pip install openai
- create a demo.py
import os
import openai
from openai import OpenAI
with open(".env") as env:
for line in env:
key, value = line.strip().split("=")
os.environ[key] = value
client = OpenAI(api_key=os.environ.get("API_KEY"),)
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "What can gpt-40-min do?",},
],
max_tokens=30, # the return message content have max 800 tokens
temperature=0, # more close to 0 the return message will be more deterministic, more close to 2 will be more random
logprobs=True, # Enable log probabilities, token probability
top_p = 0.9, # top_p is an alternative to temperature for controlling randomness.
)
print(response.choices[0].message.content)
except openai.PermissionDeniedError as e:
print(f"Permission denied: {e}")
except openai.OpenAIError as e:
print(f"OpenAI error: {e}")


- console command: python demo.py, we will get the response from openai

the logprob value more close to 0 is more confident.
Argument: Stream
import openai
client = openai.OpenAI(api_key="your_api_key")
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[{"role": "user", "content": "Tell me a joke"}],
stream=True # Change to False to see the difference
)

Stream = False
{
"id": "chatcmpl-12345",
"object": "chat.completion",
"created": 1710456789,
"model": "gpt-4-turbo",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "Why don’t skeletons fight each other? Because they don’t have the guts!"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 15,
"total_tokens": 25
}
}
Stream = True
{"id": "chatcmpl-12345", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"role": "assistant"}, "finish_reason": null}]}
{"id": "chatcmpl-12345", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"content": "Why "}, "finish_reason": null}]}
{"id": "chatcmpl-12345", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"content": "don’t "}, "finish_reason": null}]}
{"id": "chatcmpl-12345", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"content": "skeletons "}, "finish_reason": null}]}
{"id": "chatcmpl-12345", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"content": "fight "}, "finish_reason": null}]}
{"id": "chatcmpl-12345", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"content": "each other?"}, "finish_reason": null}]}
{"id": "chatcmpl-12345", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"content": " Because "}, "finish_reason": null}]}
{"id": "chatcmpl-12345", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"content": "they "}, "finish_reason": null}]}
{"id": "chatcmpl-12345", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"content": "don’t "}, "finish_reason": null}]}
{"id": "chatcmpl-12345", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"content": "have "}, "finish_reason": null}]}
{"id": "chatcmpl-12345", "object": "chat.completion.chunk", "choices": [{"index": 0, "delta": {"content": "the guts!"}, "finish_reason": "stop"}]}
OpenAI Arguments
- presence_penalty, value range from -2.0 to 2.0; close to 2.0, the feedback will be more diverse
- frequency_penalty, value range from -2.0 to 2.0; close to 2.0, the will reduce repeating the same words.
- n, this argument determines how many completions (responses)
- stop=[“\n”,], When the feedback text has a new line (\n) in it, Openai will stop.
- suffix=”]\n}”,
import os
import openai
from openai import OpenAI
with open(".env") as env:
for line in env:
key, value = line.strip().split("=")
os.environ[key] = value
client = OpenAI(api_key=os.environ.get("API_KEY"),)
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "Write a JSON containing primary numbers between 0 and 9 \n\n{\n\t\"primaries\":[", "suffix": "]\n}"},
],
max_tokens=50,
n=1,
)
print(response.choices[0].message.content)
except openai.PermissionDeniedError as e:
print(f"Permission denied: {e}")
except openai.OpenAIError as e:
print(f"OpenAI error: {e}")

import os
import openai
from openai import OpenAI
with open(".env") as env:
for line in env:
key, value = line.strip().split("=")
os.environ[key] = value
client = OpenAI(api_key=os.environ.get("API_KEY"),)
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "Todo list to create a company in US\n\n1."},
],
temperature=0.3,
top_p=0.1,
frequency_penalty=0,
presence_penalty=0.5,
stop=["6."],
)
print(response.choices[0].message.content)
except openai.PermissionDeniedError as e:
print(f"Permission denied: {e}")
except openai.OpenAIError as e:
print(f"OpenAI error: {e}")

Translating Text (openai.response.create)
I want to translate “Hallo Welt” to English “Hello World”, to Chinse “你好,世界“, to Spanish “Hola Mundo“
import os
import openai
from openai import OpenAI
with open(".env") as env:
for line in env:
key, value = line.strip().split("=")
os.environ[key] = value
client = OpenAI(api_key=os.environ.get("API_KEY"),)
try:
response = client.responses.create(
model="gpt-4o-mini",
input="Hallo Welt",
instructions="Translate to English, Chinese, and Spanish",
)
print(response)
except openai.PermissionDeniedError as e:
print(f"Permission denied: {e}")
except openai.OpenAIError as e:
print(f"OpenAI error: {e}")
Response(id='resp_67d29884089081929e4c4419f9a5020502467553557a1dd7', created_at=1741854852.0, error=None, incomplete_details=None, instructions='Translate to English, Chinese, and Spanish', metadata={}, model='gpt-4o-mini-2024-07-18', object='response', output=[ResponseOutputMessage(id='msg_67d29884bac08192bf2dd218d91a4d4e02467553557a1dd7', content=[ResponseOutputText(annotations=[], text='Sure! Here’s the translation:\n\n- **English:** Hello World\n- **Chinese (Simplified):** 你好,世界 (Nǐ hǎo, shìjiè)\n- **S
panish:** Hola Mundo', type='output_text')], role='assistant', status='completed', type='message')], parallel_tool_calls=True, temperature=1.0, tool_choice='auto', tools=[], top_p=1.0, max_output_tokens=None, previous_response_id=None, reasoning=Reasoning(effort=None, generate_summary=None), status='completed', text=ResponseTextConfig(format=ResponseFormatText(type='text')), truncation='disabled', usage=ResponseUsage(input_tokens=39, output_tokens=46, output_tokens_details=OutputTokensDetails(reasoning_tokens=0), total_tokens=85, input_tokens_details={'cached_tokens': 0}), user=None, store=True)
You can use this fuction to do many things.
- You can input “Expalin the following Python Code” in the instruction argument, input your python code in the input argument.
- You can correct the spling mistaks.
- You can use to refine your resume.
- You can use the correct your english sentence.
- You can use query what commands can finish your job.
Creating a Chatbot Assistant
import os
import click
import openai
from openai import OpenAI
with open(".env") as env:
for line in env:
key, value = line.strip().split("=")
os.environ[key] = value
client = OpenAI(api_key=os.environ.get("API_KEY"),)
try:
_prompt = """
Input: List all the files in the current directory
Output: ls -l
Input: List all the files in the current directory, including hidden files
Output: ls -la
Input: Delete all the files in the current directory
Output: rm *
Input: Count the number of occurrences of the word "sun" in the file "test.txt"
Output: grep -o "sun" test.txt | wc -l
Input: {}
Output: """
while True:
request = input(click.style("Input", fg="green"))
prompt = _prompt.format(request)
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": prompt},
],
temperature=0.0,
max_tokens=100,
stop=["\n"],
)
command = response.choices[0].message.content.strip()
click.echo(click.style("Output: ", fg="yellow") + command)
click.echo()
except openai.PermissionDeniedError as e:
print(f"Permission denied: {e}")
except openai.OpenAIError as e:
print(f"OpenAI error: {e}")
=============================================================================================================
Input: list all
Output: ls -a
Input: delete all
Output: rm -rf *
Input: count all files
Output: To count all files in the current directory, you can use the following command:
Input: count all files that are not directories
Output: `find . -type f | wc -l`