Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/interplane-mv/blob/main/rust/crates/interplane-lenshift/src/openai.rs # interplane-mv INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `interplane-mv / rust / crates / interplane-lenshift / src / openai.rs` 240 lines ยท 8448 bytes Raw Blame History 1 //! Dialect `openai` (version 1): OpenAI-compatible assistant messages. 2 use interplane_core::{digest, ErrorCode, ToolRequest, ToolResult}; 3 use serde_json::{json, Value}; 4 5 use crate::*; 6 7 pub struct OpenAi; 8 9 impl Dialect for OpenAi { 10 fn name(&self) -> &str { 11 "openai" 12 } 13 fn version(&self) -> &str { 14 "1" 15 } 16 17 fn parse(&self, input: &Value, ctx: &ParseContext) -> LenshiftTurn { 18 let mut turn = LenshiftTurn { 19 dialect: "openai".into(), 20 dialect_version: "1".into(), 21 parser_version: PARSER_VERSION.into(), 22 model: ctx.model.clone(), 23 text: String::new(), 24 reasoning_digest: None, 25 intents: vec![], 26 rejected: vec![], 27 partial: false, 28 intent_indices: vec![], 29 }; 30 let Some(msg) = input.as_object() else { 31 turn.rejected.push(RejectedCall { 32 index: 0, 33 code: ErrorCode::MalformedToolCall, 34 message: "assistant message is not an object".into(), 35 source_digest: Some(digest(input)), 36 request_id: assign_request_id(None, ctx, 0), 37 }); 38 return turn; 39 }; 40 if let Some(s) = msg.get("content").and_then(Value::as_str) { 41 turn.text = s.to_string(); 42 } 43 turn.reasoning_digest = ["reasoning_content", "reasoning"] 44 .iter() 45 .filter_map(|k| msg.get(*k).and_then(Value::as_str)) 46 .find(|s| !s.is_empty()) 47 .map(text_digest); 48 49 let calls: Vec<&Value> = match msg.get("tool_calls").and_then(Value::as_array) { 50 Some(a) if !a.is_empty() => a.iter().collect(), 51 _ => msg 52 .get("function_call") 53 .filter(|v| v.is_object()) 54 .into_iter() 55 .collect(), 56 }; 57 let legacy = msg 58 .get("tool_calls") 59 .and_then(Value::as_array) 60 .is_none_or(|a| a.is_empty()); 61 for (index, call) in calls.into_iter().enumerate() { 62 let src_digest = digest(call); 63 let (id, func): (Option<&str>, Option<&Value>) = if legacy { 64 (None, Some(call)) 65 } else { 66 (call.get("id").and_then(Value::as_str), call.get("function")) 67 }; 68 let request_id = assign_request_id(id, ctx, index); 69 let reject = |turn: &mut LenshiftTurn, msg: &str| { 70 turn.rejected.push(RejectedCall { 71 index, 72 code: ErrorCode::MalformedToolCall, 73 message: msg.into(), 74 source_digest: Some(src_digest.clone()), 75 request_id: request_id.clone(), 76 }); 77 }; 78 let name = func 79 .and_then(|f| f.get("name")) 80 .and_then(Value::as_str) 81 .unwrap_or(""); 82 if name.is_empty() { 83 reject(&mut turn, "missing tool name"); 84 continue; 85 } 86 let Some(tool) = canonical_tool(name) else { 87 reject(&mut turn, "invalid tool name"); 88 continue; 89 }; 90 let args = match func.and_then(|f| f.get("arguments")) { 91 Some(Value::String(s)) => match serde_json::from_str::(s) { 92 Ok(Value::Object(m)) => m, 93 Ok(_) => { 94 reject(&mut turn, "arguments is not an object"); 95 continue; 96 } 97 Err(_) => { 98 reject(&mut turn, "arguments is not valid JSON"); 99 continue; 100 } 101 }, 102 // `arguments` must be a JSON string (spec/LENSHIFT.md). An already-decoded object is 103 // what Ollama's own /api/chat sends, not an OpenAI-compatible endpoint. 104 _ => { 105 reject(&mut turn, "arguments is not valid JSON"); 106 continue; 107 } 108 }; 109 turn.intents.push(make_intent( 110 "openai", 111 "1", 112 ctx, 113 request_id, 114 tool, 115 args, 116 id.map(str::to_string), 117 src_digest.clone(), 118 name, 119 "none", 120 )); 121 turn.intent_indices.push(index); 122 } 123 turn 124 } 125 126 fn render_result(&self, result: &ToolResult, intent: Option<&ToolRequest>) -> Value { 127 let id = intent 128 .and_then(|i| i.provenance.source_call_id.clone()) 129 .or_else(|| result.request_id.clone()) 130 .unwrap_or_default(); 131 json!({"role": "tool", "tool_call_id": id, "content": serialize_result(result)}) 132 } 133 } 134 135 #[cfg(test)] 136 mod tests { 137 use super::*; 138 use interplane_core::ResultStatus; 139 140 fn ctx() -> ParseContext { 141 ParseContext { 142 trace_id: "tr".into(), 143 turn: 2, 144 model: "m".into(), 145 } 146 } 147 fn call(id: Option<&str>, name: &str, args: Value) -> Value { 148 let mut c = json!({"type": "function", "function": {"name": name, "arguments": args}}); 149 if let Some(i) = id { 150 c["id"] = json!(i); 151 } 152 c 153 } 154 155 #[test] 156 fn single_call_with_digest_of_canonical_call() { 157 let c = call( 158 Some("call_1"), 159 "filesystem.read", 160 json!("{\"path\": \"/a\"}"), 161 ); 162 let t = OpenAi.parse( 163 &json!({"role": "assistant", "content": null, "tool_calls": [c.clone()]}), 164 &ctx(), 165 ); 166 assert_eq!(t.intents.len(), 1); 167 let i = &t.intents[0]; 168 assert_eq!(i.request_id, "call_1"); 169 assert_eq!(i.tool.namespace.as_deref(), Some("filesystem")); 170 assert_eq!(i.arguments["path"], json!("/a")); 171 assert_eq!( 172 i.provenance.source_digest.as_deref(), 173 Some(digest(&c).as_str()) 174 ); 175 assert_eq!(i.provenance.coercion.as_deref(), Some("none")); 176 assert_eq!(t.text, ""); 177 } 178 #[test] 179 fn malformed_arguments_and_missing_name() { 180 let msg = json!({"content": "hi", "tool_calls": [ 181 call(Some("a"), "x", json!("not json")), 182 call(Some("b"), "x", json!("[1]")), 183 call(Some("c"), "", json!("{}")), 184 call(None, "ok", json!("{}")), 185 ]}); 186 let t = OpenAi.parse(&msg, &ctx()); 187 let m: Vec<&str> = t.rejected.iter().map(|r| r.message.as_str()).collect(); 188 assert_eq!( 189 m, 190 [ 191 "arguments is not valid JSON", 192 "arguments is not an object", 193 "missing tool name" 194 ] 195 ); 196 assert_eq!(t.intents[0].request_id, "tr:t2:c3"); 197 assert_eq!(t.intent_indices, vec![3]); 198 assert_eq!(t.text, "hi"); 199 } 200 #[test] 201 fn reasoning_and_legacy_function_call() { 202 let t = OpenAi.parse( 203 &json!({"content": "x", "reasoning_content": "thought", "function_call": {"name": "f", "arguments": "{}"}}), 204 &ctx(), 205 ); 206 assert_eq!(t.reasoning_digest, Some(text_digest("thought"))); 207 assert_eq!(t.intents.len(), 1); 208 assert_eq!(t.intents[0].provenance.source_call_id, None); 209 assert_eq!(t.intents[0].request_id, "tr:t2:c0"); 210 } 211 #[test] 212 fn plain_answer_and_garbage_input() { 213 let t = OpenAi.parse(&json!({"content": "just text"}), &ctx()); 214 assert!(t.intents.is_empty() && t.rejected.is_empty() && !t.partial); 215 let t = OpenAi.parse(&json!("nope"), &ctx()); 216 assert_eq!(t.rejected.len(), 1); 217 } 218 #[test] 219 fn render_ok_and_error() { 220 let r = ToolResult::ok("r1", json!({"b": 1, "a": 2})); 221 let v = OpenAi.render_result(&r, None); 222 assert_eq!( 223 v, 224 json!({"role": "tool", "tool_call_id": "r1", "content": "{\"a\":2,\"b\":1}"}) 225 ); 226 let e = ToolResult::failed( 227 Some("r1"), 228 ResultStatus::Denied, 229 ErrorCode::PolicyDenied, 230 "no", 231 ); 232 let v = OpenAi.render_result(&e, None); 233 assert_eq!( 234 v["content"], 235 json!( 236 "{\"error\":{\"code\":\"policy_denied\",\"message\":\"no\"},\"status\":\"denied\"}" 237 ) 238 ); 239 } 240 }