|
<< Click to Display Table of Contents >> Navigation: 3. Script Language > JSON - Parser > Text-Operations > PSJ. - JSON Operations |
SPR Script Language
PSJ.ExtractFinishReason
Extracts finish reason from first choice.
Intention
The PSJ.ExtractFinishReason command in SPR takes a JSON string ($$JSON) and extracts the "finish_reason" string from the first item in the "choices" array, storing it in an optional variable ($$RET). It’s like asking your robot to check a JSON logbook, find the first entry in a list of completed tasks, and tell you why that task stopped—such as "done" or "timeout".
For example, from {"choices":[{"finish_reason":"stop"}]}, it pulls out "stop" as the reason the first choice ended.
Illustration
📝 Extract: PSJ.ExtractFinishReason|{"choices":[{"finish_reason":"stop"}]}|$$RSN sets $$RSN to "stop".
📝 Multi: PSJ.ExtractFinishReason|{"choices":[{"finish_reason":"done"},{"finish_reason":"error"}]}|$$END sets $$END to "done" (first only).
Syntax
PSJ.ExtractFinishReason|$$JSON[|$$RET]
Parameter Explanation
P1 - $$JSON - (Variable, String)
The JSON string to parse (e.g., $$JSON as "{\"choices\":[{\"finish_reason\":\"stop\"}]}"). Required.
P2 - $$RET - (Variable, String, Optional)
The variable to store the extracted finish reason string (e.g., $$RET as "$$RSN"). If omitted, the string is returned but not stored.
Technical Background
This command calls W_JSON_ExtractFinishReason, which parses a JSON string (jsonText) and extracts the "finish_reason" string from the path "choices.0.finish_reason". It returns the string (e.g., "stop" from {"choices":[{"finish_reason":"stop"}]}) or an empty string if an error occurs (e.g., invalid JSON or missing path). Internally, it uses W_JSON_ParseString to create a handle, W_JSON_GetStringByPath to extract the value, and W_JSON_FreeHandle to clean up. No handle is returned, so no freeing is needed by the caller.
Examples
'***********************************
' Sample 1: Extract Simple Reason
PSJ.ExtractFinishReason|{"choices":[{"finish_reason":"stop"}]}|$$RSN
' Print the extracted reason
PRT.Reason: $$RSN
MBX.Ready
'***********************************
' Sample 2: First of Multiple Choices
PSJ.ExtractFinishReason|{"choices":[{"finish_reason":"done"},{"finish_reason":"error"}]}|$$END
' Print the extracted reason
PRT.Reason: $$END
MBX.Ready
'***********************************
' Sample 3: No Return Variable
PSJ.ExtractFinishReason|{"choices":[{"finish_reason":"timeout"}]}
' Reason returned but not stored
MBX.Ready
Remarks
- Returns the "finish_reason" string from the first "choices" item; no handle is created.
- Returns an empty string if the path "choices.0.finish_reason" is missing or invalid.
- Use PSJ.ErrCode to diagnose errors if the result is empty.
Limitations
- $$JSON must be valid JSON with a "choices" array.
- Only extracts from the first choice (index 0).
- Requires the exact path "choices.0.finish_reason".
See also: