Repository navigation
feat: Decode Anthropic Messages replies to pivot events - #1970
Conversation
…ub (rossoctl#1965) Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com> Signed-off-by: Hai Huang <huang195@gmail.com>
…t details The estimate for T2-T6 is more than 2,000 counted lines. P2 now has the reply decoder (T3). P3 has the encoder, the goldens, the resend tests and the docs, with parent P2. The encoder must not merge before the reply decoder, because translate.Target selects a protocol that has only a request encoder. The reply goldens use goldenName. The listener test builds its own request, because postCodex sets no query and no Authorization header. Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com> Signed-off-by: Hai Huang <huang195@gmail.com>
Add NewReplyDecoder to the anthropic-messages protocol (rules S13-S15 of rossoctl#1965). The decoder reads a streamed or a not-streamed reply and gives pivot events: - The stream gives start, the kept blocks, usage, then stop. The usage comes before stop, because each reply encoder ends at stop. - A server-tool block and its deltas give no event and use no pivot index. The raw capture keeps them. - A thinking block with no text and a signature goes to the agent. - A stream with no message_stop ends with a 502 error. - A stream error event gets its status from its type. - A non-2xx body that is not Anthropic's error shape gives api_error with its first 200 bytes, cut at a rune start. No route changes: the router picks a target only when the target has a request encoder, and this protocol has none yet. Assisted-By: Claude (Anthropic AI) <noreply@anthropic.com> Signed-off-by: Hai Huang <huang195@gmail.com>
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 15 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
clawgenti
left a comment
There was a problem hiding this comment.
Summary
The reply decoder follows S13-S15 and plan decisions 5-13. I ran it on Anthropic-shaped inputs that are not in the fixtures, and each one decoded correctly. The inputs covered the current message_start usage (cache_creation, service_tier, server_tool_use: null, container: null), interleaved thinking with thinking_delta and signature_delta, a streamed server_tool_use with input_json_delta followed by web_search_tool_result (both skipped with no index gap), citations_delta on a text block (skipped), a tool_use with an empty partial_json (the Responses encoder fills {}), message_delta with context_management and null stop_reason or usage, CRLF line ends, data: with no space, a trailing [DONE], and an error event with details: null and request_id. I also ran the fixtures end to end through translate.Reply("responses", "anthropic-messages", ...), and Codex-shaped output came out right. That output covered function-call argument deltas, the cortex1: reasoning item that carries only a signature, a skipped server-tool block, refusal to incomplete/content_filter, and the stream error to 529. go test ./translate/..., go test -race ./translate/anthropic/, go vet and gofmt are clean. No route uses the decoder yet: Target still requires a RequestEncoder. My two comments below are small and do not block merge.
I agree with the open findings in the PR body. Two of them become live in P3, so it would be good to fix them there: the stop_reason pass-through (model_context_window_exceeded reaching Codex as completed), and the typed wireBlock fields that are decoded before a server-tool block is skipped.
Author: huang195 (MEMBER — maintainer)
Areas reviewed: Go (translate/anthropic reply decoder, tests, fixtures), Docs (plan)
Agent/IDE config (.claude/.vscode): none
Commits: 3 commits, all signed-off: yes
CI status: passing
| d.failEvent(m.Error) | ||
| return | ||
| } | ||
| d.emit(pivot.Event{Kind: pivot.EventStart, ID: m.ID, Model: m.Model}) |
There was a problem hiding this comment.
suggestion: whole treats any 2xx JSON value that is not an error as a complete reply. A body of {} or null (for example from a proxy or a misrouted endpoint) gives start, usage{0}, stop end_turn, so the agent sees an empty but successful turn. The stream path refuses this case (decision 8, msgEndedEarly), but the not-streamed path has no matching guard. Consider requiring m.Type == "message" and otherwise failing with 502 api_error (for example "the inference server sent a reply that is not an Anthropic message"). Probe: decodeAll(200, false, "{}") and decodeAll(200, false, "null") both give [start, usage, stop end_turn].
| var errorStatus = map[string]int{ | ||
| "invalid_request_error": 400, "authentication_error": 401, "permission_error": 403, | ||
| "not_found_error": 404, "request_too_large": 413, "rate_limit_error": 429, | ||
| "overloaded_error": 529, |
There was a problem hiding this comment.
nit: Anthropic's error list also has billing_error (402) and timeout_error (504). Today a stream error event with either type gets status 500. Adding them to the map would keep the status faithful. If you want the map to stay equal to decision 9, it could instead go in the plan's open items for P3.
What changed
This PR adds
NewReplyDecoderto theanthropic-messagesprotocol (rules S13-S15 of #1965). The decoder reads a streamed or a not-streamed Anthropic reply and gives pivot events.message_stopends with a 502 error.errorevent gets its status from its type.api_errorwith its first 200 bytes. The cut is at a rune start.No route changes. The router picks a target only when the target has a request encoder, and this protocol has none yet. P3 adds it.
How it was tested
cd core && GOWORK=off go test ./translate/anthropic/passes.core/translate/testdata/responses-anthropic/reply/. Each.ssefixture is also fed with a split at every byte boundary, and one byte at a time..jsonfixture gives the same events as its.ssetwin, except for the split of the deltas.Size
Review findings that are not fixed
These findings are minor. No route uses this decoder in this PR, so none of them can change a live reply before P3.
decode_reply.go:172-178(failEvent) and lines 289-292: a streamerrorevent, or a 2xx not-streamed"type":"error"body, with an emptyerror.typegivesEventError{Status: 500, ErrorType: ""}. The agent-side encoder then sends"type":"". The Chat decoder checks the type against a known set. Suggestion: useapi_errorwhen the type is empty. No test covers this case.decode_reply.go:281-287:stop_reasonis passed on with no check. Anthropic also sendsstop_sequence,pause_turnandmodel_context_window_exceeded.pivot.Event.StopReasondocuments onlyend_turn,max_tokens,tool_useandrefusal.responses/reply.goterminalmaps each unknown reason toresponse.completed. Thuspause_turn(an incomplete server-tool turn) andmodel_context_window_exceeded(a cut-off reply) get to Codex as a complete reply. The plan does not name these values. A possible map:model_context_window_exceededtomax_tokens.decode_reply.go:286and lines 298-321: a stream withmessage_stopbut nomessage_start, or a kept block with nocontent_block_stopbeforemessage_stop, gives usage and stop with noEventStartor noEventBlockStop. The reply encoders expect a balanced event list. A real Anthropic server does not send this, so the risk is low. No test covers it.decode_reply.go:314-316: in a not-streamed body, atool_useblock with noinputmember gives noDeltaInputJSON. A block with"input":nullgives the deltanull. Anthropic always sends an object, so this is only hardening. Decision 16 fills{}on the encode side, but the decode side has no matching rule._StreamErrorStatus,_StartTextAndUsage,_BadJSON) stay inside the decisions of T3.decode_reply.go:43and line 251:wireBlockreadstext,thinking,signature,data,idandnamefor each block beforeopenBlockskips a server-tool block (S13). A wrong JSON type in any typed field (id,model,text,index,stop_reason, or a usage token count such as2.0) fails the whole event or body with a 502. Blocks that the decoder skips also cause this. A probe sentcontent_block_start {"type":"web_search_tool_result","data":5}, and the whole stream failed. Suggestion: decode the block asRawMessageand readtypefirst, or decode only the fields of the four kinds that the decoder keeps. This becomes live in P3.decode_reply.go:252and line 301: a JSON type mismatch gets the message "not valid JSON", but the JSON is valid. Probe values that ended the reply with this message: usageoutput_tokens12.5or"12",stop_reason3,index"0",text5,tool_useid7,error.message5, and"error":"boom". Suggestion: say that Cortex cannot read the event, or add the error text, so that an operator can find the field.decode_reply.go:344(httpError): a non-2xx body without Anthropic's error shape always getsapi_error.chat/reply.gousespivot.ErrorType(d.status)for this case, and the T3 interfaces listpivot.ErrorTypeas consumed, but this code does not call it. With it, an HTML 429 from a proxy givesrate_limit_errorand a 401 givesauthentication_error. To make 529 giveoverloaded_error, map it througherrorStatustoo. Also, an Anthropic-shaped body whoseerror.messageis a number falls back toapi_errorand the raw body, so the decoder losesrate_limit_error.decode_reply.go:77: anerrorevent with a stringerror("error":"overloaded"), or with amessagethat is not a string, gives 502 "not valid JSON", and the server's status and text are lost. A 2xx body{"type":"error","error":{"message":5}}fails the same way. Suggestion: fall back toapi_errorwith the raw text, ashttpErrordoes for non-2xx bodies.For a human after review
These steps need a real Anthropic API key and a live Codex session. They need P2 and P3 (all of T2-T6) merged or checked out and installed. Do not run them in this workflow.
api: {anthropic-messages: /v1/messages}forhttps://api.anthropic.com, and route Codex to it (agentop server use <name> --agent codex).cache_read_input_tokensis above 0 from turn 2 (S12). If it stays at 0, report it in the PR.Part of #1965
Assisted-By: Claude (Anthropic AI) noreply@anthropic.com