interplane.Get Omega
Read in your language

interplane-mv

INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.

Brought by drakestapleton

branch main Branches Tags History

interplane-mv / rust / crates / interplane-lenshift / src / openai_stream.rs

230 lines · 8684 bytes Raw Blame History
1//! Dialect `openai_stream` (version 1): a streamed OpenAI-compatible response body (SSE text).
2//! The fragments are assembled into one assistant message, which is parsed with the `openai`
3//! rules. A stream that did not finish cleanly is rejected call by call, never guessed.
4use std::collections::BTreeMap;
5
6use interplane_core::{digest, ErrorCode, ToolRequest, ToolResult};
7use serde_json::{Map, Value};
8
9use crate::openai::OpenAi;
10use crate::*;
11
12pub struct OpenAiStream;
13
14const NAME: &str = "openai_stream";
15const COMPLETE: [&str; 3] = ["stop", "tool_calls", "function_call"];
16
17/// The data of each complete SSE event, in order.
18pub fn events(body: &str) -> Vec<String> {
19 let (mut out, mut data) = (Vec::new(), Vec::<&str>::new());
20 for line in body.split('\n') {
21 let line = line.strip_suffix('\r').unwrap_or(line);
22 if line.is_empty() {
23 if !data.is_empty() {
24 out.push(data.join("\n"));
25 }
26 data.clear();
27 } else if line == "data" {
28 data.push("");
29 } else if let Some(v) = line.strip_prefix("data:") {
30 data.push(v.strip_prefix(' ').unwrap_or(v));
31 }
32 }
33 out
34}
35
36#[derive(Default)]
37struct Slot {
38 id: Option<String>,
39 name: Option<String>,
40 arguments: Option<String>,
41}
42
43fn keep_first(slot: &mut Option<String>, value: Option<&Value>, what: &str) -> Result<(), String> {
44 let Some(v) = value.and_then(Value::as_str).filter(|s| !s.is_empty()) else {
45 return Ok(());
46 };
47 match slot {
48 None => *slot = Some(v.to_string()),
49 Some(old) if old != v => return Err(format!("conflicting tool call {what}")),
50 Some(_) => {}
51 }
52 Ok(())
53}
54
55/// `(message, finish_reason)` for a stream body, or the stream error.
56pub fn assemble(body: &str) -> Result<(Value, Option<String>), String> {
57 let (mut text, mut reasoning) = (String::new(), String::new());
58 let mut any_reasoning = false;
59 let mut calls: BTreeMap<u64, Slot> = BTreeMap::new();
60 let mut finish: Option<String> = None;
61 let mut done = false;
62 for data in events(body) {
63 if done {
64 return Err("event after [DONE]".into());
65 }
66 if data == "[DONE]" {
67 done = true;
68 continue;
69 }
70 let chunk = match serde_json::from_str::<Value>(&data) {
71 Ok(Value::Object(m)) => m,
72 _ => return Err("stream chunk is not a JSON object".into()),
73 };
74 let Some(choices) = chunk.get("choices").and_then(Value::as_array) else {
75 continue;
76 };
77 for choice in choices {
78 let Some(choice) = choice.as_object() else {
79 return Err("stream choice is not an object".into());
80 };
81 if choice.get("index").is_some_and(|i| i.as_u64() != Some(0)) {
82 return Err("multiple choices are not supported".into());
83 }
84 if let Some(delta) = choice.get("delta").and_then(Value::as_object) {
85 if let Some(s) = delta.get("content").and_then(Value::as_str) {
86 text.push_str(s);
87 }
88 for key in ["reasoning_content", "reasoning"] {
89 if let Some(s) = delta.get(key).and_then(Value::as_str) {
90 reasoning.push_str(s);
91 any_reasoning = true;
92 }
93 }
94 for frag in delta
95 .get("tool_calls")
96 .and_then(Value::as_array)
97 .into_iter()
98 .flatten()
99 {
100 let Some(index) = frag.get("index").and_then(Value::as_u64) else {
101 return Err("tool call fragment has no index".into());
102 };
103 let slot = calls.entry(index).or_default();
104 keep_first(&mut slot.id, frag.get("id"), "id")?;
105 if let Some(function) = frag.get("function").and_then(Value::as_object) {
106 keep_first(&mut slot.name, function.get("name"), "name")?;
107 if let Some(s) = function.get("arguments").and_then(Value::as_str) {
108 slot.arguments.get_or_insert_with(String::new).push_str(s);
109 }
110 }
111 }
112 }
113 match choice.get("finish_reason") {
114 None | Some(Value::Null) => {}
115 Some(Value::String(r)) => match &finish {
116 None => finish = Some(r.clone()),
117 Some(f) if f != r => return Err("conflicting finish_reason".into()),
118 Some(_) => {}
119 },
120 Some(_) => return Err("finish_reason is not a string".into()),
121 }
122 }
123 }
124 let mut message = Map::new();
125 message.insert("role".into(), "assistant".into());
126 message.insert("content".into(), text.into());
127 if any_reasoning {
128 message.insert("reasoning_content".into(), reasoning.into());
129 }
130 if !calls.is_empty() {
131 let out: Vec<Value> = calls
132 .into_values()
133 .map(|s| {
134 let mut function = Map::new();
135 if let Some(n) = s.name {
136 function.insert("name".into(), n.into());
137 }
138 if let Some(a) = s.arguments {
139 function.insert("arguments".into(), a.into());
140 }
141 let mut call = Map::new();
142 call.insert("type".into(), "function".into());
143 call.insert("function".into(), function.into());
144 if let Some(id) = s.id {
145 call.insert("id".into(), id.into());
146 }
147 Value::Object(call)
148 })
149 .collect();
150 message.insert("tool_calls".into(), out.into());
151 }
152 Ok((Value::Object(message), finish))
153}
154
155impl Dialect for OpenAiStream {
156 fn name(&self) -> &str {
157 NAME
158 }
159 fn version(&self) -> &str {
160 "1"
161 }
162
163 fn parse(&self, input: &Value, ctx: &ParseContext) -> LenshiftTurn {
164 let assembled = match input.as_str() {
165 Some(body) => assemble(body),
166 None => Err("stream is not text".into()),
167 };
168 let (message, finish) = match assembled {
169 Ok(v) => v,
170 Err(e) => {
171 let source_digest = match input.as_str() {
172 Some(body) => text_digest(body),
173 None => digest(input),
174 };
175 return LenshiftTurn {
176 dialect: NAME.into(),
177 dialect_version: "1".into(),
178 parser_version: PARSER_VERSION.into(),
179 model: ctx.model.clone(),
180 text: String::new(),
181 reasoning_digest: None,
182 intents: vec![],
183 rejected: vec![RejectedCall {
184 index: 0,
185 code: ErrorCode::MalformedToolCall,
186 message: e,
187 source_digest: Some(source_digest),
188 request_id: assign_request_id(None, ctx, 0),
189 }],
190 partial: false,
191 intent_indices: vec![],
192 };
193 }
194 };
195 let mut turn = OpenAi.parse(&message, ctx);
196 turn.dialect = NAME.into();
197 for intent in &mut turn.intents {
198 intent.provenance.dialect = NAME.into();
199 }
200 if finish.as_deref().is_some_and(|f| COMPLETE.contains(&f)) {
201 return turn;
202 }
203 let intents = std::mem::take(&mut turn.intents);
204 let indices = std::mem::take(&mut turn.intent_indices);
205 let mut cut: Vec<RejectedCall> = indices
206 .into_iter()
207 .zip(intents)
208 .map(|(index, i)| RejectedCall {
209 index,
210 code: ErrorCode::MalformedToolCall,
211 message: String::new(),
212 source_digest: i.provenance.source_digest,
213 request_id: i.request_id,
214 })
215 .chain(std::mem::take(&mut turn.rejected))
216 .collect();
217 cut.sort_by_key(|r| r.index);
218 for r in &mut cut {
219 r.code = ErrorCode::MalformedToolCall;
220 r.message = "truncated tool call".into();
221 }
222 turn.partial = !cut.is_empty();
223 turn.rejected = cut;
224 turn
225 }
226
227 fn render_result(&self, result: &ToolResult, intent: Option<&ToolRequest>) -> Value {
228 OpenAi.render_result(result, intent)
229 }
230}