File size: 8,816 Bytes
854994d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
use crate::endpoint::realtime_websocket::methods_common::REALTIME_AUDIO_SAMPLE_RATE;
use crate::endpoint::realtime_websocket::protocol::AudioFormatType;
use crate::endpoint::realtime_websocket::protocol::ConversationContentType;
use crate::endpoint::realtime_websocket::protocol::ConversationFunctionCallOutputItem;
use crate::endpoint::realtime_websocket::protocol::ConversationItemContent;
use crate::endpoint::realtime_websocket::protocol::ConversationItemPayload;
use crate::endpoint::realtime_websocket::protocol::ConversationItemType;
use crate::endpoint::realtime_websocket::protocol::ConversationMessageItem;
use crate::endpoint::realtime_websocket::protocol::NoiseReductionType;
use crate::endpoint::realtime_websocket::protocol::RealtimeOutboundMessage;
use crate::endpoint::realtime_websocket::protocol::RealtimeOutputModality;
use crate::endpoint::realtime_websocket::protocol::RealtimeSessionMode;
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use crate::endpoint::realtime_websocket::protocol::SessionAudio;
use crate::endpoint::realtime_websocket::protocol::SessionAudioFormat;
use crate::endpoint::realtime_websocket::protocol::SessionAudioInput;
use crate::endpoint::realtime_websocket::protocol::SessionAudioOutput;
use crate::endpoint::realtime_websocket::protocol::SessionAudioOutputFormat;
use crate::endpoint::realtime_websocket::protocol::SessionFunctionTool;
use crate::endpoint::realtime_websocket::protocol::SessionInputAudioTranscription;
use crate::endpoint::realtime_websocket::protocol::SessionNoiseReduction;
use crate::endpoint::realtime_websocket::protocol::SessionToolType;
use crate::endpoint::realtime_websocket::protocol::SessionTurnDetection;
use crate::endpoint::realtime_websocket::protocol::SessionType;
use crate::endpoint::realtime_websocket::protocol::SessionUpdateSession;
use crate::endpoint::realtime_websocket::protocol::TurnDetectionType;
use codex_protocol::protocol::ConversationTextRole;
use serde_json::json;

const REALTIME_V2_OUTPUT_MODALITY_AUDIO: &str = "audio";
const REALTIME_V2_OUTPUT_MODALITY_TEXT: &str = "text";
const REALTIME_V2_TOOL_CHOICE: &str = "auto";
const REALTIME_V2_BACKGROUND_AGENT_TOOL_NAME: &str = "background_agent";
const REALTIME_V2_BACKGROUND_AGENT_TOOL_DESCRIPTION: &str = "Send a user request to the background agent. Use this as the default action. Do not rephrase the user's ask or rewrite it in your own words; pass along the user's own words. If the background agent is idle, this starts a new task and returns the final result to the user. If the background agent is already working on a task, this sends the request as guidance to steer that previous task. If the user asks to do something next, later, after this, or once current work finishes, call this tool so the work is actually queued instead of merely promising to do it later.";
const REALTIME_V2_SILENCE_TOOL_NAME: &str = "remain_silent";
const REALTIME_V2_SILENCE_TOOL_DESCRIPTION: &str = "Call this when the best response is to say nothing. Use it instead of speaking after hidden system/control messages, after background agent updates in silent modes, or whenever acknowledging aloud would be distracting. This tool has no user-visible effect.";
const REALTIME_V2_INPUT_TRANSCRIPTION_MODEL: &str = "gpt-4o-mini-transcribe";

pub(super) fn conversation_item_create_message(
    text: String,
    role: ConversationTextRole,
) -> RealtimeOutboundMessage {
    let content_type = match role {
        ConversationTextRole::Assistant => ConversationContentType::OutputText,
        ConversationTextRole::User | ConversationTextRole::Developer => {
            ConversationContentType::InputText
        }
    };

    RealtimeOutboundMessage::ConversationItemCreate {
        item: ConversationItemPayload::Message(ConversationMessageItem {
            r#type: ConversationItemType::Message,
            role,
            content: vec![ConversationItemContent {
                r#type: content_type,
                text,
            }],
        }),
    }
}

pub(super) fn conversation_function_call_output_message(
    call_id: String,
    output_text: String,
) -> RealtimeOutboundMessage {
    RealtimeOutboundMessage::ConversationItemCreate {
        item: ConversationItemPayload::FunctionCallOutput(ConversationFunctionCallOutputItem {
            r#type: ConversationItemType::FunctionCallOutput,
            call_id,
            output: output_text,
        }),
    }
}

pub(super) fn session_update_session(
    instructions: String,
    session_mode: RealtimeSessionMode,
    output_modality: RealtimeOutputModality,
    voice: RealtimeVoice,
) -> SessionUpdateSession {
    match session_mode {
        RealtimeSessionMode::Conversational => SessionUpdateSession {
            id: None,
            r#type: SessionType::Realtime,
            model: None,
            instructions: Some(instructions),
            output_modalities: Some(vec![output_modality_value(output_modality).to_string()]),
            audio: SessionAudio {
                input: SessionAudioInput {
                    format: SessionAudioFormat {
                        r#type: AudioFormatType::AudioPcm,
                        rate: REALTIME_AUDIO_SAMPLE_RATE,
                    },
                    noise_reduction: Some(SessionNoiseReduction {
                        r#type: NoiseReductionType::NearField,
                    }),
                    transcription: Some(SessionInputAudioTranscription {
                        model: REALTIME_V2_INPUT_TRANSCRIPTION_MODEL.to_string(),
                    }),
                    turn_detection: Some(SessionTurnDetection {
                        r#type: TurnDetectionType::ServerVad,
                        interrupt_response: true,
                        create_response: true,
                        silence_duration_ms: 500,
                    }),
                },
                output: Some(SessionAudioOutput {
                    format: Some(SessionAudioOutputFormat {
                        r#type: AudioFormatType::AudioPcm,
                        rate: REALTIME_AUDIO_SAMPLE_RATE,
                    }),
                    voice,
                }),
            },
            tools: Some(vec![
                SessionFunctionTool {
                    r#type: SessionToolType::Function,
                    name: REALTIME_V2_BACKGROUND_AGENT_TOOL_NAME.to_string(),
                    description: REALTIME_V2_BACKGROUND_AGENT_TOOL_DESCRIPTION.to_string(),
                    parameters: json!({
                        "type": "object",
                        "properties": {
                            "prompt": {
                                "type": "string",
                                "description": "The user request to delegate to the background agent."
                            }
                        },
                        "required": ["prompt"],
                        "additionalProperties": false
                    }),
                },
                SessionFunctionTool {
                    r#type: SessionToolType::Function,
                    name: REALTIME_V2_SILENCE_TOOL_NAME.to_string(),
                    description: REALTIME_V2_SILENCE_TOOL_DESCRIPTION.to_string(),
                    parameters: json!({
                        "type": "object",
                        "properties": {},
                        "additionalProperties": false
                    }),
                },
            ]),
            tool_choice: Some(REALTIME_V2_TOOL_CHOICE.to_string()),
        },
        RealtimeSessionMode::Transcription => SessionUpdateSession {
            id: None,
            r#type: SessionType::Transcription,
            model: None,
            instructions: None,
            output_modalities: None,
            audio: SessionAudio {
                input: SessionAudioInput {
                    format: SessionAudioFormat {
                        r#type: AudioFormatType::AudioPcm,
                        rate: REALTIME_AUDIO_SAMPLE_RATE,
                    },
                    noise_reduction: None,
                    transcription: Some(SessionInputAudioTranscription {
                        model: REALTIME_V2_INPUT_TRANSCRIPTION_MODEL.to_string(),
                    }),
                    turn_detection: None,
                },
                output: None,
            },
            tools: None,
            tool_choice: None,
        },
    }
}

fn output_modality_value(output_modality: RealtimeOutputModality) -> &'static str {
    match output_modality {
        RealtimeOutputModality::Text => REALTIME_V2_OUTPUT_MODALITY_TEXT,
        RealtimeOutputModality::Audio => REALTIME_V2_OUTPUT_MODALITY_AUDIO,
    }
}

pub(super) fn websocket_intent() -> Option<&'static str> {
    None
}