-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathapi.rs
More file actions
2291 lines (2087 loc) · 79.2 KB
/
Copy pathapi.rs
File metadata and controls
2291 lines (2087 loc) · 79.2 KB
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use axum::{
Extension, Json,
extract::{Path, Query, State},
http::StatusCode,
response::IntoResponse,
};
#[cfg(feature = "schema")]
use schemars::schema_for;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::sync::broadcast::Sender;
use crate::AppState;
use terraphim_config::Config;
use terraphim_persistence::Persistable;
use terraphim_rolegraph::RoleGraph;
use terraphim_rolegraph::magic_unpair;
use terraphim_service::TerraphimService;
use terraphim_types::RoleName;
use terraphim_types::{Document, IndexedDocument, SearchQuery};
use crate::error::{Result, Status};
pub type SearchResultsStream = Sender<IndexedDocument>;
/// Response body of the [`health`] readiness probe.
///
/// Deterministic JSON contract so integration test harnesses can parse the
/// body (not just assert the status code): `{"status":"ok"}`.
#[derive(Debug, serde::Serialize)]
pub struct HealthResponse {
/// Readiness state of the server.
pub status: &'static str,
}
/// Readiness probe.
///
/// Returns HTTP 200 with a fixed JSON body `{"status":"ok"}` once the Axum
/// router is serving requests. Used by integration tests to wait for startup
/// instead of a fixed `sleep`, which is the documented root cause of the
/// `test_default_role_ripgrep_integration` flake (#2998, #2947).
pub(crate) async fn health() -> Json<HealthResponse> {
Json(HealthResponse { status: "ok" })
}
#[cfg(test)]
mod health_tests {
use super::*;
/// AC #2998: `GET /health` returns HTTP 200 with body `{"status":"ok"}`.
///
/// Locks the JSON body contract (was previously a free-form `"OK"` string
/// that could not be parsed by a JSON-asserting harness).
#[test]
fn health_serialises_to_fixed_json_status_ok() {
let body = serde_json::to_string(&HealthResponse { status: "ok" })
.expect("HealthResponse must serialise");
assert_eq!(body, r#"{"status":"ok"}"#);
}
/// The handler returns the canonical body without allocation surprises.
#[tokio::test]
async fn health_handler_returns_json_status_ok() {
let Json(payload) = health().await;
assert_eq!(payload.status, "ok");
}
}
/// Response for creating a document
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CreateDocumentResponse {
/// Status of the document creation
pub status: Status,
/// The id of the document that was successfully created
pub id: String,
}
/// Creates index of the document for each rolegraph
pub(crate) async fn create_document(
State(app_state): State<AppState>,
Json(document): Json<Document>,
) -> Result<Json<CreateDocumentResponse>> {
log::debug!("create_document");
let mut terraphim_service = TerraphimService::new(app_state.config_state.clone());
let document = terraphim_service.create_document(document).await?;
Ok(Json(CreateDocumentResponse {
status: Status::Success,
id: document.id,
}))
}
// TODO: Is this still needed now that we have search?
pub(crate) async fn _list_documents(
State(rolegraph): State<Arc<Mutex<RoleGraph>>>,
) -> impl IntoResponse {
let rolegraph = rolegraph.lock().await.clone();
log::debug!("{rolegraph:?}");
(StatusCode::OK, Json("Ok"))
}
/// Response envelope returned by the document search endpoints.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SearchResponse {
/// Status of the search
pub status: Status,
/// Vector of results which matched the query
pub results: Vec<Document>,
/// The number of documents that match the search query
pub total: usize,
}
/// Search for documents in all Terraphim graphs defined in the config via GET params
pub(crate) async fn search_documents(
Extension(_tx): Extension<SearchResultsStream>,
State(app_state): State<AppState>,
search_query: Query<SearchQuery>,
) -> Result<Json<SearchResponse>> {
log::debug!("search_document called with {:?}", search_query);
let mut terraphim_service = TerraphimService::new(app_state.config_state);
let results = terraphim_service.search(&search_query.0).await?;
let total = results.len();
Ok(Json(SearchResponse {
status: Status::Success,
results,
total,
}))
}
/// Search for documents in all Terraphim graphs defined in the config via POST body
pub(crate) async fn search_documents_post(
Extension(_tx): Extension<SearchResultsStream>,
State(app_state): State<AppState>,
search_query: Json<SearchQuery>,
) -> Result<Json<SearchResponse>> {
log::debug!("POST Searching documents with query: {search_query:?}");
let mut terraphim_service = TerraphimService::new(app_state.config_state);
let results = terraphim_service.search(&search_query).await?;
let total = results.len();
if total == 0 {
log::debug!("No documents found");
} else {
log::debug!("Found {total} documents");
}
Ok(Json(SearchResponse {
status: Status::Success,
results,
total,
}))
}
/// Response type for showing the config
///
/// This is also used when updating the config
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ConfigResponse {
/// Status of the config fetch
pub status: Status,
/// The config
pub config: Config,
}
/// API handler for Terraphim Config
pub(crate) async fn get_config(State(app_state): State<AppState>) -> Result<Json<ConfigResponse>> {
log::debug!("Called API endpoint get_config");
let terraphim_service = TerraphimService::new(app_state.config_state);
let config = terraphim_service.fetch_config().await;
Ok(Json(ConfigResponse {
status: Status::Success,
config,
}))
}
/// API handler for Terraphim Config update
///
/// This function updates the configuration both in-memory and persists it to disk
/// so that the changes survive server restarts.
pub(crate) async fn update_config(
State(app_state): State<AppState>,
Json(config_new): Json<Config>,
) -> Result<Json<ConfigResponse>> {
log::info!("Updating configuration and persisting to disk");
// Update in-memory configuration
let mut config = app_state.config_state.config.lock().await;
*config = config_new.clone();
drop(config); // Release the lock before async save operation
// Persist the configuration to disk
match config_new.save().await {
Ok(()) => {
log::info!("Configuration successfully updated and persisted");
Ok(Json(ConfigResponse {
status: Status::Success,
config: config_new,
}))
}
Err(e) => {
log::error!("Failed to persist configuration: {:?}", e);
// The configuration was updated in memory but not persisted
// This is still partially successful, so we return the new config
// but log the persistence error
Ok(Json(ConfigResponse {
status: Status::Success,
config: config_new,
}))
}
}
}
/// Returns JSON Schema for Terraphim Config
#[cfg(feature = "schema")]
pub(crate) async fn get_config_schema() -> Json<Value> {
let schema = schema_for!(Config);
Json(serde_json::to_value(&schema).expect("schema serialization"))
}
/// Returns JSON Schema for Terraphim Config (placeholder when schema feature disabled)
#[cfg(not(feature = "schema"))]
pub(crate) async fn get_config_schema() -> Json<Value> {
Json(serde_json::json!({
"error": "Schema generation not available. Enable 'schema' feature."
}))
}
/// Request body for updating the selected role only
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SelectedRoleRequest {
pub selected_role: terraphim_types::RoleName,
}
/// Update only the selected role without replacing the whole config
pub(crate) async fn update_selected_role(
State(app_state): State<AppState>,
Json(payload): Json<SelectedRoleRequest>,
) -> Result<Json<ConfigResponse>> {
let terraphim_service = TerraphimService::new(app_state.config_state.clone());
let config = terraphim_service
.update_selected_role(payload.selected_role)
.await?;
Ok(Json(ConfigResponse {
status: Status::Success,
config,
}))
}
// NOTE: RoleGraph visualisation DTOs
/// A single node in the role-graph visualisation payload.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GraphNodeDto {
/// Unique numeric identifier for this node.
pub id: u64,
/// Human-readable label (normalised term or raw id if unavailable).
pub label: String,
/// PageRank-derived relevance score for this node.
pub rank: u64,
}
/// A directed edge between two nodes in the role-graph visualisation payload.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GraphEdgeDto {
/// Identifier of the source node.
pub source: u64,
/// Identifier of the target node.
pub target: u64,
/// Edge weight reflecting co-occurrence strength.
pub rank: u64,
}
/// Response envelope for the `GET /rolegraph` endpoint.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RoleGraphResponseDto {
/// Outcome of the request.
pub status: Status,
/// All nodes in the requested role's knowledge graph.
pub nodes: Vec<GraphNodeDto>,
/// All edges connecting those nodes.
pub edges: Vec<GraphEdgeDto>,
/// Node IDs that have been pinned by the user (may be empty).
#[serde(default)]
pub pinned_node_ids: Vec<u64>,
}
#[derive(Debug, Deserialize)]
pub struct RoleGraphQuery {
role: Option<String>,
}
/// Return nodes and edges for the RoleGraph of the requested role (or currently selected role if omitted)
pub(crate) async fn get_rolegraph(
State(app_state): State<AppState>,
Query(query): Query<RoleGraphQuery>,
) -> Result<Json<RoleGraphResponseDto>> {
// Determine which role we should use
let role_name: RoleName = if let Some(role_str) = query.role {
RoleName::new(&role_str)
} else {
app_state.config_state.get_selected_role().await
};
// Retrieve the rolegraph for the role
let Some(rolegraph_sync) = app_state.config_state.roles.get(&role_name) else {
return Err(crate::error::ApiError(
StatusCode::NOT_FOUND,
anyhow::anyhow!(format!("Rolegraph not found for role: {role_name}")),
));
};
let rolegraph = rolegraph_sync.lock().await;
// Build node DTOs
let nodes: Vec<GraphNodeDto> = rolegraph
.nodes_map()
.iter()
.map(|(id, node)| {
let label = rolegraph
.ac_reverse_nterm
.get(id)
.map(|v| v.as_str().to_string())
.unwrap_or_else(|| id.to_string());
GraphNodeDto {
id: *id,
label,
rank: node.rank,
}
})
.collect();
// Build edge DTOs
let edges: Vec<GraphEdgeDto> = rolegraph
.edges_map()
.iter()
.map(|(edge_id, edge)| {
let (source, target) = magic_unpair(*edge_id);
GraphEdgeDto {
source,
target,
rank: edge.rank,
}
})
.collect();
let pinned_node_ids = rolegraph.get_pinned_node_ids().to_vec();
Ok(Json(RoleGraphResponseDto {
status: Status::Success,
nodes,
edges,
pinned_node_ids,
}))
}
/// Query parameters for KG term search
#[derive(Debug, Deserialize)]
pub struct KgSearchQuery {
/// The knowledge graph term to search for
pub term: String,
}
/// Find documents that contain a given knowledge graph term
///
/// This endpoint searches for documents that were the source of a knowledge graph term.
/// For example, given "haystack", it will find documents like "haystack.md" that contain
/// this term or its synonyms ("datasource", "service", "agent").
pub(crate) async fn find_documents_by_kg_term(
State(app_state): State<AppState>,
axum::extract::Path(role_name): axum::extract::Path<String>,
Query(query): Query<KgSearchQuery>,
) -> Result<Json<SearchResponse>> {
log::debug!(
"Finding documents for KG term '{}' in role '{}'",
query.term,
role_name
);
let role_name = RoleName::new(&role_name);
let mut terraphim_service = TerraphimService::new(app_state.config_state);
let results = terraphim_service
.find_documents_for_kg_term(&role_name, &query.term)
.await?;
let total = results.len();
log::debug!("Found {} documents for KG term '{}'", total, query.term);
Ok(Json(SearchResponse {
status: Status::Success,
results,
total,
}))
}
/// Request for document summarization
#[derive(Debug, Deserialize)]
pub struct SummarizeDocumentRequest {
/// Document ID to summarize
pub document_id: String,
/// Role to use for summarization (determines OpenRouter configuration)
pub role: String,
/// Optional: Override max summary length (default: 250 characters)
#[allow(dead_code)]
pub max_length: Option<usize>,
/// Optional: Force regeneration even if summary exists
#[allow(dead_code)]
pub force_regenerate: Option<bool>,
}
/// Response for document summarization
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SummarizeDocumentResponse {
/// Status of the summarization request
pub status: Status,
/// The document ID that was summarized
pub document_id: String,
/// The generated summary
pub summary: Option<String>,
/// The OpenRouter model used for summarization
pub model_used: Option<String>,
/// Whether this summary was newly generated or retrieved from cache
pub from_cache: bool,
/// Error message if summarization failed
pub error: Option<String>,
}
// New async queue API types
/// Request for async document summarization
#[derive(Debug, Deserialize)]
pub struct AsyncSummarizeRequest {
/// Document ID to summarize
pub document_id: String,
/// Role to use for summarization
pub role: String,
/// Optional: Priority level (low, normal, high, critical)
pub priority: Option<String>,
/// Optional: Override max summary length (default: 250 characters)
pub max_length: Option<usize>,
/// Optional: Force regeneration even if summary exists
pub force_regenerate: Option<bool>,
/// Optional: Callback URL for completion notification
pub callback_url: Option<String>,
}
/// Response for async summarization request
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AsyncSummarizeResponse {
/// Status of the request submission
pub status: Status,
/// Task ID for tracking progress
pub task_id: Option<String>,
/// Position in queue if successfully queued
pub position_in_queue: Option<usize>,
/// Estimated wait time in seconds
pub estimated_wait_seconds: Option<u64>,
/// Error message if submission failed
pub error: Option<String>,
}
/// Response for task status
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct TaskStatusResponse {
/// Status of the request
pub status: Status,
/// Task ID
pub task_id: String,
/// Current task status
pub task_status: Option<String>,
/// Progress percentage (0-100) if processing
pub progress: Option<f32>,
/// Result summary if completed
pub summary: Option<String>,
/// Error message if failed
pub error: Option<String>,
/// Processing duration if completed
pub processing_duration_ms: Option<u64>,
/// Next retry time if failed and retryable
pub next_retry_seconds: Option<u64>,
/// Retry count
pub retry_count: Option<u32>,
}
/// Request to cancel a task
#[derive(Debug, Deserialize)]
pub struct CancelTaskRequest {
/// Task ID to cancel
#[allow(dead_code)] // Task ID comes from URL path, not request body
pub task_id: String,
/// Reason for cancellation
pub reason: Option<String>,
}
/// Response for task cancellation
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CancelTaskResponse {
/// Status of the cancellation request
pub status: Status,
/// Whether the task was successfully cancelled
pub cancelled: bool,
/// Error message if cancellation failed
pub error: Option<String>,
}
/// Response for queue statistics
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct QueueStatsResponse {
/// Status of the request
pub status: Status,
/// Queue statistics
pub stats: Option<terraphim_service::summarization_queue::QueueStats>,
/// Error message if retrieval failed
pub error: Option<String>,
}
/// Request for batch summarization
#[derive(Debug, Deserialize)]
pub struct BatchSummarizeRequest {
/// List of documents to summarize
pub documents: Vec<BatchSummarizeItem>,
/// Role to use for summarization
pub role: String,
/// Priority for all tasks (low, normal, high, critical)
pub priority: Option<String>,
/// Optional: Callback URL for batch completion notification
pub callback_url: Option<String>,
}
/// Single item in batch summarization request
#[derive(Debug, Deserialize)]
pub struct BatchSummarizeItem {
/// Document ID to summarize
pub document_id: String,
/// Optional: Override max summary length
pub max_length: Option<usize>,
/// Optional: Force regeneration even if summary exists
pub force_regenerate: Option<bool>,
}
/// Response for batch summarization
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BatchSummarizeResponse {
/// Status of the batch request
pub status: Status,
/// List of submitted task IDs
pub task_ids: Vec<String>,
/// Number of successfully queued tasks
pub queued_count: usize,
/// Number of failed submissions
pub failed_count: usize,
/// Errors for failed submissions
pub errors: Vec<String>,
}
/// Query parameters for summarization status
#[derive(Debug, Deserialize)]
pub struct SummarizationStatusQuery {
/// Role to check summarization status for
pub role: String,
}
/// Response for summarization status
#[derive(Debug, Serialize, Clone)]
pub struct SummarizationStatusResponse {
/// Status of the request
pub status: Status,
/// Whether LLM is enabled for this role
pub llm_enabled: bool,
/// Whether LLM is properly configured for this role
pub llm_configured: bool,
/// The model that would be used for summarization
pub model: Option<String>,
/// Number of documents with existing summaries for this role
pub cached_summaries_count: u32,
}
/// Chat message exchanged with the assistant
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ChatMessage {
pub role: String, // "system" | "user" | "assistant"
pub content: String,
}
/// Chat request payload
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ChatRequest {
/// Role to use for chat (determines LLM configuration)
pub role: String,
/// Conversation so far
pub messages: Vec<ChatMessage>,
/// Optional model override
pub model: Option<String>,
/// Optional conversation ID to include context from
pub conversation_id: Option<String>,
/// Optional maximum tokens for the response
pub max_tokens: Option<u32>,
/// Optional temperature for response randomness (0.0-1.0)
pub temperature: Option<f32>,
}
/// Chat response payload
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ChatResponse {
pub status: Status,
pub message: Option<String>,
pub model_used: Option<String>,
pub error: Option<String>,
}
/// Handle chat completion via generic LLM client (OpenRouter, Ollama, etc.)
pub(crate) async fn chat_completion(
State(app_state): State<AppState>,
Json(request): Json<ChatRequest>,
) -> Result<Json<ChatResponse>> {
let role_name = RoleName::new(&request.role);
let config = app_state.config_state.config.lock().await;
let Some(role_ref) = config.roles.get(&role_name) else {
return Ok(Json(ChatResponse {
status: Status::Error,
message: None,
model_used: None,
error: Some(format!("Role '{}' not found", request.role)),
}));
};
// Clone role data to use after releasing the lock
let role = role_ref.clone();
// Check if VM execution is enabled BEFORE role is consumed
log::info!(
"Checking VM execution for role: {}, extra keys: {:?}",
role.name,
role.extra.keys().collect::<Vec<_>>()
);
let has_vm_execution = role
.extra
.get("vm_execution")
.or_else(|| {
// Handle nested extra field (serialization quirk similar to llm.rs)
role.extra
.get("extra")
.and_then(|nested| nested.get("vm_execution"))
})
.and_then(|vm_config| {
log::info!("Found vm_execution config: {:?}", vm_config);
vm_config.get("enabled")
})
.and_then(|v| v.as_bool())
.unwrap_or(false);
log::info!("VM execution enabled: {}", has_vm_execution);
// Clone role again for VM execution if needed
let role_for_vm = if has_vm_execution {
Some(role.clone())
} else {
None
};
drop(config);
// Try to build an LLM client from the role configuration
use terraphim_service::llm;
let Some(llm_client) = llm::build_llm_from_role(&role) else {
return Ok(Json(ChatResponse {
status: Status::Error,
message: None,
model_used: None,
error: Some("No LLM provider configured for this role. Please configure OpenRouter or Ollama in the role's 'extra' settings.".to_string()),
}));
};
// Build messages array; optionally inject system prompt and context
let mut messages_json: Vec<serde_json::Value> = Vec::new();
// Start with system prompt if available (support both OpenRouter and generic formats)
let system_prompt = {
#[cfg(feature = "openrouter")]
{
role.llm_chat_system_prompt.or_else(|| {
// Try generic system prompt from extra
role.extra
.get("system_prompt")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
})
}
#[cfg(not(feature = "openrouter"))]
{
// Try generic system prompt from extra
role.extra
.get("system_prompt")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
}
};
if let Some(system) = &system_prompt {
messages_json.push(serde_json::json!({"role":"system","content":system}));
}
// Inject context from conversation if provided
if let Some(conversation_id) = &request.conversation_id {
let conv_id = ConversationId::from_string(conversation_id.clone());
let manager = CONTEXT_MANAGER.lock().await;
if let Some(conversation) = manager.get_conversation(&conv_id) {
// Build context content from all context items
let mut context_content = String::new();
if !conversation.global_context.is_empty() {
context_content.push_str("=== CONTEXT INFORMATION ===\n");
context_content.push_str("The following information provides relevant context for this conversation:\n\n");
for (index, context_item) in conversation.global_context.iter().enumerate() {
context_content.push_str(&format!(
"Context Item {}: {}\n",
index + 1,
context_item.title
));
if let Some(score) = context_item.relevance_score {
context_content.push_str(&format!("Relevance Score: {:.2}\n", score));
}
context_content.push_str(&format!("Content: {}\n", context_item.content));
if !context_item.metadata.is_empty() {
context_content
.push_str(&format!("Metadata: {:?}\n", context_item.metadata));
}
context_content.push_str("\n---\n\n");
}
context_content.push_str("=== END CONTEXT ===\n\n");
context_content.push_str("Please use this context information to inform your responses. You can reference specific context items when relevant.\n\n");
// Add context as a system message after the main system prompt
messages_json
.push(serde_json::json!({"role": "system", "content": context_content}));
}
}
}
// Add user messages from the request
for m in request.messages.iter() {
messages_json.push(serde_json::json!({"role": m.role, "content": m.content}));
}
// Determine model name for response
let model_name = request
.model
.or({
#[cfg(feature = "openrouter")]
{
role.llm_chat_model
.clone()
.or_else(|| role.llm_model.clone())
}
#[cfg(not(feature = "openrouter"))]
{
None
}
})
.or_else(|| {
role.extra
.get("llm_model")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
})
.or_else(|| {
role.extra
.get("ollama_model")
.and_then(|v| v.as_str())
.map(|s| s.to_string())
})
.unwrap_or_else(|| format!("{} (default)", llm_client.name()));
// Configure chat options
let chat_opts = llm::ChatOptions {
max_tokens: request.max_tokens.or(Some(1024)),
temperature: request.temperature.or(Some(0.7)),
};
// Call the LLM client FIRST
match llm_client.chat_completion(messages_json, chat_opts).await {
Ok(mut reply) => {
// Check for code blocks in LLM response AFTER getting the reply
let vm_execution_result = if let Some(role_for_vm) = role_for_vm.clone() {
if reply.contains("```") {
use terraphim_multi_agent::{CommandInput, CommandType, TerraphimAgent};
use terraphim_persistence::DeviceStorage;
log::info!("Detected code blocks in LLM response, attempting VM execution");
log::info!(
"LLM response length: {}, contains backticks: {}",
reply.len(),
reply.matches("```").count()
);
// Create in-memory persistence for this chat session
match DeviceStorage::arc_memory_only().await {
Ok(persistence) => {
match TerraphimAgent::new(role_for_vm, persistence, None).await {
Ok(agent) => {
if let Ok(()) = agent.initialize().await {
// Execute code blocks from LLM response
let execute_input =
CommandInput::new(reply.clone(), CommandType::Execute);
match agent.process_command(execute_input).await {
Ok(vm_result) => {
log::info!("VM execution completed successfully");
// Return execution results, not "no code found" messages
if !vm_result
.text
.contains("No executable code found")
{
Some(vm_result.text)
} else {
None
}
}
Err(e) => {
log::warn!("VM execution failed: {}", e);
Some(format!("VM Execution Error: {}", e))
}
}
} else {
None
}
}
Err(e) => {
log::warn!("Failed to create agent for VM execution: {}", e);
None
}
}
}
Err(e) => {
log::warn!("Failed to create persistence for VM execution: {}", e);
None
}
}
} else {
None
}
} else {
None
};
// Append VM execution results if available
if let Some(vm_output) = vm_execution_result {
reply = format!("{}\n\n--- VM Execution Results ---\n{}", reply, vm_output);
}
Ok(Json(ChatResponse {
status: Status::Success,
message: Some(reply),
model_used: Some(model_name),
error: None,
}))
}
Err(e) => Ok(Json(ChatResponse {
status: Status::Error,
message: None,
model_used: Some(model_name),
error: Some(format!("Chat failed: {}", e)),
})),
}
}
/// Verify OpenRouter API key and fetch available models
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct OpenRouterModelsRequest {
pub role: String,
pub api_key: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct OpenRouterModelsResponse {
pub status: Status,
pub models: Vec<String>,
pub error: Option<String>,
}
#[allow(dead_code)]
#[cfg_attr(not(feature = "openrouter"), allow(unused_variables))]
pub(crate) async fn list_openrouter_models(
State(app_state): State<AppState>,
Json(req): Json<OpenRouterModelsRequest>,
) -> Result<Json<OpenRouterModelsResponse>> {
let role_name = RoleName::new(&req.role);
let config = app_state.config_state.config.lock().await;
let Some(role) = config.roles.get(&role_name) else {
return Ok(Json(OpenRouterModelsResponse {
status: Status::Error,
models: vec![],
error: Some(format!("Role '{}' not found", req.role)),
}));
};
#[cfg(feature = "openrouter")]
{
// Determine API key preference: request -> role -> env
let api_key = if let Some(k) = &req.api_key {
k.clone()
} else if let Some(k) = &role.llm_api_key {
k.clone()
} else {
match std::env::var("OPENROUTER_KEY") {
Ok(v) => v,
Err(_) => {
return Ok(Json(OpenRouterModelsResponse {
status: Status::Error,
models: vec![],
error: Some("Missing OpenRouter API key".to_string()),
}));
}
}
};
// Any valid model string works for constructing the client
let seed_model = role
.llm_model
.clone()
.unwrap_or_else(|| "openai/gpt-3.5-turbo".to_string());
drop(config);
use terraphim_service::openrouter::OpenRouterService;
match OpenRouterService::new(&api_key, &seed_model) {
Ok(client) => match client.list_models().await {
Ok(models) => Ok(Json(OpenRouterModelsResponse {
status: Status::Success,
models,
error: None,
})),
Err(e) => Ok(Json(OpenRouterModelsResponse {
status: Status::Error,
models: vec![],
error: Some(format!("Failed to list models: {}", e)),
})),
},
Err(e) => Ok(Json(OpenRouterModelsResponse {
status: Status::Error,
models: vec![],
error: Some(format!("Failed to init OpenRouter client: {}", e)),
})),
}
}
#[cfg(not(feature = "openrouter"))]
{
Ok(Json(OpenRouterModelsResponse {
status: Status::Error,
models: vec![],
error: Some("OpenRouter feature not enabled during compilation".to_string()),
}))
}
}
/// Generate or retrieve a summary for a document using OpenRouter
///
/// This endpoint generates AI-powered summaries for documents using the OpenRouter service.
/// It requires the role to have OpenRouter properly configured (enabled, API key, model).
/// Summaries are cached in the persistence layer to avoid redundant API calls.
#[cfg_attr(not(feature = "openrouter"), allow(unused_variables))]
pub(crate) async fn summarize_document(
State(app_state): State<AppState>,
Json(request): Json<SummarizeDocumentRequest>,
) -> Result<Json<SummarizeDocumentResponse>> {
log::debug!(
"Summarizing document '{}' with role '{}'",
request.document_id,
request.role
);
let role_name = RoleName::new(&request.role);
let config = app_state.config_state.config.lock().await;
// Get the role configuration
let Some(role_ref) = config.roles.get(&role_name) else {
return Ok(Json(SummarizeDocumentResponse {
status: Status::Error,
document_id: request.document_id,
summary: None,
model_used: None,
from_cache: false,
error: Some(format!("Role '{}' not found", request.role)),
}));
};
// Check if OpenRouter is enabled and configured for this role
#[cfg(feature = "openrouter")]
{
if !role_ref.has_llm_config() {
return Ok(Json(SummarizeDocumentResponse {
status: Status::Error,