Skip to content

Response Reconstruction

After an upstream provider returns a Chat Completions response, GodeX must reconstruct it into the shape of an OpenAI Responses API ResponseObject. This is the inverse of Request Building -- tool calls must be restored to their original types, finish reasons must be mapped to the Responses status model, reasoning text must be extracted, and output contracts must be validated. The reconstructResponseObject function handles this entire transformation.

At a Glance

StepFunctionPurpose
1firstChoice extractionGet the first choice from the provider response
2outputText extractionRead the text content from the choice message
3validateOutputContractIf requiresValidJson, parse and validate the output
4mapProviderFinishReasonMap provider finish reason to Responses status
5restoreToolCall (per call)Restore each tool call to its original Responses type
6Reasoning text extractionExtract reasoning_content from the choice message
7Assemble ResponseObjectCombine all parts into the final response

Finish Reason Mapping

Providers use various finish_reason strings. The mapProviderFinishReason function maps these to the Responses API's terminal states (completed, incomplete, failed):

Provider finish_reasonResponses statusincomplete_details.reasonerror
stopcompletednullnull
tool_callscompletednullnull
lengthincomplete"max_output_tokens"null
model_context_window_exceededincomplete"max_output_tokens"null
content_filterincomplete"content_filter"null
sensitiveincomplete"content_filter"null
network_errorfailednull{ code: SERVER_ERROR, message }
null / undefinedfailednull"Provider returned no finish reason"
Any other valuefailednull"Unexpected finish reason"

Reconstruction Sequence

Tool Call Restoration

The restoreToolCall function uses the ToolIdentityMap to reverse the provider-side tool name back to the original Responses type. Each provider function call carries (callId, name, arguments). The identity map provides the requestedType which determines the reconstruction path:

requestedTypeReconstructionFallback
function{ type: "function_call", call_id, name, arguments }Always succeeds
shellParse arguments as JSON; extract commands arrayFallback to function_call
local_shellParse arguments as JSON; extract command array + envFallback to function_call
apply_patchParse arguments as JSON; extract operation objectFallback to function_call
customParse arguments as JSON; extract input stringFallback to function_call

When parsing fails (malformed JSON, missing fields), restoreToolCall falls back to a generic function_call ResponseItem using the requestedName from the identity map. This ensures the response is always valid even when the provider's output is unexpected.

Tool Identity Map

The ToolIdentityMap is built during request building and carries the bidirectional mapping between requested tool names/types and provider tool names/types. During reconstruction it is used in reverse:

Request-Building DirectionReconstruction Direction
requestedName -> providerNameproviderName -> requestedName
requestedType -> providerTypeproviderName -> requestedType

The map enforces uniqueness: if two different tools map to the same provider name, a BridgeError is thrown during request building.

Output Contract Validation

When the output contract was degraded (e.g., json_schema to json_object with strict: true), requiresValidJson is set. After reconstruction, validateOutputContract parses the output text as JSON:

  • Pass: The response is valid JSON; the ResponseObject is returned normally.
  • Fail: A BridgeFailure is thrown with code BRIDGE_RESPONSE_INVALID_OUTPUT_FORMAT, including the provider, model, and response ID in the metadata.

ResponseObject Assembly

The final ResponseObject is assembled from all collected parts:

FieldSource
idGenerated responseId from request identity
objectAlways "response"
created_atTimestamp from context creation
completed_atCurrent timestamp at reconstruction
statusFrom mapProviderFinishReason
modelResolved model name
outputArray of ResponseItems: reasoning, tool calls, assistant message
output_textExtracted text content
usageFrom accessor.usage()
errorFrom finish reason mapping (null if completed)
incomplete_detailsFrom finish reason mapping (null if completed)

The output array is ordered: reasoning items first, then restored tool calls, then the assistant message (if there is text or no tool calls were present).

Cross-References

References