formal-ai 0.151.0

Formal symbolic AI implementation with OpenAI-compatible APIs
Documentation
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
//! Natural-language web-search intent recognition.

use crate::engine::normalize_prompt;

use super::web_requests::normalize_url_candidate;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum WebSearchQueryKind {
    ExplicitPrefix,
    SemanticAction,
    ImplicitResearchQuestion,
    EnumerationResearchRequest,
}

impl WebSearchQueryKind {
    pub(super) const fn as_str(self) -> &'static str {
        match self {
            Self::ExplicitPrefix => "explicit_prefix",
            Self::SemanticAction => "semantic_action",
            Self::ImplicitResearchQuestion => "implicit_research_question",
            Self::EnumerationResearchRequest => "enumeration_research_request",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct WebSearchRequest {
    pub(super) query: String,
    pub(super) kind: WebSearchQueryKind,
}

pub(super) fn extract_web_search_request(
    prompt: &str,
    normalized: &str,
) -> Option<WebSearchRequest> {
    let normalized_words = normalize_prompt(prompt);
    if normalized_words.starts_with("search conversations ")
        || normalized_words.starts_with("search my conversations ")
        || normalized_words.starts_with("search my chats ")
        || is_personal_fact_filter_request(&normalized_words)
    {
        return None;
    }
    for prefix in WEB_SEARCH_EXPLICIT_PREFIXES {
        if let Some(query) = normalized_words.strip_prefix(prefix) {
            if let Some(query) = valid_search_query(query) {
                return Some(WebSearchRequest {
                    query,
                    kind: WebSearchQueryKind::ExplicitPrefix,
                });
            }
        }
        if let Some(query) = normalized.strip_prefix(prefix) {
            if let Some(query) = valid_search_query(query) {
                return Some(WebSearchRequest {
                    query,
                    kind: WebSearchQueryKind::ExplicitPrefix,
                });
            }
        }
    }
    if let Some(query) = extract_semantic_web_search_query(&normalized_words) {
        return Some(WebSearchRequest {
            query,
            kind: WebSearchQueryKind::SemanticAction,
        });
    }
    if let Some(query) = extract_enumeration_research_request(&normalized_words) {
        return Some(WebSearchRequest {
            query,
            kind: WebSearchQueryKind::EnumerationResearchRequest,
        });
    }
    extract_implicit_research_question(&normalized_words).map(|query| WebSearchRequest {
        query,
        kind: WebSearchQueryKind::ImplicitResearchQuestion,
    })
}

fn is_personal_fact_filter_request(normalized: &str) -> bool {
    normalized.contains("facts i have contributed")
        || normalized.contains("facts ive contributed")
        || normalized.contains("facts i contributed")
        || normalized.contains("my facts")
}

fn clean_search_query(value: &str) -> String {
    value
        .trim()
        .trim_matches(is_url_wrapper_punctuation)
        .trim_end_matches(is_url_trailing_punctuation)
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

const fn is_url_wrapper_punctuation(character: char) -> bool {
    matches!(
        character,
        '<' | '>' | '(' | ')' | '[' | ']' | '{' | '}' | '"' | '\'' | '`' | '«' | '»'
    )
}

const fn is_url_trailing_punctuation(character: char) -> bool {
    matches!(character, '.' | ',' | '!' | '?' | ';' | ':' | '')
}

const WEB_SEARCH_EXPLICIT_PREFIXES: &[&str] = &[
    "search the web for ",
    "search web for ",
    "search the internet for ",
    "search internet for ",
    "search online for ",
    "search for information about ",
    "search for information on ",
    "web search for ",
    "find on the internet ",
    "find online ",
    "find information about ",
    "find information on ",
    "find detailed information about ",
    "find detailed information on ",
    "find info about ",
    "find info on ",
    "look up information about ",
    "look up information on ",
    "look up info about ",
    "look up info on ",
    "look up online ",
    "найди в интернете ",
    "поищи в интернете ",
    "поиск в интернете ",
    "найди онлайн ",
    "поищи онлайн ",
    "найди в сети ",
    "поищи в сети ",
    "найди информацию в интернете о ",
    "найди информацию в интернете об ",
    "поищи информацию в интернете о ",
    "поищи информацию в интернете об ",
    "найди информацию о ",
    "найди информацию об ",
    "найди информацию про ",
    "найди информацию по ",
    "найти информацию о ",
    "найти информацию об ",
    "поищи информацию о ",
    "поищи информацию об ",
    "поищи информацию про ",
    "поищи информацию по ",
    "найди инфу о ",
    "найди инфу об ",
    "поищи инфу о ",
    "поищи инфу об ",
    "найди сведения о ",
    "найди сведения об ",
    "поищи сведения о ",
    "поищи сведения об ",
    "найди материалы о ",
    "найди материалы об ",
    "поищи материалы о ",
    "поищи материалы об ",
];

const WEB_SEARCH_ACTION_MARKERS: &[&str] = &[
    " search ",
    " find ",
    " look up ",
    " lookup ",
    " research ",
    " investigate ",
    " найди ",
    " найти ",
    " поищи ",
    " поиск ",
    " поискать ",
    " ищи ",
    " разыщи ",
    " узнай ",
    "खोज",
    "ढूंढ",
    "ढूँढ",
    "搜索",
    "查找",
    "查询",
    "檢索",
    "检索",
    "搜一下",
    "查一下",
];

const WEB_SEARCH_STRONG_ACTION_MARKERS: &[&str] = &[
    " search ",
    " look up ",
    " lookup ",
    " research ",
    " investigate ",
    " поищи ",
    " поиск ",
    " поискать ",
    " ищи ",
    "खोज",
    "ढूंढ",
    "ढूँढ",
    "搜索",
    "查找",
    "查询",
    "檢索",
    "检索",
    "搜一下",
    "查一下",
];

const WEB_SEARCH_SIGNAL_MARKERS: &[&str] = &[
    " web ",
    " internet ",
    " online ",
    " wikipedia ",
    " wikidata ",
    " wiktionary ",
    " information ",
    " info ",
    " details ",
    " data ",
    " material ",
    " materials ",
    " resource ",
    " resources ",
    " source ",
    " sources ",
    " article ",
    " articles ",
    " fact ",
    " facts ",
    " интернете ",
    " интернет ",
    " онлайн ",
    " сети ",
    " википед",
    " викиданн",
    " информац",
    " инфу ",
    " сведения ",
    " материал",
    " данные ",
    " источник",
    "जानकारी",
    "सूचना",
    "विवरण",
    "सामग्री",
    "स्रोत",
    "लेख",
    "इंटरनेट",
    "ऑनलाइन",
    "वेब",
    "विकिपीडिया",
    "विकिडाटा",
    "信息",
    "資料",
    "资料",
    "内容",
    "來源",
    "来源",
    "资源",
    "資源",
    "文章",
    "百科",
    "维基百科",
    "維基百科",
    "维基数据",
    "維基數據",
    "网上",
    "網上",
    "在线",
    "在線",
    "互联网",
    "網路",
    "网络",
];

const SEARCH_QUERY_AFTER_MARKERS: &[&str] = &[
    " about ",
    " on ",
    " regarding ",
    " concerning ",
    " for ",
    " о ",
    " об ",
    " про ",
    " по ",
    " насчет ",
    " относительно ",
    "关于",
    "關於",
    "有关",
    "有關",
];

const SEARCH_QUERY_BEFORE_MARKERS: &[&str] = &[
    " के बारे में",
    " के विषय में",
    " से संबंधित",
    " पर",
    " की जानकारी",
    " की सूचना",
];

const SEARCH_ACTION_AFTER_MARKERS: &[&str] = &[
    "search for ",
    "search ",
    "find ",
    "look up ",
    "lookup ",
    "research ",
    "investigate ",
    "найди ",
    "найти ",
    "поищи ",
    "поискать ",
    "ищи ",
    "разыщи ",
    "узнай ",
    "खोजो ",
    "खोजें ",
    "खोजिए ",
    "ढूंढो ",
    "ढूँढो ",
    "ढूंढें ",
    "ढूँढें ",
    "搜索",
    "查找",
    "查询",
    "檢索",
    "检索",
    "搜一下",
    "查一下",
];

const SEARCH_QUERY_LEADING_NOISE: &[&str] = &[
    "please ",
    "can you ",
    "could you ",
    "would you ",
    "me ",
    "the ",
    "some ",
    "detailed ",
    "more ",
    "current ",
    "latest ",
    "information about ",
    "information on ",
    "info about ",
    "info on ",
    "details about ",
    "details on ",
    "data about ",
    "data on ",
    "подробные ",
    "информацию о ",
    "информацию об ",
    "инфу о ",
    "инфу об ",
    "сведения о ",
    "сведения об ",
    "материалы о ",
    "материалы об ",
    "материалы по ",
    "данные о ",
    "данные об ",
    "о ",
    "об ",
    "про ",
    "по ",
    "कृपया ",
    "जानकारी ",
    "सूचना ",
    "विवरण ",
    "सामग्री ",
    "关于",
    "關於",
    "有关",
    "有關",
];

const SEARCH_QUERY_TRAILING_NOISE: &[&str] = &[
    " online",
    " on the internet",
    " on the web",
    " on wikipedia",
    " in wikipedia",
    " from wikipedia",
    " information",
    " info",
    " details",
    " data",
    " material",
    " materials",
    " resources",
    " sources",
    " articles",
    " facts",
    " в интернете",
    " онлайн",
    " в сети",
    " в википедии",
    " википедии",
    " информация",
    " сведения",
    " материалы",
    " данные",
    " के बारे में",
    " के विषय में",
    " से संबंधित",
    " पर",
    " की जानकारी",
    " की सूचना",
    " जानकारी",
    " सूचना",
    " विवरण",
    " सामग्री",
    " स्रोत",
    " विकिपीडिया में",
    " ऑनलाइन",
    " इंटरनेट पर",
    " खोजो",
    " खोजें",
    " खोजिए",
    " ढूंढो",
    " ढूँढो",
    " ढूंढें",
    " ढूँढें",
    "的信息",
    "的資料",
    "的资料",
    "信息",
    "資料",
    "资料",
    "内容",
    "文章",
    "在维基百科上",
    "在維基百科上",
    "维基百科",
    "維基百科",
    "网上",
    "網上",
    "在线",
    "在線",
    "搜索",
    "查找",
    "查一下",
    "搜一下",
];

const SEARCH_QUERY_SOURCE_ONLY: &[&str] = &[
    "web",
    "internet",
    "online",
    "wikipedia",
    "wikidata",
    "wiktionary",
    "интернет",
    "интернете",
    "онлайн",
    "сети",
    "википедии",
    "इंटरनेट",
    "ऑनलाइन",
    "वेब",
    "विकिपीडिया",
    "网上",
    "網上",
    "在线",
    "在線",
    "互联网",
    "網路",
    "网络",
    "维基百科",
    "維基百科",
];

const IMPLICIT_RESEARCH_QUESTION_PREFIXES: &[&str] = &[
    "what is the ",
    "what is a ",
    "what is an ",
    "what is ",
    "what are the ",
    "what are ",
    "what s the ",
    "what s a ",
    "what s an ",
    "what s ",
    "which is the ",
    "which is a ",
    "which is an ",
    "which are the ",
    "which are ",
    "which ",
    "who is the ",
    "who are the ",
    "who ",
    "where is the ",
    "where are the ",
    "where ",
    "when is the ",
    "when are the ",
    "when ",
    "why is the ",
    "why are the ",
    "why ",
    "how is the ",
    "how are the ",
    "how ",
    "can you tell me ",
    "could you tell me ",
    "do you know ",
];

const IMPLICIT_RESEARCH_MODIFIERS: &[&str] = &[
    " most ",
    " best ",
    " top ",
    " leading ",
    " standard ",
    " de facto ",
    " widely used ",
    " commonly used ",
    " popular ",
    " recommended ",
    " current ",
    " latest ",
    " recent ",
    " state of the art ",
    " sota ",
    " should i use ",
    " should we use ",
    " should be used ",
];

const IMPLICIT_RESEARCH_EVIDENCE_DOMAINS: &[&str] = &[
    " dataset ",
    " datasets ",
    " benchmark ",
    " benchmarks ",
    " corpus ",
    " corpora ",
    " metric ",
    " metrics ",
    " framework ",
    " frameworks ",
    " paper ",
    " papers ",
    " study ",
    " studies ",
];

const IMPLICIT_RESEARCH_EVALUATION_DOMAINS: &[&str] = &[
    " evaluation ",
    " evaluate ",
    " validation ",
    " validate ",
    " quality ",
    " translation ",
    " compare ",
    " comparison ",
];

const ENUMERATION_RESEARCH_PREFIXES: &[&str] = &[
    "list all ",
    "list every ",
    "list the ",
    "show all ",
    "show me all ",
    "show me the ",
    "give me all ",
    "name all ",
    "enumerate all ",
    "перечисли всех ",
    "перечисли все ",
    "список всех ",
    "назови всех ",
    "सभी ",
    "हर ",
    "列出所有 ",
    "列出全部 ",
    "显示所有 ",
    "枚举所有 ",
];

const ENUMERATION_RESEARCH_CONSTRAINT_MARKERS: &[&str] = &[
    " with ",
    " that ",
    " who ",
    " whose ",
    " where ",
    " which ",
    " having ",
    " have ",
    " has ",
    " featuring ",
    " capable of ",
    " can ",
    " for ",
    " by ",
    " in ",
    " с ",
    " у которых ",
    " которые ",
    " имеющие ",
    " имеющих ",
    " для ",
    " в ",
    " जिनके ",
    " जिनमें ",
    " जिसमें ",
    " वाले ",
    " के साथ ",
    " के लिए ",
    " में ",
    " 具有 ",
    "",
    " 带有 ",
    " 可以 ",
    "",
    "",
    " 用于 ",
];

fn extract_semantic_web_search_query(normalized: &str) -> Option<String> {
    let has_action = contains_any_search_marker(normalized, WEB_SEARCH_ACTION_MARKERS);
    if !has_action {
        return None;
    }
    let has_strong_action =
        contains_any_search_marker(normalized, WEB_SEARCH_STRONG_ACTION_MARKERS);
    if !has_strong_action && !contains_any_search_marker(normalized, WEB_SEARCH_SIGNAL_MARKERS) {
        return None;
    }
    for marker in SEARCH_QUERY_AFTER_MARKERS {
        if let Some(index) = normalized.find(marker) {
            let start = index + marker.len();
            if let Some(query) = valid_search_query(&normalized[start..]) {
                return Some(query);
            }
        }
    }
    for marker in SEARCH_QUERY_BEFORE_MARKERS {
        if let Some(index) = normalized.find(marker) {
            if let Some(query) = valid_search_query(&normalized[..index]) {
                return Some(query);
            }
        }
    }
    for marker in SEARCH_ACTION_AFTER_MARKERS {
        if let Some(index) = normalized.find(marker) {
            let start = index + marker.len();
            if let Some(query) = valid_search_query(&normalized[start..]) {
                return Some(query);
            }
        }
    }
    None
}

fn extract_implicit_research_question(normalized: &str) -> Option<String> {
    if !starts_with_any(normalized, IMPLICIT_RESEARCH_QUESTION_PREFIXES) {
        return None;
    }
    let padded = format!(" {normalized} ");
    let has_modifier = IMPLICIT_RESEARCH_MODIFIERS
        .iter()
        .any(|marker| padded.contains(marker));
    let has_evidence_domain = IMPLICIT_RESEARCH_EVIDENCE_DOMAINS
        .iter()
        .any(|marker| padded.contains(marker));
    let has_evaluation_domain = IMPLICIT_RESEARCH_EVALUATION_DOMAINS
        .iter()
        .any(|marker| padded.contains(marker));
    if !(has_modifier || has_evidence_domain && has_evaluation_domain) {
        return None;
    }
    let query = strip_implicit_research_prefix(normalized);
    valid_search_query(query)
}

fn extract_enumeration_research_request(normalized: &str) -> Option<String> {
    let query = strip_enumeration_research_prefix(normalized)?;
    if !looks_like_enumeration_research_query(query) {
        return None;
    }
    valid_search_query(query)
}

fn starts_with_any(value: &str, prefixes: &[&str]) -> bool {
    prefixes.iter().any(|prefix| value.starts_with(prefix))
}

fn strip_implicit_research_prefix(value: &str) -> &str {
    for prefix in IMPLICIT_RESEARCH_QUESTION_PREFIXES {
        if let Some(stripped) = value.strip_prefix(prefix) {
            return stripped;
        }
    }
    value
}

fn strip_enumeration_research_prefix(value: &str) -> Option<&str> {
    for prefix in ENUMERATION_RESEARCH_PREFIXES {
        if let Some(stripped) = value.strip_prefix(prefix) {
            return Some(stripped);
        }
    }
    None
}

fn looks_like_enumeration_research_query(query: &str) -> bool {
    if query.split_whitespace().count() < 3 {
        return false;
    }
    contains_any_search_marker(query, ENUMERATION_RESEARCH_CONSTRAINT_MARKERS)
}

fn contains_any_search_marker(normalized: &str, markers: &[&str]) -> bool {
    markers
        .iter()
        .any(|marker| contains_search_marker(normalized, marker))
}

fn contains_search_marker(normalized: &str, marker: &str) -> bool {
    if marker.starts_with(' ') || marker.ends_with(' ') {
        let padded = format!(" {normalized} ");
        padded.contains(marker)
    } else {
        normalized.contains(marker)
    }
}

fn valid_search_query(value: &str) -> Option<String> {
    let query = clean_semantic_search_query(value);
    let query_key = query.to_lowercase();
    if query.is_empty()
        || SEARCH_QUERY_SOURCE_ONLY.contains(&query_key.as_str())
        || normalize_url_candidate(&query).is_some()
    {
        return None;
    }
    Some(query)
}

fn clean_semantic_search_query(value: &str) -> String {
    let mut query = clean_search_query(value);
    loop {
        let before = query.clone();
        for prefix in SEARCH_QUERY_LEADING_NOISE {
            if let Some(stripped) = query.strip_prefix(prefix) {
                query = clean_search_query(stripped);
            }
        }
        for suffix in SEARCH_QUERY_TRAILING_NOISE {
            if let Some(stripped) = query.strip_suffix(suffix) {
                query = clean_search_query(stripped);
            }
        }
        if query == before {
            return query;
        }
    }
}