forge
Explore
Log in

Don't you dare go Hollow

hezarfen_backend

Clone
★ 0

0 watching0 forksRust8.3 MiB6d68754Ahmet Kaan Gümüş2 months ago566 commits

chat.rs194 lines, 7.4 KiBHistoryRawDownload
1//! Payload contract for the `chat.reply` capability.
2//!
3//! The transport is untouched: this is JSON that rides inside the existing
4//! [`Request::payload`](crate::ai::protocol::Request::payload) and comes back
5//! inside [`Response::Ok`](crate::ai::protocol::Response::Ok)`::payload`. One
6//! request, one answer — the exchange stays unary, so a service answers with
7//! the whole reply text rather than streaming tokens.
8//!
9//! The service is stateless about conversations. The backend owns the thread
10//! and re-sends the relevant tail of it on every turn, which means a service
11//! may restart, scale out, or be replaced mid-conversation without losing
12//! context.
13
14use serde::{Deserialize, Serialize};
15
16/// The capability string routed to a chat service. Defined once, in
17/// [`crate::constant`]; re-exported here so a reader of the payload contract
18/// finds it next to the payloads.
19pub use crate::constant::AI_CHAT_CAPABILITY;
20
21/// Who said a turn. Serialises to `"user"` / `"assistant"` — the two names
22/// every chat model API already uses, so a service can hand the history to its
23/// model with no remapping.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26pub enum ChatRole {
27 User,
28 Assistant,
29}
30
31/// One previous message in the conversation.
32#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
33pub struct ChatTurn {
34 pub role: ChatRole,
35 pub content: String,
36}
37
38/// What the backend asks a chat service to answer.
39#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
40pub struct ChatRequestPayload {
41 /// The user's new message. `history` does *not* contain it.
42 pub message: String,
43 /// The **school role** of the person asking — `"parent"`, `"student"`,
44 /// `"teacher"`, `"manager"` or `"admin"`, the same lowercase strings the
45 /// rest of the API uses ([`Role::as_str`](crate::domain::role::Role::as_str)).
46 /// Deliberately not `role`: that name belongs to [`ChatTurn`], where it says
47 /// who *said* a turn.
48 ///
49 /// Read live from the authenticated session on every request and never
50 /// taken from the request body, so a service may answer on it: a student
51 /// must not be handed an answer scoped for a manager. Scoping the answer is
52 /// the service's job — the backend only forwards the role.
53 pub asker_role: String,
54 /// The last N turns of the conversation, **oldest first** — index 0 is the
55 /// furthest back, the final element is the turn immediately before
56 /// `message`. Same order a model's `messages` array expects, so a service
57 /// appends `message` and sends it straight on.
58 ///
59 /// Absent or `[]` means a fresh conversation; a minimal service (or a
60 /// first turn) can omit the key entirely.
61 #[serde(default)]
62 pub history: Vec<ChatTurn>,
63}
64
65/// The service's answer, inside `Response::Ok { payload }`.
66///
67/// Handled failures do *not* come back here — they use the existing
68/// [`Response::Err`](crate::ai::protocol::Response::Err) `{ code, message }`,
69/// so there is exactly one failure shape on the bridge for every capability.
70#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
71pub struct ChatReplyPayload {
72 /// The complete reply text. Not chunked, not partial.
73 pub text: String,
74}
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79 use crate::domain::role::Role;
80 use serde_json::json;
81
82 #[test]
83 fn payloads_round_trip() {
84 let request = ChatRequestPayload {
85 message: "and the second?".into(),
86 asker_role: Role::Student.as_str().to_string(),
87 history: vec![
88 ChatTurn {
89 role: ChatRole::User,
90 content: "what is the first law?".into(),
91 },
92 ChatTurn {
93 role: ChatRole::Assistant,
94 content: "inertia".into(),
95 },
96 ],
97 };
98 let encoded = serde_json::to_value(&request).unwrap();
99 assert_eq!(
100 serde_json::from_value::<ChatRequestPayload>(encoded).unwrap(),
101 request
102 );
103
104 let reply = ChatReplyPayload {
105 text: "F = ma".into(),
106 };
107 let encoded = serde_json::to_value(&reply).unwrap();
108 assert_eq!(
109 serde_json::from_value::<ChatReplyPayload>(encoded).unwrap(),
110 reply
111 );
112 }
113
114 #[test]
115 fn chat_payload_keys_are_the_documented_wire_names() {
116 // Services in other languages match on these literals — a rename here
117 // silently breaks every one of them, so pin the encoding.
118 let request = serde_json::to_value(ChatRequestPayload {
119 message: "hi".into(),
120 asker_role: Role::Teacher.as_str().to_string(),
121 history: vec![
122 ChatTurn {
123 role: ChatRole::User,
124 content: "a".into(),
125 },
126 ChatTurn {
127 role: ChatRole::Assistant,
128 content: "b".into(),
129 },
130 ],
131 })
132 .unwrap();
133 assert_eq!(
134 request,
135 json!({
136 "message": "hi",
137 "asker_role": "teacher",
138 "history": [
139 { "role": "user", "content": "a" },
140 { "role": "assistant", "content": "b" },
141 ],
142 })
143 );
144 // Every role reaches the wire as its documented lowercase slug — the
145 // one `Role::as_str` already publishes, not a second spelling.
146 for role in crate::domain::role::ROLES {
147 let encoded = serde_json::to_value(ChatRequestPayload {
148 message: "hi".into(),
149 asker_role: role.as_str().to_string(),
150 history: Vec::new(),
151 })
152 .unwrap();
153 assert_eq!(encoded["asker_role"], role.as_str());
154 }
155 assert_eq!(
156 serde_json::to_value(ChatReplyPayload { text: "ok".into() }).unwrap(),
157 json!({ "text": "ok" })
158 );
159 assert_eq!(AI_CHAT_CAPABILITY, "chat.reply");
160 }
161
162 #[test]
163 fn history_is_optional_on_the_wire() {
164 // The smallest legal request: a first turn, from a service author who
165 // never sends an empty array.
166 let bare: ChatRequestPayload =
167 serde_json::from_value(json!({ "message": "hi", "asker_role": "student" })).unwrap();
168 assert!(bare.history.is_empty());
169 let empty: ChatRequestPayload = serde_json::from_value(
170 json!({ "message": "hi", "asker_role": "student", "history": [] }),
171 )
172 .unwrap();
173 assert_eq!(bare, empty);
174 }
175
176 #[test]
177 fn history_keeps_its_oldest_first_order() {
178 // Round-tripping must not reorder: a service reading index 0 as the
179 // oldest turn depends on it.
180 let raw = json!({
181 "message": "third",
182 "asker_role": "student",
183 "history": [
184 { "role": "user", "content": "first" },
185 { "role": "assistant", "content": "second" },
186 ],
187 });
188 let payload: ChatRequestPayload = serde_json::from_value(raw).unwrap();
189 assert_eq!(payload.history[0].content, "first");
190 assert_eq!(payload.history[0].role, ChatRole::User);
191 assert_eq!(payload.history[1].content, "second");
192 assert_eq!(payload.history[1].role, ChatRole::Assistant);
193 }
194}