Skip to content

mkht/PSOpenAI

Repository files navigation

PSOpenAI

Test

PowerShell module for OpenAI and Azure OpenAI Service.
You can use OpenAI functions such as ChatGPT, Speech-to-Text, Text-to-Image from PowerShell.

This is a community-based project and is not an official offering of OpenAI.


Supported Platforms

  • Windows PowerShell 5.1
  • PowerShell 7 or higher
  • Windows, macOS or Linux

You need to sign-up OpenAI account and generates API key for authentication.
https://platform.openai.com/api-keys


Installation

You can install PSOpenAI from PowerShell Gallery.

Install-Module -Name PSOpenAI

Functions

The full list of functions

Common

OpenAI

Chat

Guide: How to use Chat

Responses

Guide: Migrate ChatCompletion to Response

Assistants

Guide: How to use Assistants
Guide: How to use File search with Assistants and Vector Store

Realtime

Guide: How to use Realtime API

[*] Works on Windows with PowerShell 7.4+ only.

Images

Audio

Files

Batch

Guide: How to use Batch

Others

Azure OpenAI Service


Usage

See Docs and Guides for more detailed and complex scenario descriptions.

Responses

The primary method for interacting with OpenAI models. You can generate text from the model with the code below.

$env:OPENAI_API_KEY = '<Put your API key here.>'
$Response = Request-Response -Model 'gpt-4o' -Message 'Explain quantum physics in simple terms.'
Write-Output $Response.output_text

This code outputs answer from model like this.

Quantum physics is a branch of science that deals with the behavior of ...

Chat Completions

The previous standard for generating text is the Chat Completions API. You can use that API to generate text from the model with the code below.

Chat Completions API is compatible with other AI services besides OpenAI, such as GitHub Models and Google Gemini. You can also use self-hosted local AI models with LM Studio or Ollama. That is explained in the Advanced section.

$env:OPENAI_API_KEY = '<Put your API key here.>'
$Completion = Request-ChatCompletion -Model 'gpt-4o' -Message 'Give me a recipe for chocolate cake.'
Write-Output $Completion.Answer[0]

Audio Speech (Text-to-Speech)

Generates audio from the input text.

$env:OPENAI_API_KEY = '<Put your API key here.>'
Request-AudioSpeech -Model 'gpt-4o-mini-tts' -Text 'Hello, My name is shimmer.' -OutFile 'C:\Output\text2speech.mp3' -Voice shimmer

Audio transcription (Speech-to-Text)

Transcribes audio into the input language.

$global:OPENAI_API_KEY = '<Put your API key here.>'
Request-AudioTranscription -Model 'gpt-4o-transcribe' -File 'C:\SampleData\audio.mp3'

Image generation

Creating images from scratch based on a text prompt.

$global:OPENAI_API_KEY = '<Put your API key here.>'
Request-ImageGeneration -Model 'gpt-image-1' -Prompt 'A cute baby lion' -Size 1024x1024 -OutFile 'C:\output\babylion.png'

This sample code saves image to C:\output\babylion.png. The saved image like this.

Generated image

Restore masked images

Request-ImageEdit -Image 'C:\sunflower_masked.png' -Prompt 'sunflower' -OutFile 'C:\sunflower_restored.png' -Size 256x256

Masked image is restored to full images by AI models.

Source Generated
masked restored

Moderation

Test whether text complies with OpenAI's content policies.

The moderation endpoint is free to use when monitoring the inputs and outputs of OpenAI APIs.

PS C:\> $Result = Request-Moderation -Text "I want to kill them."
PS C:\> $Result.results.categories

# True means it violates that category.
sexual           : False
hate             : False
violence         : True
self-harm        : False
sexual/minors    : False
hate/threatening : False
violence/graphic : False

List available models

Get a list of available models.

$Models = Get-OpenAIModels

Realtime (Beta)

The Realtime API enables you to communicate with AI models live, in real time experiences.

Here's a basic text-based example. For more detailed usage, please refer to the guide. Guide: How to use Realtime API

$env:OPENAI_API_KEY = '<Put your API key here>'

# Subscribe to events
Register-EngineEvent -SourceIdentifier 'PSOpenAI.Realtime.ReceiveMessage' -Action {
    $eventItem = $Event.SourceArgs[0]
    switch ($eventItem.type) {
        'response.text.delta' {
            $eventItem.delta | Write-Host -NoNewLine -ForegroundColor Blue
        }
    }
}

# Connect to the Realtime session
Connect-RealtimeSession -Model 'gpt-4o-realtime-preview'
Set-RealtimeSessionConfiguration -Modalities 'text' -Instructions 'You are a science tutor.'

# Send messages to the AI model
Add-RealtimeSessionItem -Message 'Why does the sun rise in the east and set in the west?' -TriggerResponse

# Disconnect
Disconnect-RealtimeSession

Advanced

Multiple conversations keeping context.

Request-Response and Request-ChatCompletion accepts past dialogs from pipeline. Additional questions can be asked while maintaining context.

PS C:\> $FirstQA = Request-ChatCompletion -Model 'gpt-4.1-nano' -Message 'What is the population of the United States?'
PS C:\> Write-Output $FirstQA.Answer

As of October 2023, the estimated population of the United States is approximately 336 million people.

PS C:\> $SecondQA = $FirstQA | Request-ChatCompletion -Message 'Translate the previous answer into French.'
PS C:\> Write-Output $SecondQA.Answer

En octobre 2023, la population estimée des États-Unis est d'environ 336 millions de personnes.

PS C:\> $ThirdQA = $SecondQA | Request-ChatCompletion -Message 'Just tell me the number.'
PS C:\> Write-Output $ThirdQA.Answer

336 millions

Streaming responses

By default, results are output all at once after all responses are complete, so it may take some time before results are available. To get responses sooner, you can use the -Stream option for Request-ChatCompletion and Request-Response

Request-ChatCompletion 'Describe ChatGPT in 100 charactors.' -Stream | Write-Host -NoNewline

Stream

Vision (Image input)

You can input images to the model and get answers.

# Local file
$Response = Request-Response -Model 'o4-mini' -Images 'C:\SampleData\donut.png' -Message 'How many donuts are there?'

# Remote URL
$Response = Request-Response -Model 'o4-mini' -Images 'https://upload.wikimedia.org/wikipedia/commons/5/5f/Cerro_El_%C3%81vila_desde_El_Bosque_-_Caracas.jpg' -Message 'Where is this?'

Web Search

Allow models to search the web for the latest information before generating a response.

$Response = Request-Response -Model 'gpt-4.1' -Message 'What was a tech news in Merch 2025?' -UseWebSearch

Azure OpenAI Service

If you want to use Azure OpenAI Service instead of OpenAI. You should create Azure OpenAI resource to your Azure tenant, and get API key and endpoint url. See guides for more details.

$global:OPENAI_API_KEY = '<Put your api key here>'
$global:OPENAI_API_BASE  = 'https://<resource-name>.openai.azure.com/'

Request-ChatCompletion `
  -Model 'gpt-4o' `
  -Message 'Hello Azure OpenAI Service.' `
  -ApiType Azure

OpenAI Compatible Servers

If you want to use OpenAI compatible services such as GitHub Models, Google Gemini, self-hosted servers like LM Studio or Ollama.

# This is an example for GitHub Models.
$global:OPENAI_API_KEY = '<Put your GITHUB_TOKEN>'
$global:OPENAI_API_BASE  = 'https://models.github.ai/inference'

Request-ChatCompletion `
  -Model 'microsoft/Phi-4-reasoning' `
  -Message 'What is the capital of France?' `
  -ApiType OpenAI

About API key

Almost all functions require an API key for authentication.
You need to sign-up OpenAI account and generates API key from here.
https://platform.openai.com/api-keys

There are three ways to give an API key to functions.

Method 1: Set an environment variable named OPENAI_API_KEY. (RECOMMENDED)

Set the API key to the environment variable named OPENAI_API_KEY.
This method is best suited when running on a trusted host or CI/CD pipeline.

PS C:> $env:OPENAI_API_KEY = '<Put your API key here.>'
PS C:> Request-ChatCompletion -Message "Who are you?"

Method 2: Set a global variable named OPENAI_API_KEY.

Set the API key to the $global:OPENAI_API_KEY variable. The variable is implicitly used whenever a function is called within the session.

PS C:> $global:OPENAI_API_KEY = '<Put your API key here.>'
PS C:> Request-ChatCompletion -Message "Who are you?"

Method 3: Supply as named parameter.

Specify the API key explicitly in the ApiKey parameter. It must be specified each time the function is called.
This is best used when the function is called only once or with few calls, such as when executing manually from the console.

PS C:> Request-ChatCompletion -Message "Who are you?" -ApiKey '<Put your API key here.>'

Changelog

CHANGELOG.md


Plans and TODOs.

If you have a feature request or bug report, please tell us in Issue.

  • More docs, samples.
  • Performance improvements.
  • Add a support for fine-tuning.

License & Libraries

MIT License

This module uses these OSS libraries.