設定與首次呼叫
這是獨立的 OpenAI 相容服務,並非 OpenAI 自家的 Codex API。其單一模型為開放權重模型,僅支援文字,處理程式碼的能力足以勝任生成、說明與重構任務,但仍建議您對生成的程式碼進行審查。如果您想先了解背景資訊,OpenAI Codex API頁面說明了兩者的關係。
使用 pip install openai 安裝 SDK,在 API 金鑰頁面建立金鑰,然後執行:
# pip install openai
from openai import OpenAI
client = OpenAI(base_url="https://api.getcodexapi.com/v1", api_key="YOUR_KEY")
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a senior Python developer. Reply with code only, no commentary."},
{"role": "user", "content": "Write a function that parses an ISO 8601 date string and returns a datetime."},
],
temperature=0.2,
)
print(resp.choices[0].message.content)新用戶的免費試用額度 $0.50可涵蓋數千次此類小型呼叫。Temperature 設為 0.2,因為程式碼較少隨機性會更好。如果答案被 Markdown 程式碼區塊包圍,請在程式碼中移除它,或在系統提示詞中要求純文字。Base URL 頁面 Codex API base URL再次列出確切地址。
提示詞生成可執行程式碼
幾個習慣比任何參數更能改善輸出結果。
- 說明語言與版本。「Python 3.11,僅限標準函式庫」可減少大量猜測。
- 提供函式簽名。貼上函式標頭與文件字串,並要求模型填充主體。
- 顯示一個輸入與輸出的範例。這比文字描述更能鎖定邊界情況。
- 一次只要求一件事。生成函式,然後在第二次呼叫中要求測試。
- 要求差異比對(diff)進行編輯。整檔重寫會消耗輸出 token,其成本高於輸入。
上下文視窗為 100,000 token,max_tokens 為選填。對於程式碼任務,你可以貼上多個模組,仍留有回覆空間。設定 max_tokens 僅作為防止輸出失控的安全網。
JSON 模式用於結構化結果
當程式碼處理答案時,使用 JSON 模式。它使輸出為有效的 JSON;它不會強制執行你的 schema,因此請在提示詞中命名鍵名並進行檢查。
import json
from openai import OpenAI
client = OpenAI(base_url="https://api.getcodexapi.com/v1", api_key="YOUR_KEY")
resp = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Return JSON with keys: name, args (list of strings), returns."},
{"role": "user", "content": "Describe the signature of: def clamp(x, lo, hi)."},
],
temperature=0,
)
data = json.loads(resp.choices[0].message.content)
print(data["name"], data["args"])將其與 try/except 包裹 json.loads 搭配使用,並重試一次將解析錯誤回傳給模型。實際上這可處理罕見的格式錯誤回應。使用溫度 0 使重複執行結果一致。
工具呼叫
透過工具描述函式,由模型決定何時呼叫。你執行函式,然後以 tool 角色回傳輸出。這是每個程式碼代理的基礎。
import json
from openai import OpenAI
client = OpenAI(base_url="https://api.getcodexapi.com/v1", api_key="YOUR_KEY")
tools = [{
"type": "function",
"function": {
"name": "run_tests",
"description": "Run the project's test suite and return the output.",
"parameters": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"],
},
},
}]
messages = [{"role": "user", "content": "Run the tests in tests/unit and tell me what failed."}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools, tool_choice="auto")
msg = first.choices[0].message
if msg.tool_calls:
call = msg.tool_calls[0]
args = json.loads(call.function.arguments)
output = "2 passed, 1 failed: test_parse_empty" # replace with a real runner
messages.append(msg)
messages.append({"role": "tool", "tool_call_id": call.id, "content": output})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)像審查其他貢獻一樣測試生成的程式碼:執行它、進行 lint 檢查,並保留一組已知正確輸出的提示詞,以便在提示詞變更導致結果變差時察覺。比較版本時鎖定 seed 與溫度。
注意事項:保持工具描述簡短且字面化,執行前驗證參數,切勿將模型輸出直接傳入 shell。對於迴圈,只要 tool_calls 存在就重複呼叫,並在達到最大步驟數後停止。每個步驟都會重新發送歷史記錄,因此十步執行約需支付十倍的上下文成本。
串流輸出與 429 重試
對於互動式工具,在 token 到達時進行串流輸出。用量資訊位於串流結尾,便於記錄成本。
import time
from openai import OpenAI, RateLimitError
client = OpenAI(base_url="https://api.getcodexapi.com/v1", api_key="YOUR_KEY", max_retries=0)
def ask(prompt, tries=4):
for attempt in range(tries):
try:
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
stream=True,
stream_options={"include_usage": True},
)
text = []
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
piece = chunk.choices[0].delta.content
text.append(piece)
print(piece, end="", flush=True)
if chunk.usage:
print("\ntokens:", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)
return "".join(text)
except RateLimitError:
time.sleep(5 * (attempt + 1))
raise RuntimeError("still rate limited")
ask("Explain Python generators in four sentences.")該重試迴路背後的限制:完整金鑰允許 8 個並行請求和每分鐘 300 次,試用金鑰則為 2 個和 60 次。超過限制時,您會收到 HTTP 429 錯誤,代碼為 rate_limited 或 concurrency。暫時過載也會產生 429 錯誤,並附上 Retry-After: 5 標頭。範例在客戶端設為 max_retries=0,以便由您的迴路控制等待時間。串流請求會佔用其並行槽位直到串流結束,因此請務必消耗或關閉串流。
同時執行許多請求
批次工作(例如為一百個函式生成測試)需要並行上限。請使用執行緒池,完整金鑰最多使用 8 個執行緒。
一種簡單的模式是將 ThreadPoolExecutor(max_workers=6) 包在呼叫 ask 的函式周圍,保留兩個槽位供其他工作使用。試用金鑰請使用 2 個執行緒。如果您傳入較大的數字,API 會對額外請求回傳 concurrency 錯誤,您的重試迴路將花費時間等待而非工作。對於非同步程式碼,請使用 AsyncOpenAI 並對每次呼叫使用 asyncio.Semaphore(6);這可在不使用執行緒的情況下提供相同的上限。X-RateLimit-Limit-Requests 和 X-RateLimit-Limit-Concurrency 回應標頭顯示您金鑰的限制。
程式碼工作負載的成本
價格為每 1M 輸入 token $0.15,每 1M 輸出 token $0.50。假設你為 200 個函式生成單元測試。每次呼叫傳送 1,500 個輸入 token 並回傳 700 個 token。輸入:200 x 1,500 = 300,000 token,即 $0.045。輸出:200 x 700 = 140,000 token,即 $0.07。總計:$0.115。
大型檔案的重構會輸入 30,000 個 token 並輸出 8,000 個:每次執行費用為 $0.0045 + $0.004 = $0.0085。失敗或遭拒的請求不會收費,且額度永不過期。儲值從 $20 起,可透過信用卡或加密貨幣支付,$50 起贈 5%,$100 起贈 10%,$200 起贈 15%。請見 定價,並閱讀 文件以取得完整參數列表。

