Skip to main content

sim_codec_chat/providers/anthropic/
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    anthropic_codec_symbol, decode::decode_anthropic_request_for_codec,
8    encode::encode_anthropic_response_for_codec,
9};
10
11/// Runtime codec for Anthropic Messages JSON.
12pub struct AnthropicCodec;
13
14impl Decoder for AnthropicCodec {
15    fn decode(&self, cx: &mut ReadCx<'_>, input: Input) -> Result<Expr> {
16        decode_anthropic_request_for_codec(cx.codec, input)
17    }
18}
19
20impl Encoder for AnthropicCodec {
21    fn encode(&self, cx: &mut WriteCx<'_>, expr: &Expr) -> Result<Output> {
22        encode_anthropic_response_for_codec(cx.codec, expr).map(Output::Text)
23    }
24}
25
26/// Host-registered lib for `codec:anthropic`.
27pub struct AnthropicCodecLib {
28    symbol: Symbol,
29    codec_id: CodecId,
30}
31
32impl AnthropicCodecLib {
33    /// Creates the lib bound to the given runtime-assigned codec id.
34    pub fn new(id: CodecId) -> Self {
35        Self {
36            symbol: anthropic_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(AnthropicCodec),
46            Arc::new(AnthropicCodec),
47            Symbol::qualified("codec", "AnthropicTranscript"),
48        )
49    }
50}
51
52impl Lib for AnthropicCodecLib {
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}