0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめての OpenAI Codex #1 ― APIキー取得から「Hello, World」生成まで①

Posted at

はじめての OpenAI Codex #1 ― APIキー取得から「Hello, World」生成まで

1. Codexって何者?

  • GPT‑3 系列の コード特化モデル
  • 入力:自然文+途中までのコード
  • 出力:続きを自動生成

2. OpenAI アカウント&APIキー

  1. OpenAI公式サイトでアカウント作成 → https://platform.openai.com/signup
  2. Dashboard → API keys → “Create new secret key” をクリックし、キーをコピー
  3. .env に保存して安全に管理します
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxx

3. Python から呼び出す

3‑1. ライブラリをインストール

pip install openai python-dotenv

3‑2. サンプルコード

# codex_hello.py
import os, openai
from dotenv import load_dotenv
load_dotenv()

openai.api_key = os.getenv("OPENAI_API_KEY")

prompt = "Write a Python function that prints 'Hello, World!'"

resp = openai.Completion.create(
    model="code-davinci-002",
    prompt=prompt,
    max_tokens=60,
    temperature=0
)

print(resp.choices[0].text.strip())

4. 実行結果

def hello():
    print("Hello, World!")

5. パラメータ解説

引数 意味 推奨値
model 使用モデル code-davinci-002 など
prompt 入力プロンプト 自然文+コード
max_tokens 生成トークン上限 60〜200
temperature 出力の多様性 (0=決定的) 0〜0.3

6. よくあるエラー

エラー 対処
InvalidRequestError: You must provide an api_key. .env のキー名とコード側が一致しているか確認
RateLimitError 無料枠超過。ダッシュボードで残高を確認するか課金設定を行う

7. 次回予告

Day 2:VSCode拡張 “GitHub Copilot” でリアルタイム補完を体験
コードを書くたびに Tab 一発で AI が続きを提案!お楽しみに。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?