Skip to content

Unify ChatMessage and ChatMessageInput into a single message type - #1339

Merged
malibio merged 2 commits into
mainfrom
worktree-issue-1325-unify-chat-message
Jun 5, 2026
Merged

malibio merged 2 commits into
mainfrom
worktree-issue-1325-unify-chat-message

Conversation

@malibio

@malibio malibio commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator

Closes #1325

#1325)

Move ChatMessage, Role, and ToolCallRaw to nlp-engine as the single source of
truth. Remove ChatMessageInput and ToolCallInput from nlp-engine. Delete the
hand-written field-by-field conversion in inference.rs — generate_streaming now
accepts ChatMessage directly. agent_types re-exports the three types from
nlp-engine so all call sites are unchanged. Adding a new message field is now
reflected everywhere by construction; silent field drops are no longer possible.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@malibio

malibio commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review — PR #1339: Unify ChatMessage and ChatMessageInput

Overall assessment: This PR achieves its primary goal cleanly. The structural fix is sound, the hand-written field map is genuinely eliminated, and the compiler now enforces field totality on the critical llama.cpp inference path. One stale docstring, two missing serde annotations, and one pre-existing note for the Ollama path are the only items requiring attention before merge.


Requirements Validation

Acceptance Criterion Status
Single source-of-truth message type PASS — ChatMessage, Role, ToolCallRaw live in nlp-engine::chat::types, re-exported from agent_types
Hand-written field-by-field map removed PASS — 25-line .map() in inference.rs is gone; generate_streaming now accepts Vec<ChatMessage> directly
Adding a field cannot compile without updating both inference and templating paths PASS (with one exception — see below)
Existing ai-chat tool_calls round-trip unchanged PASS — field semantics are identical; ToolCallRaw fields function_name/arguments_json existed on both pre-merge structs
bun run quality:fix Not verified by reviewer — no CI output visible
bun run test:all Not verified by reviewer — no CI output visible

Findings

Improvement

packages/nlp-engine/src/chat/types.rs — tool_call_id and name missing skip_serializing_if

The original ChatMessageInput.call_id had #[serde(skip_serializing_if = "Option::is_none")]. The unified ChatMessage adds the reasoning field with that annotation, but tool_call_id and name are missing it:

pub tool_call_id: Option<String>,
pub name: Option<String>,

These will serialize as "tool_call_id": null and "name": null on non-tool-result turns when the struct is used as JSON (e.g., if it is ever serialized directly to the DB or sent over a wire format). This is inconsistent with reasoning (which has the annotation) and with the old call_id field. Both should carry #[serde(default, skip_serializing_if = "Option::is_none")]. The chat_message_to_oai_value function sidesteps this because it constructs the JSON manually, so there is no immediate inference bug, but the inconsistency is a latent correctness risk.

packages/agent/src/local_agent/ollama_inference.rs — map_role is now redundant with Role::as_str

The map_role private function (lines 307-314) is an exhaustive match over Role that produces the same strings as Role::as_str(). Now that Role::as_str() is public and canonical, map_role is dead weight. This was pre-existing, so it is not a blocker for this PR, but it should be cleaned up in a follow-on (or here, since the file is already in scope of this refactor).

// Current: map_role(&msg.role)  →  "system"/"user"/"assistant"/"tool"
// Could be: msg.role.as_str().to_string()  or  impl Display for Role

Nit

packages/nlp-engine/src/chat/mod.rs line 699 — stale docstring

The chat_message_to_oai_value function still says "Convert one ChatMessageInput" in its doc comment. The function signature now takes &ChatMessage. Update to:

/// Convert one `ChatMessage` into an OpenAI-format message value for the

packages/nlp-engine/src/chat/types.rs — no serde round-trip test for ChatMessage

The constructor unit tests verify field assignment but there is no serde_json::from_str / serde_json::to_string round-trip test. Given that the type is now used in persisted session state, a basic #[test] fn chat_message_serde_round_trip() would be a cheap safety net (especially relevant for the tool_call_id/name annotation gap noted above).


Architecture Assessment

The chosen approach — moving the canonical type down to the lower-level crate (nlp-engine) and re-exporting upward through agent_types — is the correct direction for this layered dependency graph. The alternative (a shared-types crate) would be heavier for a two-crate boundary.

The compiler-enforcement claim holds on the primary path: because generate_streaming now takes Vec<ChatMessage> directly, any new field added to ChatMessage is immediately visible at every construction site in agent_loop.rs without a silent default. The apply_chat_template / chat_message_to_oai_value path is the one place where adding a field to ChatMessage does not force a compiler error — the manual JSON construction in chat_message_to_oai_value would silently ignore a new field. This is an inherent limitation of manual JSON serialization and is documented in the existing test comments. Acceptable for this PR; worth calling out so future contributors know where the enforcement gap is.

The Ollama backend (ollama_inference.rs) still contains a ChatMessage → OllamaMessage mapping that drops tool_calls from outbound history messages. This is a pre-existing issue (unchanged on main, unchanged in this PR) and is outside the scope of this change. It is worth tracking separately because it means the Ollama path has the same class of bug that this PR fixes for the llama.cpp path.


Verdict: Approve with suggestions. The two missing skip_serializing_if annotations and the stale docstring are quick fixes. The map_role redundancy and missing serde round-trip test can reasonably be deferred.

- Add skip_serializing_if to tool_call_id and name on ChatMessage;
  aligns with reasoning field annotation, prevents null serialization
  on non-tool-result turns during session persistence
- Fix stale doc comment: ChatMessageInput → ChatMessage in
  chat_message_to_oai_value
- Delete map_role() in ollama_inference.rs; replace with Role::as_str(),
  which is now the canonical method on the unified type; update test
  to call as_str() directly and scope Role import to test module

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@malibio

malibio commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator Author

Address Review Summary

✅ Addressed (3/3 actionable findings)

🟡 skip_serializing_if on tool_call_id/name — Added #[serde(default, skip_serializing_if = "Option::is_none")] to both fields in ChatMessage. Now consistent with the reasoning field; prevents null serialization on non-tool-result turns during session persistence.

🟢 Redundant map_role — Deleted map_role() from ollama_inference.rs; replaced the single call site with msg.role.as_str().to_string(). Moved Role import into the test module where it's now exclusively needed. Updated test to call Role::as_str() directly.

🟢 Stale doc comment — Fixed chat_message_to_oai_value doc: ChatMessageInput → ChatMessage.

⏭️ Skipped (1 out-of-scope finding)

Ollama path drops tool_calls — Pre-existing gap in ollama_inference.rs; the OllamaMessage struct has no tool_calls field. Out of scope for this PR (which targets the llama.cpp path duplication). Filed as a follow-on.

@malibio
malibio merged commit dfd8401 into main Jun 5, 2026
@malibio
malibio deleted the worktree-issue-1325-unify-chat-message branch June 5, 2026 16:06
malibio added a commit that referenced this pull request Jun 22, 2026
)

* Unify ChatMessage into nlp-engine, eliminating ChatMessageInput (closes #1325)

Move ChatMessage, Role, and ToolCallRaw to nlp-engine as the single source of
truth. Remove ChatMessageInput and ToolCallInput from nlp-engine. Delete the
hand-written field-by-field conversion in inference.rs — generate_streaming now
accepts ChatMessage directly. agent_types re-exports the three types from
nlp-engine so all call sites are unchanged. Adding a new message field is now
reflected everywhere by construction; silent field drops are no longer possible.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

* Address review: serde annotations, stale doc, redundant map_role

- Add skip_serializing_if to tool_call_id and name on ChatMessage;
  aligns with reasoning field annotation, prevents null serialization
  on non-tool-result turns during session persistence
- Fix stale doc comment: ChatMessageInput → ChatMessage in
  chat_message_to_oai_value
- Delete map_role() in ollama_inference.rs; replace with Role::as_str(),
  which is now the canonical method on the unified type; update test
  to call as_str() directly and scope Role import to test module

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

---------

Co-authored-by: Michael Libio <[email protected]>
Co-authored-by: Claude Sonnet 4.6 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unify ChatMessage and ChatMessageInput into a single message type

1 participant