### Start a Run with Thread and Assistant IDs Source: https://github.com/mkht/psopenai/blob/main/Docs/Start-ThreadRun.md Use this example to start a run for an existing thread with a specified assistant. Ensure you have the correct Thread ID and Assistant ID. ```powershell PS C:\> Start-ThreadRun -ThreadId 'thread_abc123' -Assistant 'asst_abc123' ``` -------------------------------- ### Installation Source: https://context7.com/mkht/psopenai/llms.txt Install the PSOpenAI module from the PowerShell Gallery. ```APIDOC ## Installation ```powershell Install-Module -Name PSOpenAI ``` ``` -------------------------------- ### Ask a question and get an answer Source: https://github.com/mkht/psopenai/blob/main/Docs/Request-ChatCompletion.md A basic example of asking a single question to ChatGPT and selecting the 'Answer' property from the output. ```PowerShell PS C:\> Request-ChatCompletion -Message "Who are you?" | select Answer ``` -------------------------------- ### Simplified Workflow with Pipelines Source: https://github.com/mkht/psopenai/blob/main/Guides/How_to_use_Assistants.md Streamline Assistant interactions by chaining cmdlets using pipelines. This example demonstrates creating an Assistant, a Thread, adding a message, starting a run, and receiving the result in a single command sequence. ```PowerShell # Create a new Assistant $Assistant = New-Assistant -Model "gpt-3.5-turbo" # Create a Thread and add a Message, then starts Run and receive the result when completes the Run. $Result = New-Thread |` Add-ThreadMessage "Hello, what can you do for me?" -PassThru | ` Start-ThreadRun -Assistant $Assistant |` Receive-ThreadRun -Wait # Dislpays only Assistant response message $Result.Messages.SimpleContent[-1].Content ``` -------------------------------- ### Use OpenAI Compatible Servers (GitHub Models Example) Source: https://github.com/mkht/psopenai/blob/main/README.md Connect to OpenAI compatible servers, such as GitHub Models, by setting the API key (e.g., GITHUB_TOKEN) and the base URL. This example uses GitHub Models. ```powershell # This is an example for GitHub Models. $global:OPENAI_API_KEY = '' $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 ``` -------------------------------- ### Start Vector Store File Batch Source: https://github.com/mkht/psopenai/blob/main/Docs/Start-VectorStoreFileBatch.md Use this command to start a batch for adding files to a specified vector store. Ensure you provide the correct VectorStoreId and a list of File IDs. ```powershell PS C:\> Start-VectorStoreFileBatch -VectorStoreId 'vs_abc123' -Files ('file-abc123', 'file-def456', 'file-ghi789') ``` -------------------------------- ### Start Realtime Session Audio Input Source: https://github.com/mkht/psopenai/blob/main/Docs/Start-RealtimeSessionAudioInput.md This command captures audio from the computer's microphone and starts sending it to the server session. It requires Windows and PowerShell 7.4 or higher. ```powershell PS C:\> Start-RealtimeSessionAudioInput ``` -------------------------------- ### Generate Multiple Images and Get URLs Source: https://github.com/mkht/psopenai/blob/main/Docs/Request-ImageGeneration.md This example demonstrates generating multiple images with a specific model and prompt, retrieving the results as URLs. Note that for 'dall-e-3', only one image can be generated at a time. ```PowerShell Request-ImageGeneration -Model 'dall-e-3' -Prompt 'Delicious ramen with gyoza' -Model -ResponseFormat 'url' -NumberOfImages 3 ``` -------------------------------- ### Start an Assistant Run Source: https://github.com/mkht/psopenai/blob/main/Guides/How_to_use_Assistants.md Initiate a run by associating an Assistant with a Thread using `Start-ThreadRun`. This cmdlet starts the process but does not wait for completion, returning a Run object with a 'queued' status. ```PowerShell # Start a run $Run = Start-ThreadRun -Thread $Thread -Assistant $Assistant ``` -------------------------------- ### Install PSOpenAI Module Source: https://github.com/mkht/psopenai/blob/main/README.md Installs the PSOpenAI module from the PowerShell Gallery. Ensure you have an OpenAI account and API key for authentication. ```powershell Install-Module -Name PSOpenAI ``` -------------------------------- ### Start-ThreadRun - Run Syntax Source: https://github.com/mkht/psopenai/blob/main/Docs/Start-ThreadRun.md This syntax is used to start a run on an existing thread. It requires a Thread ID and an Assistant object. ```APIDOC ## Start-ThreadRun - Run ### Description Starts a run on an existing thread using a specified Assistant. This overload is suitable for continuing conversations or performing new tasks within an established thread. ### Method Start-ThreadRun ### Parameters #### Path Parameters - **ThreadId** (String) - Required - The ID of the thread to run. - **Assistant** (Object) - Required - The assistant object to use for executing the run. #### Query Parameters - **Model** (String) - Optional - The name of the model to use for the run. Overrides the assistant's default model. - **Instructions** (String) - Optional - Overrides the assistant's instructions for this specific run. - **ReasoningEffort** (String) - Optional - Constrains the reasoning effort for the model. Supported values: `none`, `low`, `medium`, `high`. - **AdditionalInstructions** (String) - Optional - Appends additional instructions to the assistant's instructions for this run. - **AdditionalMessages** (Object[]) - Optional - Additional messages to include in the thread before starting the run. - **Include** (String[]) - Optional - A list of additional fields to include in the response. - **MaxPromptTokens** (Int32) - Optional - Maximum prompt tokens for the run. - **MaxCompletionTokens** (Int32) - Optional - Maximum completion tokens for the run. - **TruncationStrategyType** (String) - Optional - The type of truncation strategy to use. - **TruncationStrategyLastMessages** (Int32) - Optional - The number of last messages to retain when using truncation. - **ToolChoice** (String) - Optional - Specifies the tool to be chosen for the run. - **ToolChoiceFunctionName** (String) - Optional - The name of the function to use for tool choice. - **UseCodeInterpreter** - Optional - Enables the code interpreter tool. - **UseFileSearch** - Optional - Enables the file search tool. - **Functions** (IDictionary) - Optional - A dictionary of functions to be used. - **ParallelToolCalls** - Optional - Enables parallel tool calls. - **MetaData** (IDictionary) - Optional - Metadata to associate with the run. - **Temperature** (Double) - Optional - Controls randomness for the model's output. - **Stream** - Optional - Enables streaming of the response. - **ResponseFormat** (String) - Optional - Specifies the format of the response. - **TimeoutSec** (Int32) - Optional - Timeout in seconds for the run. - **MaxRetryCount** (Int32) - Optional - Maximum number of retries for the run. - **ApiBase** (Uri) - Optional - The base URI for the API. - **ApiKey** (SecureString) - Optional - The API key for authentication. - **Organization** (String) - Optional - The organization ID. - **AdditionalQuery** (IDictionary) - Optional - Additional query parameters. - **AdditionalHeaders** (IDictionary) - Optional - Additional headers for the request. - **AdditionalBody** (Object) - Optional - Additional body content for the request. ### Request Example ```powershell PS C:\> Start-ThreadRun -ThreadId 'thread_abc123' -Assistant 'asst_abc123' ``` ### Response (Details on response structure would typically be here, but are not provided in the source text.) ``` -------------------------------- ### API Key Setup Source: https://context7.com/mkht/psopenai/llms.txt Configure your OpenAI API key using environment variables, global variables, or per-call parameters. ```APIDOC ## API Key Setup ```powershell # Method 1 (recommended): environment variable $env:OPENAI_API_KEY = 'sk-...' # Method 2: global variable $global:OPENAI_API_KEY = 'sk-...' # Method 3: per-call parameter Request-ChatCompletion -Message "Hello" -ApiKey 'sk-...' ``` ``` -------------------------------- ### Start Real-time Session Audio Output Source: https://github.com/mkht/psopenai/blob/main/Docs/Start-RealtimeSessionAudioOutput.md This command initiates the audio output for real-time sessions. It requires Windows and PowerShell 7.4 or higher. ```powershell PS C:\> Start-RealtimeSessionAudioOutput ``` -------------------------------- ### Start Thread Run and Receive Output Source: https://github.com/mkht/psopenai/blob/main/CHANGELOG.md Initiate a thread run with a new assistant and a message. The output can then be received and waited upon using Receive-ThreadRun. ```PowerShell $Assistant = New-Assistant -Model "gpt-3.5-turbo" $Run = Start-ThreadRun -Assistant $Assistant -Message "Hello, what can you do for me?" $Result = $Run | Receive-ThreadRun -Wait ``` -------------------------------- ### Start-ThreadRun - ThreadAndRun Syntax Source: https://github.com/mkht/psopenai/blob/main/Docs/Start-ThreadRun.md This syntax is used to start a run when a thread ID is not explicitly provided. It requires an Assistant ID and a Message to initiate the run. ```APIDOC ## Start-ThreadRun - ThreadAndRun ### Description Starts a run using a provided Assistant ID and an initial Message. This overload is used when you need to create a new run context or when the thread ID is implicitly managed. ### Method Start-ThreadRun ### Parameters #### Path Parameters - **Assistant** (String) - Required - The ID of the assistant to use for the run. - **Message** (String) - Required - The initial message to send to the assistant. #### Query Parameters - **Images** (Object[]) - Optional - Images to be included with the message. - **ImageDetail** (String) - Optional - Specifies the detail level for image analysis. - **Model** (String) - Optional - The name of the model to use for the run. Overrides the assistant's default model. - **Instructions** (String) - Optional - Overrides the assistant's instructions for this specific run. - **ReasoningEffort** (String) - Optional - Constrains the reasoning effort for the model. Supported values: `none`, `low`, `medium`, `high`. - **AdditionalMessages** (Object[]) - Optional - Additional messages to include in the thread before starting the run. - **Role** (String) - Optional - The role of the message sender. - **FileIdsForCodeInterpreter** (Object[]) - Optional - File IDs to be made available to the code interpreter tool (max 20). - **VectorStoresForFileSearch** (Object[]) - Optional - Vector stores attached to the thread (max 1). - **MaxPromptTokens** (Int32) - Optional - Maximum prompt tokens for the run. - **MaxCompletionTokens** (Int32) - Optional - Maximum completion tokens for the run. - **TruncationStrategyType** (String) - Optional - The type of truncation strategy to use. - **TruncationStrategyLastMessages** (Int32) - Optional - The number of last messages to retain when using truncation. - **ToolChoice** (String) - Optional - Specifies the tool to be chosen for the run. - **ToolChoiceFunctionName** (String) - Optional - The name of the function to use for tool choice. - **UseCodeInterpreter** - Optional - Enables the code interpreter tool. - **UseFileSearch** - Optional - Enables the file search tool. - **Functions** (IDictionary) - Optional - A dictionary of functions to be used. - **ParallelToolCalls** - Optional - Enables parallel tool calls. - **MetaData** (IDictionary) - Optional - Metadata to associate with the run. - **Temperature** (Double) - Optional - Controls randomness for the model's output. - **Stream** - Optional - Enables streaming of the response. - **ResponseFormat** (Object) - Optional - Specifies the format of the response. - **JsonSchema** (String) - Optional - A JSON schema for the response format. - **TimeoutSec** (Int32) - Optional - Timeout in seconds for the run. - **MaxRetryCount** (Int32) - Optional - Maximum number of retries for the run. - **ApiBase** (Uri) - Optional - The base URI for the API. - **ApiKey** (SecureString) - Optional - The API key for authentication. - **Organization** (String) - Optional - The organization ID. - **AdditionalQuery** (IDictionary) - Optional - Additional query parameters. - **AdditionalHeaders** (IDictionary) - Optional - Additional headers for the request. - **AdditionalBody** (Object) - Optional - Additional body content for the request. ### Request Example ```powershell Start-ThreadRun -Assistant "asst_abc123" -Message "Hello, can you help me with this?" ``` ### Response (Details on response structure would typically be here, but are not provided in the source text.) ``` -------------------------------- ### Start and Monitor Batch Request Source: https://github.com/mkht/psopenai/blob/main/Guides/How_to_use_Batch.md Initiate a batch job using `Start-Batch` with the prepared items. Monitor its progress using `Get-Batch` or wait for completion with `Wait-Batch`. Batch jobs are asynchronous and take longer than standard requests. ```PowerShell # Create and start batch $Batch = $BatchItems | Start-Batch # First, the status of batch may "validating" or "in_progress" $Batch.status # Run Get-Batch several times and wait for the status to become "complete" $Batch = Get-Batch -BatchId $Batch.Id $Batch.status # Or, you can use Wait-Batch to wait until completion. $Batch = $Batch | Wait-Batch # Status may be "completed" $Batch.status ``` -------------------------------- ### Example: Delete a Video Job Source: https://github.com/mkht/psopenai/blob/main/Docs/Remove-Video.md Use this example to delete a specific video job by providing its VideoId. This is useful for cleaning up unneeded jobs. ```powershell PS C:\> Remove-Video -VideoId 'video_68ea' ``` -------------------------------- ### Get Embedding Vector for Input Text Source: https://github.com/mkht/psopenai/blob/main/Docs/Request-Embeddings.md Use this snippet to get a vector representation of a given input string. The output includes the embedding vector and the original text. ```powershell Request-Embeddings -Text 'Waiter, the food was delicious...' | select -ExpandProperty data ``` ```yaml object : embedding index : 0 embedding : {0.01004226, -0.01884855, 0.01824344, -0.01565562…} Text : Waiter, the food was delicious... ``` -------------------------------- ### Generate and Get Video Content with PowerShell Source: https://github.com/mkht/psopenai/blob/main/CHANGELOG.md Demonstrates how to generate a video using the 'sora-2' model and then retrieve its content, saving it to a file. Requires the New-Video and Get-VideoContent cmdlets. ```PowerShell $VideoJob = New-Video -Model 'sora-2' -Prompt "A cat playing piano" -Size 1280x720 $VideoJob | Get-VideoContent -OutFile "C:\output\cat_piano.mp4" -WaitForCompletion ``` -------------------------------- ### Start-Batch Cmdlet Source: https://github.com/mkht/psopenai/blob/main/Docs/Start-Batch.md This cmdlet creates and executes a batch from an uploaded file or input objects. It supports two main parameter sets: BatchInput for providing objects directly and FileId for referencing an uploaded file. ```APIDOC ## Start-Batch ### Description Creates and executes a batch from an uploaded file or input objects. ### Method Start-Batch ### Parameters #### BatchInput - **BatchInput** (Object[]) - Required - Specifies batch input objects. - **Endpoint** (String) - Optional - The endpoint to be used for all requests in the batch. Currently "/v1/chat/completions", "/v1/embeddings", and "/v1/completions" are supported. Default: "/v1/chat/completions" - **CompletionWindow** (String) - Optional - The time frame within which the batch should be processed. Currently only "24h" is supported. Default: "24h" - **OutputExpiresAfterSeconds** (Int32) - Optional - The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days). - **OutputExpiresAfterAnchor** (String) - Optional - Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`. - **MetaData** (IDictionary) - Optional - Set of 16 key-value pairs that can be attached to an object. - **TimeoutSec** (Int32) - Optional - Specifies how long the request can be pending before it times out. Default: 0 (infinite). - **MaxRetryCount** (Int32) - Optional - Number between `0` and `100`. Specifies the maximum number of retries if the request fails. Default: 0 (No retry). - **ApiBase** (Uri) - Optional - Specifies an API endpoint URL such like: `https://your-api-endpoint.test/v1`. Default: `https://api.openai.com/v1` - **ApiKey** (SecureString) - Optional - Specifies API key for authentication. If not specified, it will try to use `$global:OPENAI_API_KEY` or `$env:OPENAI_API_KEY`. #### FileId - **FileId** (String) - Required - Specifies a input file id that is uploaded on the OpenAI storage in advance. - **Endpoint** (String) - Optional - The endpoint to be used for all requests in the batch. Currently "/v1/chat/completions", "/v1/embeddings", and "/v1/completions" are supported. Default: "/v1/chat/completions" - **CompletionWindow** (String) - Optional - The time frame within which the batch should be processed. Currently only "24h" is supported. Default: "24h" - **OutputExpiresAfterSeconds** (Int32) - Optional - The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days). - **OutputExpiresAfterAnchor** (String) - Optional - Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`. - **MetaData** (IDictionary) - Optional - Set of 16 key-value pairs that can be attached to an object. - **TimeoutSec** (Int32) - Optional - Specifies how long the request can be pending before it times out. Default: 0 (infinite). - **MaxRetryCount** (Int32) - Optional - Number between `0` and `100`. Specifies the maximum number of retries if the request fails. Default: 0 (No retry). - **ApiBase** (Uri) - Optional - Specifies an API endpoint URL such like: `https://your-api-endpoint.test/v1`. Default: `https://api.openai.com/v1` - **ApiKey** (SecureString) - Optional - Specifies API key for authentication. If not specified, it will try to use `$global:OPENAI_API_KEY` or `$env:OPENAI_API_KEY`. ### Examples #### Example 1 ```powershell PS C:\> Start-Batch -FileId 'file-abc123' ``` Creates and executes a batch from an uploaded file. You need to upload formatted jsonl file to the OpenAI storage in advance. #### Example 2 ```powershell PS C:\> $BatchInputs = @() PS C:\> $BatchInputs += Request-ChatCompletion -Message 'Good morning.' -Model gpt-4o-mini -AsBatch -CustomBatchId 'custom-1' PS C:\> $BatchInputs += Request-ChatCompletion -Message 'Good night.' -Model gpt-4o-mini -AsBatch -CustomBatchId 'custom-2' PS C:\> Start-Batch -InputObject $BatchInputs ``` Creates and executes a batch from input items. You can create a batch input item by using the Request-ChatCompletion cmdlet with `-AsBatch` switch. ``` -------------------------------- ### Handle audio input and output Source: https://github.com/mkht/psopenai/blob/main/Docs/Request-ChatCompletion.md Shows how to process audio input and generate audio output using the -Modalities, -InputAudio, and -AudioOutFile parameters with a compatible model. ```PowerShell Request-ChatCompletion -Modalities text, audio -InputAudio 'C:\hello.mp3' -AudioOutFile 'C:\response.mp3' -Model gpt-4o-audio-preview ``` -------------------------------- ### Start-VectorStoreFileBatch Source: https://github.com/mkht/psopenai/blob/main/Docs/Start-VectorStoreFileBatch.md Creates and runs a batch of files for a specified vector store. This operation allows for adding multiple files to a vector store and configuring how they are processed, including chunking strategies and size limits. ```APIDOC ## Start-VectorStoreFileBatch ### Description Creates and runs a batch of files for a specified vector store. This operation allows for adding multiple files to a vector store and configuring how they are processed, including chunking strategies and size limits. ### Syntax ```powershell Start-VectorStoreFileBatch [-VectorStoreId] [-Attributes ] [-Files] [-ChunkingStrategy ] [-MaxChunkSizeTokens ] [-ChunkOverlapTokens ] [-TimeoutSec ] [-MaxRetryCount ] [-ApiBase ] [-ApiKey ] [-Organization ] [] ``` ### Parameters #### -VectorStoreId * **Type**: String * **Aliases**: vector_store_id * **Required**: True * **Position**: 0 * **Accept pipeline input**: True (ByValue, ByPropertyName) * **Description**: The ID of the vector store for which to create a File Batch. #### -Attributes * **Type**: Hashtable * **Required**: False * **Position**: Named * **Description**: Set of 16 key-value pairs that can be attached to an object. #### -Files * **Type**: Object[] * **Aliases**: file_ids, FileId * **Required**: True * **Position**: 1 * **Description**: A list of File IDs that the vector store should use. #### -ChunkingStrategy * **Type**: String * **Aliases**: chunking_strategy * **Required**: False * **Position**: Named * **Description**: The chunking strategy used to chunk the file(s). If not set, will use the "auto" strategy. #### -MaxChunkSizeTokens * **Type**: String * **Aliases**: max_chunk_size_tokens * **Required**: False * **Position**: Named * **Default value**: 800 * **Description**: The maximum number of tokens in each chunk. The default value is 800. The minimum value is 100 and the maximum value is 4096. Note that the parameter only acceptable when the ChunkingStrategy is "static". #### -ChunkOverlapTokens * **Type**: String * **Aliases**: chunk_overlap_tokens * **Required**: False * **Position**: Named * **Default value**: 400 * **Description**: The number of tokens that overlap between chunks. The default value is 400. The value must not exceed half of MaxChunkSizeTokens. Note that the parameter only acceptable when the ChunkingStrategy is "static". #### -TimeoutSec * **Type**: Int32 * **Required**: False * **Position**: Named * **Default value**: 0 * **Description**: Specifies how long the request can be pending before it times out. The default value is `0` (infinite). #### -MaxRetryCount * **Type**: Int32 * **Required**: False * **Position**: Named * **Default value**: 0 * **Description**: Number between `0` and `100`. Specifies the maximum number of retries if the request fails. The default value is `0` (No retry). Note : Retries will only be performed if the request fails with a `429 (Rate limit reached)` or `5xx (Server side errors)` error. Other errors (e.g., authentication failure) will not be performed. #### -ApiBase * **Type**: System.Uri * **Required**: False * **Position**: Named * **Default value**: https://api.openai.com/v1 * **Description**: Specifies an API endpoint URL such like: `https://your-api-endpoint.test/v1`. If not specified, it will use `https://api.openai.com/v1`. #### -ApiKey * **Type**: Object * **Required**: False * **Position**: Named * **Description**: Specifies API key for authentication. The type of data should `[string]` or `[securestring]`. If not specified, it will try to use `$global:OPENAI_API_KEY` or `$env:OPENAI_API_KEY`. #### -Organization * **Type**: string * **Aliases**: OrgId * **Required**: False * **Position**: Named * **Description**: Specifies Organization ID which used for an API request. If not specified, it will try to use `$global:OPENAI_ORGANIZATION` or `$env:OPENAI_ORGANIZATION`. ### Example ```powershell PS C:\> Start-VectorStoreFileBatch -VectorStoreId 'vs_abc123' -Files ('file-abc123', 'file-def456', 'file-ghi789') ``` Start a batch for adding 3 files to the vector store with ID `vs_abc123` ``` -------------------------------- ### Get Specific Assistant by ID Source: https://github.com/mkht/psopenai/blob/main/Docs/Get-Assistant.md Retrieves a single assistant using its unique identifier. ```powershell PS C:\> Get-Assistant -AssistantId 'asst_abc123' ``` -------------------------------- ### Get All Batches Source: https://github.com/mkht/psopenai/blob/main/Docs/Get-Batch.md Retrieves all available batches. Use the -All switch to bypass any default limits. ```powershell PS C:\> Get-Batch -All ``` -------------------------------- ### Create an Assistant with Code Interpreter Source: https://github.com/mkht/psopenai/blob/main/Guides/How_to_use_Assistants.md Use the `New-Assistant` cmdlet to create an Assistant. Specify the name, model, and enable tools like Code Interpreter. Ensure the PSOpenAI module is imported and the API key is set. ```PowerShell # Import PSOpenAI module and Set API key. Import-Module ..\PSOpenAI.psd1 -Force $env:OPENAI_API_KEY = '' # Create an Assistant $Assistant = New-Assistant ` -Name "Math Teacher" ` -Model "gpt-3.5-turbo" ` -UseCodeInterpreter ` -Instructions "You are a personal math tutor. Write and run code to answer math questions." ``` -------------------------------- ### Request Realtime Session Response Source: https://github.com/mkht/psopenai/blob/main/Docs/Request-RealtimeSessionResponse.md Initiates a request for the server to generate a response. This is a basic usage example. ```powershell PS C:\> Request-RealtimeSessionResponse ``` -------------------------------- ### Start-RealtimeSessionAudioOutput Source: https://github.com/mkht/psopenai/blob/main/Docs/Start-RealtimeSessionAudioOutput.md Activates audio output for real-time sessions. ```APIDOC ## Start-RealtimeSessionAudioOutput ### Description Output voice responses from the server through the computer's speaker device. This command activates the ability to wait for a voice response from the server and output from the client computer's speaker device. To stop this, the Stop-RealtimeSessionAudioOutput command must be executed. This command only works with Windows and PowerShell 7.4 or higher systems. It will not work on Linux systems or older PowerShell versions. ### Method Start-RealtimeSessionAudioOutput ### Parameters This command does not accept any parameters. ### Example ```powershell PS C:\> Start-RealtimeSessionAudioOutput ``` ``` -------------------------------- ### Create Batch from Input Objects Source: https://github.com/mkht/psopenai/blob/main/Docs/Start-Batch.md This example demonstrates creating a batch from input objects. Each input object is generated using the Request-ChatCompletion cmdlet with the -AsBatch switch. This is useful for dynamically creating batch tasks. ```powershell PS C:\> $BatchInputs = @() PS C:\> $BatchInputs += Request-ChatCompletion -Message 'Good morning.' -Model gpt-4o-mini -AsBatch -CustomBatchId 'custom-1' PS C:\> $BatchInputs += Request-ChatCompletion -Message 'Good night.' -Model gpt-4o-mini -AsBatch -CustomBatchId 'custom-2' PS C:\> Start-Batch -InputObject $BatchInputs ``` -------------------------------- ### Remove-Conversation Cmdlet Example Source: https://github.com/mkht/psopenai/blob/main/Docs/Remove-Conversation.md Deletes a conversation using its unique identifier. Ensure the ConversationId is correctly specified. ```powershell PS C:\> Remove-Conversation -ConversationId "conv_abc123" ``` -------------------------------- ### Get Run Results Source: https://github.com/mkht/psopenai/blob/main/Docs/Receive-ThreadRun.md Retrieves the results of a specific run using its Run ID and Thread ID. ```powershell PS C:\> Get-ThreadRun -RunId 'run_abc123' -ThreadId 'thread_abc123' | Receive-ThreadRun ``` -------------------------------- ### Get Specific Message Source: https://github.com/mkht/psopenai/blob/main/Docs/Get-ThreadMessage.md Retrieves a specific message from a thread using its Thread ID and Message ID. ```APIDOC ## Get-ThreadMessage - Get Specific Message ### Description Retrieves a specific message from a thread using its Thread ID and Message ID. ### Method GET (conceptual, as this is a PowerShell cmdlet) ### Endpoint (Not directly applicable, as this is a cmdlet) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ThreadId** (String) - Required - The ID of the Thread to retrieve messages from. - **MessageId** (String) - Required - The ID of the specific Message to retrieve. - **TimeoutSec** (Int32) - Optional - Specifies how long the request can be pending before it times out. Default is 0 (infinite). - **MaxRetryCount** (Int32) - Optional - Specifies the maximum number of retries if the request fails. Default is 0 (No retry). - **ApiBase** (Uri) - Optional - Specifies an API endpoint URL. Defaults to `https://api.openai.com/v1`. - **ApiKey** (SecureString) - Optional - Specifies API key for authentication. - **Organization** (String) - Optional - Specifies Organization ID for the API request. ### Request Example ```powershell Get-ThreadMessage -ThreadId 'thread_abc123' -MessageId 'msg_abc123' ``` ### Response #### Success Response (200) - **field1** (type) - Description (Details not provided in source) #### Response Example (Details not provided in source) ``` -------------------------------- ### Create Assistant with File Search Enabled Source: https://github.com/mkht/psopenai/blob/main/Guides/How_to_use_FileSearch_with_VectorStore.md Create a new Assistant, specifying the model, enabling file search, and associating it with a Vector Store. Set instructions to guide the Assistant's behavior. ```PowerShell # Create a new Assistant with File Search Enabled $Assistant = New-Assistant \ -Name "My Assistant" \ -Model "gpt-4o-mini" \ -UseFileSearch \ -VectorStoresForFileSearch $VectorStore \ -Instructions "You are a helpful assistant. You have access to the files you need to answer questions. Always answer based on the contents of the file." ``` -------------------------------- ### Wait for Run Completion Source: https://github.com/mkht/psopenai/blob/main/Docs/Receive-ThreadRun.md Starts a run and then waits for its completion before returning the results. This is useful for synchronous processing. ```powershell PS C:\> Start-ThreadRun -ThreadId 'thread_abc123' | Receive-ThreadRun -Wait ``` -------------------------------- ### Basic Request-Response Usage Source: https://github.com/mkht/psopenai/blob/main/Guides/Migrate_ChatCompletion_to_Response.md Demonstrates the basic usage of the Request-Response cmdlet to send a message and display the output. ```powershell $Output = Request-Response -Message 'Hello' -Model 'gpt-4o-mini' $Output | Format-List ``` ```powershell id : resp_abc123 object : response status : completed model : gpt-4o-mini-2024-07-18 output : {@{id=msg_abc123; type=message; status=completed; content=System.Object[]; role=assistant}} previous_response_id : store : True truncation : disabled usage : @{input_tokens=8; input_tokens_details=; output_tokens=10; output_tokens_details=; total_tokens=18} created_at : 2025/04/11 10:15:43 LastUserMessage : Hello output_text : Hello! How can I assist you today? History : {@{role=user; content=System.Object[]}, @{role=assistant; content=System.Object[]}} ``` -------------------------------- ### Download Container File Content using ContainerFile Object Source: https://github.com/mkht/psopenai/blob/main/Docs/Get-ContainerFileContent.md This example demonstrates how to first retrieve a ContainerFile object using Get-ContainerFile and then use that object to download the file content, saving it to a local file. This approach is useful when you already have the ContainerFile object. ```powershell PS C:\> $File = Get-ContainerFile -ContainerId 'cont_abc123' -FileId 'file-abc123' PS C:\> Get-ContainerFileContent -ContainerFile $File -OutFile 'C:\data\sample.pdf' ``` -------------------------------- ### Get a specific item from a conversation Source: https://github.com/mkht/psopenai/blob/main/Docs/Get-ConversationItem.md Retrieves a single, specific item from a conversation using its unique item ID. ```APIDOC ## Get-ConversationItem (Specific Item) ### Description Retrieves a specific item from a conversation by its unique ID. ### Method GET ### Endpoint /conversations/{conversationId}/items/{itemId} ### Parameters #### Path Parameters - **conversationId** (String) - Required - The unique identifier of the conversation. - **itemId** (String) - Required - The unique identifier of the item to retrieve. #### Query Parameters - **TimeoutSec** (Int32) - Optional - Specifies how long the request can be pending before it times out. Default is 0 (infinite). - **MaxRetryCount** (Int32) - Optional - Specifies the maximum number of retries if the request fails. Default is 0 (No retry). - **ApiBase** (Uri) - Optional - Specifies the API endpoint URL. - **ApiKey** (SecureString) - Optional - Specifies the API key for authentication. ### Request Example ```powershell Get-ConversationItem -ConversationId 'conv_abc123' -ItemId 'item_xyz789' ``` ### Response #### Success Response (200) - **id** (String) - The unique identifier of the item. - **created_at** (Int32) - The timestamp when the item was created. - **object** (String) - The type of the object (e.g., 'thread.message'). - **thread_id** (String) - The ID of the conversation this item belongs to. - **role** (String) - The role of the sender (e.g., 'user', 'assistant'). - **content** (Array) - The content of the message. #### Response Example ```json { "id": "item_xyz789", "created_at": 1678886400, "object": "thread.message", "thread_id": "conv_abc123", "role": "assistant", "content": [ { "type": "text", "text": { "value": "Here is the information you requested." } } ] } ``` ``` -------------------------------- ### Start and Wait for Batch Completion Source: https://github.com/mkht/psopenai/blob/main/Docs/Wait-Batch.md Initiates a batch process and then waits for it to complete. This is a common pattern for asynchronous operations. ```powershell PS C:\> $BatchInputs | Start-Batch | Wait-Batch ``` -------------------------------- ### Get Specific Batch by ID Source: https://github.com/mkht/psopenai/blob/main/Docs/Get-Batch.md Retrieves a single batch using its unique identifier. The -BatchId parameter is required for this operation. ```powershell PS C:\> Get-Batch -BatchId 'batch_abc123' ``` -------------------------------- ### Activate Speaker Output Source: https://github.com/mkht/psopenai/blob/main/Guides/How_to_use_Realtime_API.md Start the audio output stream to the speaker device. This is part of enabling voice-based responses from the AI. ```powershell # Activates speaker output. Start-RealtimeSessionAudioOutput ``` -------------------------------- ### New-Assistant Source: https://github.com/mkht/psopenai/blob/main/Docs/New-Assistant.md Creates a new assistant with specified parameters. This command allows for detailed configuration of an assistant, including its name, model, instructions, and the tools it can utilize. ```APIDOC ## New-Assistant ### Description Create an assistant with a model and instructions. An Assistant represents an entity that can be configured to respond to users’ Messages using several parameters. ### Syntax ```powershell New-Assistant [-Name ] [-Model ] [-Description ] [-Instructions ] [-ReasoningEffort ] [-UseCodeInterpreter] [-UseFileSearch] [-Functions ] [-FileIdsForCodeInterpreter ] [-VectorStoresForFileSearch ] [-MaxNumberOfFileSearchResults ] [-RankerForFileSearch ] [-ScoreThresholdForFileSearch ] [-FileIdsForFileSearch ] [-Temperature ] [-TopP ] [-MetaData ] [-ResponseFormat ] [-JsonSchema ] [-TimeoutSec ] [-MaxRetryCount ] [-ApiBase ] [-ApiKey ] [-Organization ] [] ``` ### Parameters #### -Name The name of the assistant. The maximum length is 256 characters. ```yaml Type: String Required: False Position: Named ``` #### -Model ID of the model to use. The default value is `gpt-3.5-turbo`. ```yaml Type: String Required: False Position: Named Default value: gpt-3.5-turbo ``` #### -Description The description of the assistant. The maximum length is 512 characters. ```yaml Type: String Required: False Position: Named ``` #### -Instructions The system instructions that the assistant uses. The maximum length is 256,000 characters. ```yaml Type: String Required: False Position: Named ``` #### -ReasoningEffort Constrains effort on reasoning for reasoning models. Supported values are `none`, `low`, `medium`, and `high`. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response. ```yaml Type: String Aliases: reasoning_effort Required: False Position: Named ``` #### -UseCodeInterpreter Specifies Whether the code interpreter tool enable or not. The default is `$false`. ```yaml Type: SwitchParameter Required: False Position: Named Default value: $false ``` #### -UseFileSearch Specifies Whether the file_search tool enable or not. The default is `$false`. ```yaml Type: SwitchParameter Required: False Position: Named Default value: $false ``` #### -Functions A list of functions the model may call. Use this to provide a list of functions the model may generate JSON inputs for. ```yaml Type: IDictionary[] Required: False Position: Named ``` #### -FileIdsForCodeInterpreter A list of file IDs made available to the code_interpreter tool. There can be a maximum of 20 files associated with the tool. ```yaml Type: Object[] Required: False Position: Named ``` #### -VectorStoresForFileSearch The vector store attached to this assistant. There can be a maximum of 1 vector store attached to the assistant. ```yaml Type: Object[] Required: False Position: Named ``` #### -FileIdsForFileSearch A list of file IDs to add to the vector store. There can be a maximum of 10000 files in a vector store. ```yaml Type: Object[] Required: False Position: Named ``` #### -MaxNumberOfFileSearchResults The maximum number of results the file search tool should output. This number should be between 1 and 50 inclusive. ```yaml Type: UInt16 Required: False Position: Named ``` #### -RankerForFileSearch The ranker to use for the file search. If not specified will use the auto ranker. ```yaml Type: String Required: False Position: Named ``` #### -ScoreThresholdForFileSearch The score threshold for the file search. All values must be a floating point number between 0 and 1. ```yaml Type: double Required: False Position: Named ``` #### -Temperature What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. ```yaml Type: double Required: False Position: Named ``` #### -TopP An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. ```yaml Type: double Aliases: top_p Required: False Position: Named ``` ### Example 1 ```powershell PS C:\> $Assistant = New-Assistant -Model gpt-4 -Instructions "You are a math teacher." -UseCodeInterpreter $true ``` Create an assitant with a model and instructions and enable to use code interpreter. ``` -------------------------------- ### Start and Wait for Thread Run Completion Source: https://github.com/mkht/psopenai/blob/main/Docs/Wait-ThreadRun.md Initiates a thread run and then waits for its completion. This is a common pattern for asynchronous operations. ```powershell PS C:\> $Thread | Start-ThreadRun | Wait-ThreadRun ``` -------------------------------- ### Create a New Video Generation Job Source: https://github.com/mkht/psopenai/blob/main/Docs/New-Video.md Use this cmdlet to create a new video generation job with a text prompt. Default model, duration, and resolution are used if not specified. ```powershell PS C:\> New-Video -Prompt 'Dancing Doggo' ``` -------------------------------- ### Stream Audio Transcription Output Source: https://github.com/mkht/psopenai/blob/main/CHANGELOG.md Example of transcribing audio with streaming output enabled. The output is piped to Write-Host without a newline. ```PowerShell # Example for transcription with streaming output Request-AudioTranscription -Model 'gpt-4o-transcribe' -File 'C:\audio.wav' -Stream | Write-Host -NoNewline ``` -------------------------------- ### Edit an image with a prompt Source: https://github.com/mkht/psopenai/blob/main/Docs/Request-ImageEdit.md Use this example to edit an existing image by providing a prompt and specifying the output file and size. Ensure the image file exists at the specified path. ```PowerShell Request-ImageEdit -Model 'gpt-image-1.5' -Prompt 'A bird on the desert' -Image 'C:\sand_with_fether.png' -OutFile 'C:\bird_on_desert.png' -Size 1024x1024 ``` -------------------------------- ### Get Latest Batches with Limit Source: https://github.com/mkht/psopenai/blob/main/Docs/Get-Batch.md Retrieves the 5 most recent batches. Use the -Limit parameter to specify the number of batches to return. ```powershell PS C:\> Get-Batch -Limit 5 ``` -------------------------------- ### Import Module and Set API Key Source: https://github.com/mkht/psopenai/blob/main/Guides/How_to_use_Video_generation.md Import the PSOpenAI module and set your OpenAI API key. This is a prerequisite for using any video generation cmdlets. ```powershell Import-Module ..\PSOpenAI.psd1 -Force $env:OPENAI_API_KEY = '' ```