Skip to content

OpenAI Chat Format (Python)

Overview

Official Documentation

OpenAI Chat

Given a list of messages containing a conversation, the model will return a response. For related guidance, please refer to the official OpenAI documentation: Chat Completions

💡 Basic Python Request Example: Text Conversation ✅

Section titled “💡 Basic Python Request Example: Text Conversation ✅”
  • In the same directory as your Python script (for example, xxxx.py), create a file named .env (note: the filename must be exactly .env, with a leading dot and no other prefix).
  • In that .env file, add the following content and fill in your API key and base URL: # .env file content OPENAI_API_KEY=“sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx” OPENAI_BASE_URL=“https://sg.4All API.com/v1”

You can add other configuration variables in the future, for example:

Section titled “You can add other configuration variables in the future, for example:”
### 2. Create a `xxxx.py` file and write the following Python code.
- In the same directory as your Python script (for example, `xxxx.py`), create a file named `.env` (note: the filename must be exactly `.env`, with a leading dot and no other prefix).
```python
import os
from dotenv import load_dotenv, find_dotenv # 导入 find_dotenv 帮助定位
import openai
from openai import OpenAI
import httpx
# 0. Load environment variables from the .env file (enhanced debugging)
print("--- 开始 .env 文件加载调试 ---")
# Try to locate the .env file in the current working directory or the script directory
# find_dotenv(usecwd=True) will try the current working directory first
# find_dotenv() (no arguments) will search upward starting from the script location
dotenv_path_found = find_dotenv(usecwd=True) # Check the current working directory
if not dotenv_path_found:
dotenv_path_found = find_dotenv() # If not found in the CWD, search normally (from the script directory upward)
if dotenv_path_found:
print(f"DEBUG: 找到 .env 文件路径: {dotenv_path_found}")
# verbose=True will print detailed information about the loading process
# override=True means variables in the .env file will override existing environment variables with the same name
loaded_successfully = load_dotenv(dotenv_path=dotenv_path_found, verbose=True, override=True)
if loaded_successfully:
print("DEBUG: 成功从 .env 文件加载变量。")
else:
# If loaded_successfully is False, it may mean the file is empty or could not be parsed,
# but usually as long as the file is found and not empty, python-dotenv may still return True even if the contents have issues.
# The real check is whether os.getenv can retrieve the values afterward.
print("DEBUG: .env 文件已找到,但 load_dotenv() 执行完毕 (请检查 verbose 输出和后续变量值)。")
else:
print("DEBUG: 未能找到 .env 文件。")
print("DEBUG: 请确保名为 '.env' 的文件存在于脚本所在目录或项目的根目录中。")
print("--- .env 文件加载调试结束 ---")
print("--- 开始环境变量获取调试 ---")
# 1. Load the API key and base URL from environment variables
api_key = os.getenv("OPENAI_API_KEY")
base_url_from_env = os.getenv("OPENAI_BASE_URL")
# Print the raw values retrieved for debugging
print(f"DEBUG: os.getenv(\"OPENAI_API_KEY\") 返回的值: {'一个字符串 (已隐藏具体内容)' if api_key else 'None'}")
if api_key:
print(f"DEBUG: API Key 的前5个字符: {api_key[:5]}") # Print part of it for confirmation
print(f"DEBUG: os.getenv(\"OPENAI_BASE_URL\") 返回的值: {base_url_from_env if base_url_from_env else 'None'}")
print("--- 环境变量获取调试结束 ---")
if not api_key:
print("--------------------------------------------------------------------")
print("错误:未能从 .env 文件或环境变量中获取 OPENAI_API_KEY。")
print("请仔细检查以下几点:")
print("1. 项目根目录或脚本所在目录中是否存在一个名为 '.env' 的文件。")
print(" (DEBUG 信息中 '找到 .env 文件路径:' 是否显示了正确的路径?)")
print("2. '.env' 文件中是否正确定义了 OPENAI_API_KEY='your_actual_key'。")
print(" (确保键名拼写正确,无多余空格,API密钥值完整无误)。")
print("3. 确保您的 .env 文件内容与示例格式一致,例如:")
print(" OPENAI_API_KEY=\"sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\"")
print(" OPENAI_BASE_URL=\"https://sg.4All API.com/v1\"")
print("请查看上面以 'DEBUG:' 开头的详细输出,以帮助定位问题。")
print("--------------------------------------------------------------------")
exit() # Required API key not found, exit the program
else:
print(f"成功加载的 API Key (部分显示): '{api_key[:5]}...{api_key[-4:]}'")
# The base URL can be loaded from the environment variables; if not set, use default_base_url = "https://sg.4All API.com/v1"
default_base_url = "OPENAI_BASE_URL" # 您常用的 URL 作为默认值
base_url = base_url_from_env if base_url_from_env else default_base_url
print(f"使用的 Base URL: {base_url}")
if base_url == default_base_url and not base_url_from_env :
print(f"(提示: OPENAI_BASE_URL 未在 .env 文件或环境变量中指定, 当前使用的是代码中的默认值 '{default_base_url}'。)")
# ... (后续的 OpenAI 客户端初始化、API 调用和错误处理代码保持不变) ...
# 2. Configure the API client
client = OpenAI(
api_key=api_key,
base_url=base_url,
timeout=httpx.Timeout(300.0, connect=60.0),
max_retries=1,
)
# 3. Prepare the message body for the API request
messages = [
{"role": "user", "content": "你好,你好,你能做什么?请用中文回答。"}
]
# 4. Send the request and handle the response
try:
print("正在尝试调用 OpenAI API...")
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
max_tokens=4500,
temperature=0.8,
)
if response.choices:
assistant_reply = response.choices[0].message.content
print("模型回复:", assistant_reply)
else:
print("未能从 API 获取有效回复。")
except openai.AuthenticationError as e:
print(f"OpenAI API 认证失败: {e}")
print("这通常意味着 API 密钥无效或没有权限。请再次核对 .env 文件中的 OPENAI_API_KEY 是否为您从 4All API 获取的正确密钥。")
print(f"当前尝试使用的 API Key (来自 .env 或环境变量,部分显示): '{api_key[:5]}...{api_key[-4:]}',Base URL 为: {base_url}")
except openai.APIConnectionError as e:
print(f"无法连接到 OpenAI API: {e}")
except openai.RateLimitError as e:
print(f"达到 OpenAI API速率限制: {e}")
except openai.APIStatusError as e:
print(f"OpenAI API 返回了错误状态码: {e.status_code}")
print(f"响应详情: {e.response}")
except Exception as e:
print(f"调用 API 时发生未知错误: {e}")
print(f"错误类型: {type(e).__name__}")

Please:

  • Carefully check your .env file: Filename: make sure it is .env. Location: make sure it is in the same folder as your Python script. Content: confirm again that the key names (OPENAI_API_KEY, OPENAI_BASE_URL) are correct, and that the API key and URL values are also completely correct, with no extra or missing characters. The format should look like this: Code snippet OPENAI_API_KEY= “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx” OPENAI_BASE_URL= “https://sg.4All API.com/v1”
  • Run the complete Python script provided above.
  • Observe the DEBUG: output at the beginning of the script. Does it find the .env file (DEBUG: 找到 .env 文件路径: ...)? Does load_dotenv report that it loaded successfully (DEBUG: 成功从 .env 文件加载变量。)? What does os.getenv("OPENAI_API_KEY") return (DEBUG: os.getenv("OPENAI_API_KEY") 返回的值: ...)?

Based on the DEBUG output:

  • If the DEBUG messages show that the .env file could not be found, or os.getenv("OPENAI_API_KEY") returns None, then the issue lies in the .env file discovery or loading process. Please focus on checking the filename, location, and the related DEBUG output from load_dotenv.
  • If the DEBUG messages show that the .env file was found and loaded, and os.getenv("OPENAI_API_KEY") successfully returns a string that looks like a key, but you still get an AuthenticationError later, then the problem is not the environment-variable loading mechanism. Instead, the value of OPENAI_API_KEY in the .env file itself is invalid or not authorized for the https://sg.4All API.com/v1 service. In that case, you need to contact the provider of 4All API to confirm the validity of the key.