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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
use actix_web::http::header::ContentType;
use chrono::Utc;
use domain::chatbot::{
    estimate_tokens, send_chat_request_and_parse_stream, ApiChatMessage, ChatRequest,
};
use headless_lms_models::chatbot_conversations::{
    self, ChatbotConversation, ChatbotConversationInfo,
};

use crate::prelude::*;

/**
GET `/api/v0/course-material/course-modules/chatbot/for-course/:course-id`

Returns one chatbot configuration id for a course that students can use.
*/
#[instrument(skip(pool))]
async fn get_chatbot_configuration_for_course(
    pool: web::Data<PgPool>,
    course_id: web::Path<Uuid>,
) -> ControllerResult<web::Json<Option<Uuid>>> {
    let token = skip_authorize();

    let mut conn = pool.acquire().await?;
    let chatbot_configurations =
        models::chatbot_configurations::get_for_course(&mut conn, *course_id).await?;

    let res = chatbot_configurations
        .into_iter()
        .find(|c| c.enabled_to_students)
        .map(|c| c.id);

    token.authorized_ok(web::Json(res))
}

/**
POST `/api/v0/course-material/chatbot/:chatbot_configuration_id/conversations/:conversation_id/send-message`

Sends a new chat message to the chatbot.
*/
#[instrument(skip(pool, app_conf))]
async fn send_message(
    pool: web::Data<PgPool>,
    params: web::Path<(Uuid, Uuid)>,
    user: AuthUser,
    app_conf: web::Data<ApplicationConfiguration>,
    payload: web::Json<String>,
) -> ControllerResult<HttpResponse> {
    let message = payload.into_inner();
    let chatbot_configuration_id = params.0;
    let conversation_id = params.1;
    let mut conn = pool.acquire().await?;
    let mut tx: sqlx::Transaction<Postgres> = conn.begin().await?;
    let token = skip_authorize();

    let configuration =
        models::chatbot_configurations::get_by_id(&mut tx, chatbot_configuration_id).await?;
    let conversation_messages =
        models::chatbot_conversation_messages::get_by_conversation_id(&mut tx, conversation_id)
            .await?;
    let new_order_number = conversation_messages
        .iter()
        .map(|m| m.order_number)
        .max()
        .unwrap_or(0)
        + 1;
    let new_message = models::chatbot_conversation_messages::insert(
        &mut tx,
        models::chatbot_conversation_messages::ChatbotConversationMessage {
            id: Uuid::new_v4(),
            created_at: Utc::now(),
            updated_at: Utc::now(),
            deleted_at: None,
            conversation_id,
            message: Some(message.clone()),
            is_from_chatbot: false,
            message_is_complete: true,
            used_tokens: estimate_tokens(&message),
            order_number: new_order_number,
        },
    )
    .await?;

    let mut api_chat_messages = conversation_messages
        .into_iter()
        .map(Into::into)
        .collect::<Vec<ApiChatMessage>>();

    api_chat_messages.push(new_message.into());
    api_chat_messages.insert(
        0,
        ApiChatMessage {
            role: "system".to_string(),
            content: configuration.prompt.clone(),
        },
    );

    let chat_request = ChatRequest {
        messages: api_chat_messages,
        temperature: configuration.temperature,
        top_p: configuration.top_p,
        frequency_penalty: configuration.frequency_penalty,
        presence_penalty: configuration.presence_penalty,
        max_tokens: configuration.response_max_tokens,
        stop: None,
        stream: true,
    };

    let response_stream = send_chat_request_and_parse_stream(
        &mut tx,
        // An Arc, cheap to clone.
        pool.clone(),
        &chat_request,
        &app_conf,
        conversation_id,
        new_order_number + 1,
    )
    .await?;

    tx.commit().await?;

    token.authorized_ok(
        HttpResponse::Ok()
            .content_type(ContentType::json())
            .streaming(response_stream),
    )
}

/**
POST `/api/v0/course-material/course-modules/chatbot/:chatbot_configuration_id/conversations/new`

Sends a new chat message to the chatbot.
*/
#[instrument(skip(pool))]
async fn new_conversation(
    pool: web::Data<PgPool>,
    user: AuthUser,
    params: web::Path<Uuid>,
) -> ControllerResult<web::Json<ChatbotConversation>> {
    let token = skip_authorize();

    let mut conn = pool.acquire().await?;
    let mut tx = conn.begin().await?;

    let configuration = models::chatbot_configurations::get_by_id(&mut tx, *params).await?;

    let conversation = models::chatbot_conversations::insert(
        &mut tx,
        ChatbotConversation {
            id: Uuid::new_v4(),
            created_at: Utc::now(),
            updated_at: Utc::now(),
            deleted_at: None,
            course_id: configuration.course_id,
            user_id: user.id,
            chatbot_configuration_id: configuration.id,
        },
    )
    .await?;

    let _first_message = models::chatbot_conversation_messages::insert(
        &mut tx,
        models::chatbot_conversation_messages::ChatbotConversationMessage {
            id: Uuid::new_v4(),
            created_at: Utc::now(),
            updated_at: Utc::now(),
            deleted_at: None,
            conversation_id: conversation.id,
            message: Some(configuration.initial_message.clone()),
            is_from_chatbot: true,
            message_is_complete: true,
            used_tokens: estimate_tokens(&configuration.initial_message),
            order_number: 0,
        },
    )
    .await?;

    tx.commit().await?;

    token.authorized_ok(web::Json(conversation))
}

/**
POST `/api/v0/course-material/course-modules/chatbot/:chatbot_configuration_id/conversations/current`

Returns the current conversation for the user.
*/
#[instrument(skip(pool))]
async fn current_conversation_info(
    pool: web::Data<PgPool>,
    user: AuthUser,
    params: web::Path<Uuid>,
) -> ControllerResult<web::Json<ChatbotConversationInfo>> {
    let token = skip_authorize();

    let mut conn = pool.acquire().await?;
    let chatbot_configuration =
        models::chatbot_configurations::get_by_id(&mut conn, *params).await?;
    let res = chatbot_conversations::get_current_conversation_info(
        &mut conn,
        user.id,
        chatbot_configuration.id,
    )
    .await?;

    token.authorized_ok(web::Json(res))
}

/**
Add a route for each controller in this module.

The name starts with an underline in order to appear before other functions in the module documentation.

We add the routes by calling the route method instead of using the route annotations because this method preserves the function signatures for documentation.
*/
pub fn _add_routes(cfg: &mut ServiceConfig) {
    cfg.route(
        "/{chatbot_configuration_id}/conversations/{conversation_id}/send-message",
        web::post().to(send_message),
    )
    .route(
        "/{chatbot_configuration_id}/conversations/current",
        web::get().to(current_conversation_info),
    )
    .route(
        "/{chatbot_configuration_id}/conversations/new",
        web::post().to(new_conversation),
    )
    .route(
        "/for-course/{course_id}",
        web::get().to(get_chatbot_configuration_for_course),
    );
}