Unify structured call completion and retain typed failures
This commit is contained in:
@@ -17,7 +17,7 @@ import (
|
||||
)
|
||||
|
||||
// CallHooks receive one logical start and finish record and the execution
|
||||
// events for this call. Call records can contain transcript content.
|
||||
// events associated with the call.
|
||||
type CallHooks struct {
|
||||
OnCall func(structuredoutput.CallRecord)
|
||||
OnEvent pk.ExecutionObserver
|
||||
@@ -45,35 +45,25 @@ func (r *Runtime) NewRoleClient(role, profileID string, settings config.LLM, hoo
|
||||
}
|
||||
|
||||
type pendingCall struct {
|
||||
request pk.RunRequest
|
||||
finish func(*pk.RunResult, error) (structuredoutput.Response, error)
|
||||
request pk.RunRequest
|
||||
once sync.Once
|
||||
complete func(*pk.RunResult, error) (structuredoutput.Response, error)
|
||||
response structuredoutput.Response
|
||||
err error
|
||||
}
|
||||
|
||||
func (p *pendingCall) finish(result *pk.RunResult, err error) (structuredoutput.Response, error) {
|
||||
p.once.Do(func() {
|
||||
p.response, p.err = p.complete(result, err)
|
||||
})
|
||||
return p.response, p.err
|
||||
}
|
||||
|
||||
func (c *RoleClient) prepareCall(parent context.Context, req structuredoutput.Request, out any, observer pk.ExecutionObserver) (*pendingCall, error) {
|
||||
var response structuredoutput.Response
|
||||
var err error
|
||||
var finishHooks []func()
|
||||
ctx := parent
|
||||
var terminalMu sync.Mutex
|
||||
var mu sync.Mutex
|
||||
var terminal pk.ExecutionEvent
|
||||
terminalAvailable := false
|
||||
finishHooks = append(finishHooks, func() {
|
||||
terminalMu.Lock()
|
||||
if terminalAvailable {
|
||||
response.Execution = outcomes.ExecutionCounts{
|
||||
Available: true,
|
||||
ProviderAttempts: int(terminal.Attempts),
|
||||
TransientRetries: int(terminal.TransientRetries),
|
||||
StructuralRepairs: int(terminal.RepairCalls),
|
||||
RetriesExhausted: terminal.RetriesExhausted,
|
||||
}
|
||||
if terminal.StatusCode != 0 {
|
||||
status := terminal.StatusCode
|
||||
response.Execution.HTTPStatus = &status
|
||||
}
|
||||
}
|
||||
terminalMu.Unlock()
|
||||
})
|
||||
var terminalAvailable bool
|
||||
var prepared *structuredoutput.PreparedSnapshot
|
||||
var record structuredoutput.CallRecord
|
||||
if c.hooks.OnCall != nil || c.hooks.OnEventWithCall != nil {
|
||||
record.CallID = c.runtime.nextCallID.Add(1)
|
||||
@@ -85,40 +75,61 @@ func (c *RoleClient) prepareCall(parent context.Context, req structuredoutput.Re
|
||||
record.Started = time.Now().UTC()
|
||||
record.Prompt = structuredoutput.PromptMetadata{PromptID: req.PromptID, ProfileID: c.profileID}
|
||||
onCall(record)
|
||||
finishHooks = append(finishHooks, func() {
|
||||
}
|
||||
call := &pendingCall{complete: func(result *pk.RunResult, runErr error) (structuredoutput.Response, error) {
|
||||
var response structuredoutput.Response
|
||||
mu.Lock()
|
||||
if terminalAvailable {
|
||||
response.Execution = outcomes.ExecutionCounts{
|
||||
Available: true, ProviderAttempts: int(terminal.Attempts),
|
||||
TransientRetries: int(terminal.TransientRetries), StructuralRepairs: int(terminal.RepairCalls),
|
||||
RetriesExhausted: terminal.RetriesExhausted,
|
||||
}
|
||||
if terminal.StatusCode != 0 {
|
||||
status := terminal.StatusCode
|
||||
response.Execution.HTTPStatus = &status
|
||||
}
|
||||
}
|
||||
if prepared != nil {
|
||||
response.Prepared = prepared
|
||||
response.Prompt = prepared.Prompt
|
||||
response.Model = prepared.Prompt.Model
|
||||
}
|
||||
mu.Unlock()
|
||||
if result != nil {
|
||||
response.FinalContent = result.RawOutput
|
||||
response.Model = result.ModelName
|
||||
}
|
||||
err := c.finishResponse(parent, &response, result, runErr, out)
|
||||
if onCall := c.hooks.OnCall; onCall != nil {
|
||||
if response.Prepared != nil {
|
||||
record.Prompt = response.Prompt
|
||||
}
|
||||
record.Finished = time.Now().UTC()
|
||||
if err != nil {
|
||||
var failure *structuredoutput.Failure
|
||||
if errors.As(err, &failure) && failure.Reason == outcomes.ReasonInvalidOutputExhausted {
|
||||
record.Failure = structuredoutput.FailureRuntime
|
||||
if structuredoutput.IsMalformedError(err) {
|
||||
record.Failure = structuredoutput.FailureMalformedOutput
|
||||
} else {
|
||||
record.Failure = structuredoutput.FailureRuntime
|
||||
}
|
||||
}
|
||||
onCall(record)
|
||||
})
|
||||
}
|
||||
finish := func() {
|
||||
for i := len(finishHooks) - 1; i >= 0; i-- {
|
||||
finishHooks[i]()
|
||||
}
|
||||
return response, err
|
||||
}}
|
||||
fail := func(err error) (*pendingCall, error) {
|
||||
_, err = call.finish(nil, err)
|
||||
return call, err
|
||||
}
|
||||
fail := func(failure error) (*pendingCall, error) {
|
||||
err = failure
|
||||
finish()
|
||||
return nil, failure
|
||||
if err := parent.Err(); err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
if parent.Err() != nil {
|
||||
return fail(classifiedFailure(parent, ctx, parent.Err(), nil))
|
||||
}
|
||||
if err = validateOutputTarget(out); err != nil {
|
||||
if err := validateOutputTarget(out); err != nil {
|
||||
return fail(&structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonSetupFailure, Message: "invalid structured output target", Cause: err})
|
||||
}
|
||||
contract, contractErr := OutputContract(req.Schema, c.settings.RepairAttempts)
|
||||
if contractErr != nil {
|
||||
return fail(&structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonSetupFailure, Message: "unknown structured response schema", Cause: contractErr})
|
||||
contract, err := OutputContract(req.Schema, c.settings.RepairAttempts)
|
||||
if err != nil {
|
||||
return fail(&structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonSetupFailure, Message: "unknown structured response schema", Cause: err})
|
||||
}
|
||||
vars := prompts.ProcessingVariables(req.Variables)
|
||||
var exchange *pk.Exchange
|
||||
if req.ContinueFrom != nil {
|
||||
var ok bool
|
||||
@@ -127,75 +138,68 @@ func (c *RoleClient) prepareCall(parent context.Context, req structuredoutput.Re
|
||||
return fail(&structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonSetupFailure, Message: "repair exchange is unavailable"})
|
||||
}
|
||||
}
|
||||
runRequest := pk.RunRequest{
|
||||
PromptID: req.PromptID, ProfileID: c.profileID, Vars: vars,
|
||||
call.request = pk.RunRequest{
|
||||
PromptID: req.PromptID, ProfileID: c.profileID, Vars: prompts.ProcessingVariables(req.Variables),
|
||||
CaptureExchange: req.CaptureExchange, ContinueFrom: exchange,
|
||||
TransientRetries: &c.settings.TransientRetries,
|
||||
Validation: contract,
|
||||
TransientRetries: &c.settings.TransientRetries, OperationTimeout: c.settings.OperationTimeout,
|
||||
Validation: contract,
|
||||
Observer: pk.ComposeObservers(observer, func(event pk.ExecutionEvent) {
|
||||
if event.Kind == pk.ExecutionFinished {
|
||||
terminalMu.Lock()
|
||||
mu.Lock()
|
||||
terminal = event
|
||||
terminalAvailable = true
|
||||
terminalMu.Unlock()
|
||||
mu.Unlock()
|
||||
}
|
||||
if c.hooks.OnEventWithCall != nil {
|
||||
c.hooks.OnEventWithCall(record.CallID, record.Context, event)
|
||||
}
|
||||
}),
|
||||
OnPrepared: func(_ context.Context, details pk.PreparedRun) {
|
||||
snapshot := preparedSnapshot(details)
|
||||
mu.Lock()
|
||||
prepared = snapshot
|
||||
mu.Unlock()
|
||||
},
|
||||
}
|
||||
var details pk.PreparedRun
|
||||
capturePrepared := func(_ context.Context, prepared pk.PreparedRun) {
|
||||
details = prepared
|
||||
response.Prompt = promptMetadata(details)
|
||||
record.Prompt = response.Prompt
|
||||
response.Model = details.EffectiveModelParams.Model
|
||||
response.Prepared = preparedSnapshot(details)
|
||||
record.Prepared = response.Prepared
|
||||
return call, nil
|
||||
}
|
||||
|
||||
func (c *RoleClient) finishResponse(parent context.Context, response *structuredoutput.Response, result *pk.RunResult, runErr error, out any) error {
|
||||
if runErr != nil || parent.Err() != nil {
|
||||
var typed *structuredoutput.Failure
|
||||
if parent.Err() == nil && errors.As(runErr, &typed) {
|
||||
return runErr
|
||||
}
|
||||
failure := classifiedFailure(parent, runErr, result)
|
||||
if failure.Reason == outcomes.ReasonSetupFailure && errors.Is(failure, pk.ErrAPIKeyEnvMissing) {
|
||||
failure.Message = fmt.Sprintf("structured model setup failed for %s profile %q: %v", c.role, c.profileID, failure.Cause)
|
||||
}
|
||||
return failure
|
||||
}
|
||||
runRequest.OperationTimeout = c.settings.OperationTimeout
|
||||
runRequest.OnPrepared = capturePrepared
|
||||
return &pendingCall{request: runRequest, finish: func(result *pk.RunResult, runErr error) (completed structuredoutput.Response, finalErr error) {
|
||||
defer func() { err = finalErr; finish(); completed = response }()
|
||||
|
||||
if result != nil {
|
||||
response.FinalContent = result.RawOutput
|
||||
record.FinalContent = result.RawOutput
|
||||
response.Model = result.ModelName
|
||||
response.PromptTokens = result.Usage.PromptTokens
|
||||
response.CompletionTokens = result.Usage.CompletionTokens
|
||||
response.TotalTokens = result.Usage.TotalTokens
|
||||
if result == nil {
|
||||
return &structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonInternalFailure, Message: "structured model call returned no result"}
|
||||
}
|
||||
if !result.Validation.IsValid {
|
||||
return classifiedFailure(parent, nil, result)
|
||||
}
|
||||
if decodeErr := json.Unmarshal([]byte(result.RawOutput), out); decodeErr != nil {
|
||||
var typeError *json.UnmarshalTypeError
|
||||
if errors.As(decodeErr, &typeError) {
|
||||
return &structuredoutput.Failure{Class: structuredoutput.FailureRecoverable, Reason: outcomes.ReasonInvalidOutput, Message: "structured output contains an unusable value", Cause: decodeErr}
|
||||
}
|
||||
if runErr != nil {
|
||||
return response, classifiedFailure(parent, ctx, runErr, result)
|
||||
}
|
||||
if result == nil {
|
||||
return response, &structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonInternalFailure, Message: "structured model call returned no result"}
|
||||
}
|
||||
if !result.Validation.IsValid {
|
||||
return response, classifiedFailure(parent, ctx, nil, result)
|
||||
}
|
||||
if decodeErr := json.Unmarshal([]byte(result.RawOutput), out); decodeErr != nil {
|
||||
var typeError *json.UnmarshalTypeError
|
||||
if errors.As(decodeErr, &typeError) {
|
||||
return response, &structuredoutput.Failure{Class: structuredoutput.FailureRecoverable, Reason: outcomes.ReasonInvalidOutput, Message: "structured output contains an unusable value", Cause: decodeErr}
|
||||
}
|
||||
return response, &structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonInternalFailure, Message: "validated structured output could not be decoded", Cause: decodeErr}
|
||||
}
|
||||
if result.Exchange != nil {
|
||||
response.Exchange = &structuredoutput.Exchange{State: result.Exchange}
|
||||
}
|
||||
|
||||
response.Content = json.RawMessage(result.RawOutput)
|
||||
response.Provider = "openai-compatible"
|
||||
return response, nil
|
||||
}}, nil
|
||||
return &structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonInternalFailure, Message: "validated structured output could not be decoded", Cause: decodeErr}
|
||||
}
|
||||
if result.Exchange != nil {
|
||||
response.Exchange = &structuredoutput.Exchange{State: result.Exchange}
|
||||
}
|
||||
response.Content = json.RawMessage(result.RawOutput)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *RoleClient) CompleteStructured(ctx context.Context, req structuredoutput.Request, out any) (structuredoutput.Response, error) {
|
||||
call, err := c.prepareCall(ctx, req, out, c.hooks.OnEvent)
|
||||
if err != nil {
|
||||
return structuredoutput.Response{}, err
|
||||
return call.response, err
|
||||
}
|
||||
result, err := c.runtime.Engine.Run(ctx, call.request)
|
||||
return call.finish(result, err)
|
||||
@@ -212,13 +216,15 @@ func OutputContract(schema responseschema.Key, repairs int) (*pk.OutputContract,
|
||||
|
||||
// classifiedFailure deliberately checks setup defects before broad PromptKit
|
||||
// validation/generation wrappers. Provider text is kept only in the typed cause.
|
||||
func classifiedFailure(parent, local context.Context, cause error, result *pk.RunResult) *structuredoutput.Failure {
|
||||
func classifiedFailure(parent context.Context, cause error, result *pk.RunResult) *structuredoutput.Failure {
|
||||
failure := &structuredoutput.Failure{Class: structuredoutput.FailureFatal, Reason: outcomes.ReasonInternalFailure, Message: "structured model call failed", Cause: cause}
|
||||
if parent.Err() != nil {
|
||||
failure.Class = structuredoutput.FailureCanceled
|
||||
failure.Reason = outcomes.ReasonCanceled
|
||||
failure.Message = "processing canceled"
|
||||
failure.Cause = parent.Err()
|
||||
if !errors.Is(cause, parent.Err()) {
|
||||
failure.Cause = errors.Join(parent.Err(), cause)
|
||||
}
|
||||
return failure
|
||||
}
|
||||
if errors.Is(cause, pk.ErrOperationTimeout) {
|
||||
@@ -232,7 +238,13 @@ func classifiedFailure(parent, local context.Context, cause error, result *pk.Ru
|
||||
failure.Message = "structured model setup failed"
|
||||
return failure
|
||||
}
|
||||
if errors.Is(local.Err(), context.DeadlineExceeded) || errors.Is(cause, context.DeadlineExceeded) {
|
||||
if errors.Is(cause, pk.ErrTransport) {
|
||||
failure.Class = structuredoutput.FailureRecoverable
|
||||
failure.Reason = outcomes.ReasonTransportFailed
|
||||
failure.Message = "model transport failed"
|
||||
return failure
|
||||
}
|
||||
if errors.Is(cause, context.DeadlineExceeded) {
|
||||
failure.Class = structuredoutput.FailureRecoverable
|
||||
failure.Reason = outcomes.ReasonOperationTimeout
|
||||
failure.Message = "model operation timed out"
|
||||
@@ -244,12 +256,6 @@ func classifiedFailure(parent, local context.Context, cause error, result *pk.Ru
|
||||
failure.Message = "model capacity was unavailable"
|
||||
return failure
|
||||
}
|
||||
if errors.Is(cause, pk.ErrTransport) {
|
||||
failure.Class = structuredoutput.FailureRecoverable
|
||||
failure.Reason = outcomes.ReasonTransportFailed
|
||||
failure.Message = "model transport failed"
|
||||
return failure
|
||||
}
|
||||
if errors.Is(cause, pk.ErrMalformedResponse) {
|
||||
failure.Class = structuredoutput.FailureRecoverable
|
||||
failure.Reason = outcomes.ReasonProviderResponseInvalid
|
||||
@@ -265,7 +271,6 @@ func classifiedFailure(parent, local context.Context, cause error, result *pk.Ru
|
||||
}
|
||||
if result != nil && !result.Validation.IsValid {
|
||||
failure.Class = structuredoutput.FailureRecoverable
|
||||
failure.Kind = structuredoutput.FailureMalformedOutput
|
||||
failure.Reason = outcomes.ReasonInvalidOutputExhausted
|
||||
failure.Message = "structured output remained invalid"
|
||||
return failure
|
||||
|
||||
Reference in New Issue
Block a user