Skip to main content

sim_codec_chat/providers/openai/
runtime.rs

1use std::sync::Arc;
2
3use sim_codec::{Decoder, DomainCodecLib, Encoder, Input, Output, ReadCx};
4use sim_kernel::{CodecId, Expr, Lib, LibManifest, Linker, LoadCx, Result, Symbol, WriteCx};
5
6use super::{
7    decode::decode_openai_request_for_codec, encode::encode_openai_response_for_codec,
8    openai_codec_symbol,
9};
10
11/// Runtime codec for OpenAI-compatible chat-completion JSON.
12pub struct OpenAiCodec;
13
14impl Decoder for OpenAiCodec {
15    fn decode(&self, cx: &mut ReadCx<'_>, input: Input) -> Result<Expr> {
16        decode_openai_request_for_codec(cx.codec, input)
17    }
18}
19
20impl Encoder for OpenAiCodec {
21    fn encode(&self, cx: &mut WriteCx<'_>, expr: &Expr) -> Result<Output> {
22        encode_openai_response_for_codec(cx.codec, expr).map(Output::Text)
23    }
24}
25
26/// Host-registered lib for `codec:openai`.
27pub struct OpenAiCodecLib {
28    symbol: Symbol,
29    codec_id: CodecId,
30}
31
32impl OpenAiCodecLib {
33    /// Creates the lib bound to the given runtime-assigned codec id.
34    pub fn new(id: CodecId) -> Self {
35        Self {
36            symbol: openai_codec_symbol(),
37            codec_id: id,
38        }
39    }
40
41    fn domain_lib(&self) -> DomainCodecLib {
42        DomainCodecLib::new(
43            self.symbol.clone(),
44            self.codec_id,
45            Arc::new(OpenAiCodec),
46            Arc::new(OpenAiCodec),
47            Symbol::qualified("codec", "OpenAiTranscript"),
48        )
49    }
50}
51
52impl Lib for OpenAiCodecLib {
53    fn manifest(&self) -> LibManifest {
54        self.domain_lib().manifest()
55    }
56
57    fn load(&self, cx: &mut LoadCx, linker: &mut Linker<'_>) -> Result<()> {
58        self.domain_lib().load(cx, linker)
59    }
60}