Filter
uncanny-automator
automator_open_ai_text_generate
Filters the body of the request sent to OpenAI for text generation.
add_filter( 'automator_open_ai_text_generate', $callback, 10, 1 );
Description
Filters the arguments passed to the OpenAI text generation API. Developers can modify the `prompt`, `temperature`, `max_tokens`, and `model` parameters before the API request is made, allowing for custom control over the generated text. This hook fires just before the API call.
Usage
add_filter( 'automator_open_ai_text_generate', 'your_function_name', 10, 1 );
Parameters
-
$body(mixed) - This parameter represents the response body received from the OpenAI API.
Return Value
The filtered value.
Examples
// Example: Modify the request body for OpenAI text generation.
// This callback function allows developers to adjust parameters like temperature,
// max tokens, or even the prompt itself before it's sent to the OpenAI API.
add_filter(
'automator_open_ai_text_generate',
function( $body ) {
// Example: Increase the temperature slightly to make the output more creative.
// Ensure temperature is within a valid range (0 to 2).
if ( isset( $body['temperature'] ) && $body['temperature'] < 1.5 ) {
$body['temperature'] = min( 1.5, $body['temperature'] + 0.2 );
}
// Example: Append a specific instruction to the prompt to ensure certain output format.
if ( isset( $body['prompt'] ) ) {
$body['prompt'] = $body['prompt'] . "nnFormat the response as a JSON object.";
}
// Example: Limit the maximum tokens for shorter responses.
// Ensure max_tokens is a reasonable positive integer.
if ( isset( $body['max_tokens'] ) && $body['max_tokens'] > 500 ) {
$body['max_tokens'] = 500;
}
return $body;
},
10, // Priority
1 // Number of accepted arguments
);
Placement
This code should be placed in the functions.php file of your active theme, a custom plugin, or using a code snippets plugin.
Source Code
src/integrations/open-ai/actions/open-ai-text-generate.php:122
protected function process_action( $user_id, $action_data, $recipe_id, $args, $parsed ) {
$this->helpers->migrate_text_models( $recipe_id );
// Read from post meta (not $parsed) because migrate_text_models() may have just updated it.
$model = get_post_meta( $action_data['ID'], 'MODEL', true );
$temperature = ! empty( $parsed['TEMPERATURE'] ) ? sanitize_text_field( $parsed['TEMPERATURE'] ) : '0.7';
$max_tokens = ! empty( $parsed['MAX_LEN'] ) ? sanitize_text_field( $parsed['MAX_LEN'] ) : '256';
$prompt = sanitize_textarea_field( $parsed[ $this->get_action_meta() ] ?? '' );
$body = array(
'prompt' => $prompt,
'temperature' => floatval( $temperature ),
'max_tokens' => intval( $max_tokens ),
'model' => $model,
);
$body = apply_filters( 'automator_open_ai_text_generate', $body );
$response = $this->api->openai_request( 'v1/completions', $body );
$response_text = $this->api->get_completion_text( $response );
$this->hydrate_tokens(
array(
'RESPONSE' => $response_text,
)
);
return true;
}