1
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?

PowershellからOpenAIの呼び出し

Posted at

はじめに

Powershell から Open AIの呼び出し方を以下の通り確認したので、その備忘録

  • Open AI API key の発行
  • 簡易PowerShellコードの作成
  • 実行結果の確認

対象読者

  • Powershell から Open AI を呼び出して使いたい

使用環境、サービス

  • Windows 11 (24H2)
  • Open AI API
  • Powershell 7


API KEYの発行方法

  • 歯車アイコンをクリック
    openai2.png
  • API Keys をクリック
    openai3.png
  • Create new secret key をクリック
    openai4.png
  • NameとProjectを入力し、「Create secret key」 クリック
    openai5.png
  • API Keyが生成されるので、コピーする。

API Key は再表示できないので注意

openai6.png

  • 作成されていることを確認。

作成したAPI key をPowershell で利用

openai7.png


Powershellコード

  • メモ帳や VSCode などでコードを作成する(文字コードはSJIS)
    ここでは c:\temp\gpt_test.ps1 として作成
  • $API_KEY には前章で作成したものを利用
  • APIを含んだヘッダとプロンプト組み込んだJSONのボディを作成し、Invoke-RestMethod でAPIに送信する簡易プログラム
  • モデルは gpt-5 を使用
c:\temp\gpt_test.ps1
param ([string]$Prompt)

# UTF-8
$OutputEncoding = [System.Text.Encoding]::UTF8

# プロンプトが空の場合のエラーチェック
if (-not $Prompt) {
    Write-Error "プロンプトが指定されていません。-Prompt パラメータを指定してください。"
    exit
}

$API_KEY = "xxxxxxxxxx"  # ここに実際のAPIキーを設定
$headers = @{
  "Authorization" = "Bearer $API_KEY"
  "Content-Type"  = "application/json"
}

# リクエストボディを作成
$body = @{
    model = "gpt-5"
    messages = @(
        @{
            role = "user"
            content = $Prompt
        }
    )
    max_completion_tokens = 5000
} | ConvertTo-Json -Depth 10

try {
    $response = Invoke-RestMethod -Uri "https://api.openai.com/v1/chat/completions" `
                                  -Method Post `
                                  -Headers $headers `
                                  -Body $body `
                                  -ContentType "application/json"
    # デバッグ用: レスポンスを確認
    #$response | ConvertTo-Json -Depth 10 | Out-File -FilePath .\debug_response.json
    
    # 結果を出力
    $content = $response.choices[0].message.content

    # 内容を出力
    Write-Output $content

} catch {
    Write-Error "APIリクエスト中にエラーが発生しました: $_"
}
  • 以下コマンドで実行する。
powershell
cd c:\temp
pwsh -ExecutionPolicy Bypass -File .\gpt_test.ps1 -Prompt "焼きそばの作り方を教えて"    
  • OpenAI API からの応答が出力される
  • 入出力合わせておおよそ 1600トークン(1 リクエスト約2.4円)※gpt-5は多少高め
    デバッグ用のコメントアウトを外すと「debug_response.json」にトークン情報が出力される
    openai1.png

参考

API

料金

1
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
1
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?