@promptbook/components 0.105.0-6 → 0.105.0-8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/esm/index.es.js CHANGED
@@ -13,10 +13,10 @@ import { createRoot } from 'react-dom/client';
13
13
  import { Converter } from 'showdown';
14
14
  import { BehaviorSubject, Subject } from 'rxjs';
15
15
  import { forTime } from 'waitasecond';
16
+ import colors from 'colors';
16
17
  import sha256 from 'crypto-js/sha256';
17
18
  import { lookup, extension } from 'mime-types';
18
19
  import { parse, unparse } from 'papaparse';
19
- import colors from 'colors';
20
20
  import Bottleneck from 'bottleneck';
21
21
  import OpenAI from 'openai';
22
22
  import QRCode from 'qrcode';
@@ -35,7 +35,7 @@ const BOOK_LANGUAGE_VERSION = '2.0.0';
35
35
  * @generated
36
36
  * @see https://github.com/webgptorg/promptbook
37
37
  */
38
- const PROMPTBOOK_ENGINE_VERSION = '0.105.0-6';
38
+ const PROMPTBOOK_ENGINE_VERSION = '0.105.0-8';
39
39
  /**
40
40
  * TODO: string_promptbook_version should be constrained to the all versions of Promptbook engine
41
41
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -3212,6 +3212,698 @@ function capitalize(word) {
3212
3212
  return word.substring(0, 1).toUpperCase() + word.substring(1);
3213
3213
  }
3214
3214
 
3215
+ /**
3216
+ * Creates human-readable hash
3217
+ *
3218
+ * @public exported from `@promptbook/utils`
3219
+ */
3220
+ async function linguisticHash(input) {
3221
+ const hash = computeHash(input);
3222
+ // Use parts of the hash to select words
3223
+ // SHA256 is 64 hex characters
3224
+ // We use different slices of the hash to ensure variety even with small changes in input
3225
+ const part1 = parseInt(hash.substring(0, 10), 16);
3226
+ const part2 = parseInt(hash.substring(10, 20), 16);
3227
+ const part3 = parseInt(hash.substring(20, 30), 16);
3228
+ const adjective = ADJECTIVES[part1 % ADJECTIVES.length];
3229
+ const noun = NOUNS[part2 % NOUNS.length];
3230
+ const verb = VERBS[part3 % VERBS.length];
3231
+ return `${capitalize(adjective)} ${noun.toLowerCase()} ${verb.toLowerCase()}`;
3232
+ }
3233
+ const ADJECTIVES = [
3234
+ 'red',
3235
+ 'blue',
3236
+ 'green',
3237
+ 'yellow',
3238
+ 'quick',
3239
+ 'slow',
3240
+ 'bright',
3241
+ 'dark',
3242
+ 'happy',
3243
+ 'sad',
3244
+ 'brave',
3245
+ 'calm',
3246
+ 'clever',
3247
+ 'eager',
3248
+ 'fancy',
3249
+ 'grand',
3250
+ 'jolly',
3251
+ 'kind',
3252
+ 'lucky',
3253
+ 'nice',
3254
+ 'proud',
3255
+ 'silly',
3256
+ 'wise',
3257
+ 'young',
3258
+ 'old',
3259
+ 'big',
3260
+ 'small',
3261
+ 'fast',
3262
+ 'shiny',
3263
+ 'wild',
3264
+ 'silent',
3265
+ 'loud',
3266
+ 'soft',
3267
+ 'hard',
3268
+ 'warm',
3269
+ 'cold',
3270
+ 'sweet',
3271
+ 'sour',
3272
+ 'bitter',
3273
+ 'salty',
3274
+ 'rich',
3275
+ 'poor',
3276
+ 'heavy',
3277
+ 'light',
3278
+ 'strong',
3279
+ 'weak',
3280
+ 'smooth',
3281
+ 'rough',
3282
+ 'clean',
3283
+ 'dirty',
3284
+ 'fresh',
3285
+ 'stale',
3286
+ 'sharp',
3287
+ 'blunt',
3288
+ 'thick',
3289
+ 'thin',
3290
+ 'wide',
3291
+ 'narrow',
3292
+ 'deep',
3293
+ 'shallow',
3294
+ 'mighty',
3295
+ 'gentle',
3296
+ 'fierce',
3297
+ 'vibrant',
3298
+ 'dusty',
3299
+ 'golden',
3300
+ 'silver',
3301
+ 'frozen',
3302
+ 'burning',
3303
+ 'ancient',
3304
+ 'modern',
3305
+ 'hidden',
3306
+ 'lost',
3307
+ 'found',
3308
+ 'magic',
3309
+ 'mystic',
3310
+ 'cosmic',
3311
+ 'stellar',
3312
+ 'lunar',
3313
+ 'solar',
3314
+ 'misty',
3315
+ 'foggy',
3316
+ 'stormy',
3317
+ 'sunny',
3318
+ 'windy',
3319
+ 'quiet',
3320
+ 'noisy',
3321
+ 'peaceful',
3322
+ 'busy',
3323
+ 'empty',
3324
+ 'full',
3325
+ 'round',
3326
+ 'square',
3327
+ 'flat',
3328
+ 'curved',
3329
+ 'tiny',
3330
+ 'huge',
3331
+ 'giant',
3332
+ 'little',
3333
+ 'short',
3334
+ 'long',
3335
+ 'near',
3336
+ 'distant',
3337
+ 'inner',
3338
+ 'outer',
3339
+ 'patient',
3340
+ 'steady',
3341
+ 'noble',
3342
+ 'pure',
3343
+ 'graceful',
3344
+ 'honest',
3345
+ 'simple',
3346
+ 'complex',
3347
+ 'active',
3348
+ 'passive',
3349
+ 'vivid',
3350
+ 'pale',
3351
+ 'loyal',
3352
+ 'true',
3353
+ 'false',
3354
+ 'fair',
3355
+ 'clear',
3356
+ 'murky',
3357
+ 'vast',
3358
+ 'slick',
3359
+ 'slippery',
3360
+ 'sticky',
3361
+ 'dull',
3362
+ 'keen',
3363
+ 'broad',
3364
+ 'slim',
3365
+ 'slender',
3366
+ 'fat',
3367
+ 'lean',
3368
+ 'stiff',
3369
+ 'flexible',
3370
+ 'rigid',
3371
+ 'elastic',
3372
+ 'tough',
3373
+ 'brittle',
3374
+ 'fragile',
3375
+ 'solid',
3376
+ 'liquid',
3377
+ 'gaseous',
3378
+ 'airy',
3379
+ 'weighty',
3380
+ 'buoyant',
3381
+ 'dense',
3382
+ 'sparse',
3383
+ 'hollow',
3384
+ 'stuffed',
3385
+ 'crowded',
3386
+ 'lonely',
3387
+ 'social',
3388
+ 'private',
3389
+ 'public',
3390
+ 'secret',
3391
+ 'famous',
3392
+ 'certain',
3393
+ 'vague',
3394
+ 'plain',
3395
+ 'easy',
3396
+ 'tame',
3397
+ 'mild',
3398
+ 'hot',
3399
+ 'cool',
3400
+ 'dry',
3401
+ 'wet',
3402
+ 'damp',
3403
+ 'moist',
3404
+ 'soaked',
3405
+ 'parched',
3406
+ 'hungry',
3407
+ 'thirsty',
3408
+ 'sleepy',
3409
+ 'awake',
3410
+ 'tired',
3411
+ 'lazy',
3412
+ 'idle',
3413
+ 'swift',
3414
+ 'rapid',
3415
+ 'unstable',
3416
+ 'shaky',
3417
+ 'firm',
3418
+ 'bold',
3419
+ 'timid',
3420
+ 'brave',
3421
+ 'cowardly',
3422
+ 'smart',
3423
+ 'dumb',
3424
+ 'foolish',
3425
+ 'mean',
3426
+ 'rude',
3427
+ 'tasty',
3428
+ 'bland',
3429
+ 'arctic',
3430
+ 'tropical',
3431
+ 'deserted',
3432
+ 'urban',
3433
+ 'rural',
3434
+ 'local',
3435
+ 'global',
3436
+ 'digital',
3437
+ 'analog',
3438
+ 'virtual',
3439
+ 'real',
3440
+ 'fake',
3441
+ 'natural',
3442
+ 'artificial',
3443
+ 'living',
3444
+ 'dead',
3445
+ 'broken',
3446
+ 'fixed',
3447
+ 'new',
3448
+ 'worn',
3449
+ 'neat',
3450
+ 'messy',
3451
+ 'brave',
3452
+ 'fearful',
3453
+ 'proud',
3454
+ 'humble',
3455
+ 'greedy',
3456
+ 'generous',
3457
+ 'calm',
3458
+ 'angry',
3459
+ 'happy',
3460
+ 'sad',
3461
+ 'excited',
3462
+ 'bored',
3463
+ 'strange',
3464
+ 'normal',
3465
+ 'odd',
3466
+ 'even',
3467
+ 'rare',
3468
+ 'common',
3469
+ 'unique',
3470
+ 'plain',
3471
+ 'fancy',
3472
+ 'basic',
3473
+ 'prime',
3474
+ 'super',
3475
+ 'mega',
3476
+ 'ultra',
3477
+ 'micro',
3478
+ 'nano',
3479
+ 'macro',
3480
+ 'mini',
3481
+ ];
3482
+ const NOUNS = [
3483
+ 'apple',
3484
+ 'sky',
3485
+ 'tree',
3486
+ 'fox',
3487
+ 'cat',
3488
+ 'bird',
3489
+ 'dog',
3490
+ 'river',
3491
+ 'mountain',
3492
+ 'forest',
3493
+ 'ocean',
3494
+ 'star',
3495
+ 'moon',
3496
+ 'sun',
3497
+ 'cloud',
3498
+ 'flower',
3499
+ 'leaf',
3500
+ 'stone',
3501
+ 'wind',
3502
+ 'rain',
3503
+ 'fire',
3504
+ 'ice',
3505
+ 'book',
3506
+ 'dream',
3507
+ 'song',
3508
+ 'road',
3509
+ 'gate',
3510
+ 'key',
3511
+ 'lamp',
3512
+ 'map',
3513
+ 'house',
3514
+ 'city',
3515
+ 'bridge',
3516
+ 'field',
3517
+ 'garden',
3518
+ 'lake',
3519
+ 'beach',
3520
+ 'island',
3521
+ 'valley',
3522
+ 'desert',
3523
+ 'world',
3524
+ 'spirit',
3525
+ 'heart',
3526
+ 'mind',
3527
+ 'soul',
3528
+ 'life',
3529
+ 'time',
3530
+ 'space',
3531
+ 'light',
3532
+ 'shadow',
3533
+ 'sound',
3534
+ 'music',
3535
+ 'voice',
3536
+ 'word',
3537
+ 'page',
3538
+ 'story',
3539
+ 'pearl',
3540
+ 'gold',
3541
+ 'silver',
3542
+ 'crystal',
3543
+ 'diamond',
3544
+ 'emerald',
3545
+ 'ruby',
3546
+ 'path',
3547
+ 'trail',
3548
+ 'peak',
3549
+ 'shore',
3550
+ 'wave',
3551
+ 'tide',
3552
+ 'flame',
3553
+ 'spark',
3554
+ 'beam',
3555
+ 'ray',
3556
+ 'seed',
3557
+ 'root',
3558
+ 'branch',
3559
+ 'bloom',
3560
+ 'thorn',
3561
+ 'bark',
3562
+ 'shell',
3563
+ 'feather',
3564
+ 'wing',
3565
+ 'claw',
3566
+ 'paw',
3567
+ 'nest',
3568
+ 'cave',
3569
+ 'grove',
3570
+ 'tower',
3571
+ 'castle',
3572
+ 'crown',
3573
+ 'sword',
3574
+ 'shield',
3575
+ 'coin',
3576
+ 'gem',
3577
+ 'ring',
3578
+ 'bell',
3579
+ 'clock',
3580
+ 'compass',
3581
+ 'anchor',
3582
+ 'torch',
3583
+ 'flute',
3584
+ 'harp',
3585
+ 'drum',
3586
+ 'lens',
3587
+ 'glass',
3588
+ 'sand',
3589
+ 'dust',
3590
+ 'mist',
3591
+ 'dew',
3592
+ 'dawn',
3593
+ 'dusk',
3594
+ 'night',
3595
+ 'day',
3596
+ 'year',
3597
+ 'age',
3598
+ 'bolt',
3599
+ 'drop',
3600
+ 'storm',
3601
+ 'snow',
3602
+ 'hail',
3603
+ 'fog',
3604
+ 'smoke',
3605
+ 'vapor',
3606
+ 'gas',
3607
+ 'fluid',
3608
+ 'liquid',
3609
+ 'solid',
3610
+ 'metal',
3611
+ 'rock',
3612
+ 'dirt',
3613
+ 'clay',
3614
+ 'sand',
3615
+ 'salt',
3616
+ 'sugar',
3617
+ 'wood',
3618
+ 'bone',
3619
+ 'skin',
3620
+ 'flesh',
3621
+ 'blood',
3622
+ 'cell',
3623
+ 'atom',
3624
+ 'pulse',
3625
+ 'beat',
3626
+ 'breath',
3627
+ 'sigh',
3628
+ 'name',
3629
+ 'echo',
3630
+ 'image',
3631
+ 'vision',
3632
+ 'thought',
3633
+ 'idea',
3634
+ 'plan',
3635
+ 'goal',
3636
+ 'wish',
3637
+ 'hope',
3638
+ 'fear',
3639
+ 'joy',
3640
+ 'love',
3641
+ 'hate',
3642
+ 'will',
3643
+ 'power',
3644
+ 'force',
3645
+ 'energy',
3646
+ 'motion',
3647
+ 'speed',
3648
+ 'place',
3649
+ 'point',
3650
+ 'line',
3651
+ 'shape',
3652
+ 'form',
3653
+ 'size',
3654
+ 'mass',
3655
+ 'weight',
3656
+ 'heat',
3657
+ 'cold',
3658
+ 'color',
3659
+ 'tone',
3660
+ 'pitch',
3661
+ 'rhythm',
3662
+ 'vibe',
3663
+ 'mood',
3664
+ 'state',
3665
+ 'way',
3666
+ 'step',
3667
+ 'move',
3668
+ 'turn',
3669
+ 'fall',
3670
+ 'rise',
3671
+ 'jump',
3672
+ 'leap',
3673
+ 'run',
3674
+ 'walk',
3675
+ 'rest',
3676
+ 'stay',
3677
+ 'trip',
3678
+ 'quest',
3679
+ 'task',
3680
+ 'work',
3681
+ 'job',
3682
+ 'play',
3683
+ 'game',
3684
+ 'sport',
3685
+ 'art',
3686
+ 'craft',
3687
+ 'tool',
3688
+ 'ship',
3689
+ 'boat',
3690
+ 'car',
3691
+ 'bike',
3692
+ 'train',
3693
+ 'plane',
3694
+ 'hub',
3695
+ 'base',
3696
+ 'core',
3697
+ 'node',
3698
+ 'link',
3699
+ 'net',
3700
+ 'web',
3701
+ 'box',
3702
+ 'bag',
3703
+ 'jar',
3704
+ 'cup',
3705
+ 'bowl',
3706
+ 'plate',
3707
+ 'dish',
3708
+ 'spoon',
3709
+ 'fork',
3710
+ 'knife',
3711
+ 'pan',
3712
+ 'pot',
3713
+ 'bed',
3714
+ 'desk',
3715
+ 'chair',
3716
+ 'door',
3717
+ 'wall',
3718
+ 'roof',
3719
+ 'floor',
3720
+ ];
3721
+ const VERBS = [
3722
+ 'jumping',
3723
+ 'dancing',
3724
+ 'flying',
3725
+ 'running',
3726
+ 'singing',
3727
+ 'shining',
3728
+ 'growing',
3729
+ 'flowing',
3730
+ 'falling',
3731
+ 'rising',
3732
+ 'sleeping',
3733
+ 'walking',
3734
+ 'talking',
3735
+ 'thinking',
3736
+ 'dreaming',
3737
+ 'looking',
3738
+ 'feeling',
3739
+ 'smiling',
3740
+ 'laughing',
3741
+ 'playing',
3742
+ 'working',
3743
+ 'resting',
3744
+ 'moving',
3745
+ 'staying',
3746
+ 'beaming',
3747
+ 'glowing',
3748
+ 'sparkling',
3749
+ 'waiting',
3750
+ 'waking',
3751
+ 'drifting',
3752
+ 'spinning',
3753
+ 'gliding',
3754
+ 'soaring',
3755
+ 'floating',
3756
+ 'whispering',
3757
+ 'calling',
3758
+ 'seeking',
3759
+ 'finding',
3760
+ 'giving',
3761
+ 'taking',
3762
+ 'weaving',
3763
+ 'building',
3764
+ 'creating',
3765
+ 'burning',
3766
+ 'freezing',
3767
+ 'melting',
3768
+ 'breathing',
3769
+ 'pulsing',
3770
+ 'beating',
3771
+ 'living',
3772
+ 'learning',
3773
+ 'knowing',
3774
+ 'hidden',
3775
+ 'shown',
3776
+ 'broken',
3777
+ 'mended',
3778
+ 'lost',
3779
+ 'found',
3780
+ 'starting',
3781
+ 'ending',
3782
+ 'climbing',
3783
+ 'diving',
3784
+ 'swimming',
3785
+ 'sailing',
3786
+ 'rolling',
3787
+ 'shaking',
3788
+ 'turning',
3789
+ 'shifting',
3790
+ 'changing',
3791
+ 'fading',
3792
+ 'dying',
3793
+ 'born',
3794
+ 'humming',
3795
+ 'crying',
3796
+ 'racing',
3797
+ 'creeping',
3798
+ 'hiding',
3799
+ 'watching',
3800
+ 'hearing',
3801
+ 'sensing',
3802
+ 'longing',
3803
+ 'hoping',
3804
+ 'loving',
3805
+ 'fearing',
3806
+ 'wondering',
3807
+ 'wandering',
3808
+ 'traveling',
3809
+ 'crossing',
3810
+ 'meeting',
3811
+ 'parting',
3812
+ 'keeping',
3813
+ 'sharing',
3814
+ 'sparking',
3815
+ 'flaming',
3816
+ 'healing',
3817
+ 'solving',
3818
+ 'opening',
3819
+ 'closing',
3820
+ 'lifting',
3821
+ 'pulling',
3822
+ 'pushing',
3823
+ 'holding',
3824
+ 'tossing',
3825
+ 'throwing',
3826
+ 'catching',
3827
+ 'fixing',
3828
+ 'making',
3829
+ 'doing',
3830
+ 'seeing',
3831
+ 'tasting',
3832
+ 'smelling',
3833
+ 'touching',
3834
+ 'pacing',
3835
+ 'hurrying',
3836
+ 'pausing',
3837
+ 'going',
3838
+ 'coming',
3839
+ 'leaving',
3840
+ 'acting',
3841
+ 'being',
3842
+ 'seeming',
3843
+ 'shrinking',
3844
+ 'widening',
3845
+ 'narrowing',
3846
+ 'heating',
3847
+ 'cooling',
3848
+ 'drying',
3849
+ 'wetting',
3850
+ 'filling',
3851
+ 'filling',
3852
+ 'emptying',
3853
+ 'letting',
3854
+ 'gaining',
3855
+ 'winning',
3856
+ 'failing',
3857
+ 'trying',
3858
+ 'using',
3859
+ 'getting',
3860
+ 'showing',
3861
+ 'hiding',
3862
+ 'breaking',
3863
+ 'fixing',
3864
+ 'saving',
3865
+ 'spending',
3866
+ 'buying',
3867
+ 'selling',
3868
+ 'paying',
3869
+ 'costing',
3870
+ 'reaching',
3871
+ 'missing',
3872
+ 'hitting',
3873
+ 'striking',
3874
+ 'leading',
3875
+ 'following',
3876
+ 'helping',
3877
+ 'serving',
3878
+ 'teaching',
3879
+ 'training',
3880
+ 'coding',
3881
+ 'writing',
3882
+ 'reading',
3883
+ 'drawing',
3884
+ 'painting',
3885
+ 'crafting',
3886
+ 'shaping',
3887
+ 'forming',
3888
+ 'joining',
3889
+ 'splitting',
3890
+ 'sharing',
3891
+ 'bonding',
3892
+ 'healing',
3893
+ 'harming',
3894
+ 'protecting',
3895
+ 'fighting',
3896
+ 'defending',
3897
+ 'attacking',
3898
+ 'escaping',
3899
+ 'catching',
3900
+ 'trapping',
3901
+ 'freeing',
3902
+ 'binding',
3903
+ 'weaving',
3904
+ 'spinning',
3905
+ ];
3906
+
3215
3907
  /**
3216
3908
  * Normalizes a text string to SCREAMING_CASE (all uppercase with underscores).
3217
3909
  *
@@ -3311,6 +4003,95 @@ function normalizeTo_snake_case(text) {
3311
4003
  return normalizeTo_SCREAMING_CASE(text).toLowerCase();
3312
4004
  }
3313
4005
 
4006
+ /**
4007
+ * Removes quotes and optional introduce text from a string
4008
+ *
4009
+ * Tip: This is very useful for post-processing of the result of the LLM model
4010
+ * Note: This function trims the text and removes whole introduce sentence if it is present
4011
+ * Note: There are two similar functions:
4012
+ * - `removeQuotes` which removes only bounding quotes
4013
+ * - `unwrapResult` which removes whole introduce sentence
4014
+ *
4015
+ * @param text optionally quoted text
4016
+ * @returns text without quotes
4017
+ * @public exported from `@promptbook/utils`
4018
+ */
4019
+ function unwrapResult(text, options) {
4020
+ const { isTrimmed = true, isIntroduceSentenceRemoved = true } = options || {};
4021
+ let trimmedText = text;
4022
+ // Remove leading and trailing spaces and newlines
4023
+ if (isTrimmed) {
4024
+ trimmedText = spaceTrim$1(trimmedText);
4025
+ }
4026
+ let processedText = trimmedText;
4027
+ // Check for markdown code block
4028
+ const codeBlockRegex = /^```[a-z]*\n([\s\S]*?)\n```\s*$/;
4029
+ const codeBlockMatch = processedText.match(codeBlockRegex);
4030
+ if (codeBlockMatch && codeBlockMatch[1] !== undefined) {
4031
+ // Check if there's only one code block
4032
+ const codeBlockCount = (processedText.match(/```/g) || []).length / 2;
4033
+ if (codeBlockCount === 1) {
4034
+ return unwrapResult(codeBlockMatch[1], { isTrimmed: false, isIntroduceSentenceRemoved: false });
4035
+ }
4036
+ }
4037
+ if (isIntroduceSentenceRemoved) {
4038
+ const introduceSentenceRegex = /^[a-zěščřžýáíéúů:\s]*:\s*/i;
4039
+ if (introduceSentenceRegex.test(text)) {
4040
+ // Remove the introduce sentence and quotes by replacing it with an empty string
4041
+ processedText = processedText.replace(introduceSentenceRegex, '');
4042
+ }
4043
+ processedText = spaceTrim$1(processedText);
4044
+ // Check again for code block after removing introduce sentence
4045
+ const codeBlockMatch2 = processedText.match(codeBlockRegex);
4046
+ if (codeBlockMatch2 && codeBlockMatch2[1] !== undefined) {
4047
+ const codeBlockCount = (processedText.match(/```/g) || []).length / 2;
4048
+ if (codeBlockCount === 1) {
4049
+ return unwrapResult(codeBlockMatch2[1], { isTrimmed: false, isIntroduceSentenceRemoved: false });
4050
+ }
4051
+ }
4052
+ }
4053
+ if (processedText.length < 3) {
4054
+ return trimmedText;
4055
+ }
4056
+ if (processedText.includes('\n')) {
4057
+ return trimmedText;
4058
+ }
4059
+ // Remove the quotes by extracting the substring without the first and last characters
4060
+ const unquotedText = processedText.slice(1, -1);
4061
+ // Check if the text starts and ends with quotes
4062
+ if ([
4063
+ ['"', '"'],
4064
+ ["'", "'"],
4065
+ ['`', '`'],
4066
+ ['*', '*'],
4067
+ ['_', '_'],
4068
+ ['„', '“'],
4069
+ ['«', '»'] /* <- QUOTES to config */,
4070
+ ].some(([startQuote, endQuote]) => {
4071
+ if (!processedText.startsWith(startQuote)) {
4072
+ return false;
4073
+ }
4074
+ if (!processedText.endsWith(endQuote)) {
4075
+ return false;
4076
+ }
4077
+ if (unquotedText.includes(startQuote) && !unquotedText.includes(endQuote)) {
4078
+ return false;
4079
+ }
4080
+ if (!unquotedText.includes(startQuote) && unquotedText.includes(endQuote)) {
4081
+ return false;
4082
+ }
4083
+ return true;
4084
+ })) {
4085
+ return unwrapResult(unquotedText, { isTrimmed: false, isIntroduceSentenceRemoved: false });
4086
+ }
4087
+ else {
4088
+ return processedText;
4089
+ }
4090
+ }
4091
+ /**
4092
+ * TODO: [🧠] Should this also unwrap the (parenthesis)
4093
+ */
4094
+
3314
4095
  /**
3315
4096
  * Parses the task and returns the list of all parameter names
3316
4097
  *
@@ -6905,6 +7686,46 @@ class UseMcpCommitmentDefinition extends BaseCommitmentDefinition {
6905
7686
  * Note: [💞] Ignore a discrepancy between file name and entity name
6906
7687
  */
6907
7688
 
7689
+ /**
7690
+ * A search engine implementation that uses the SerpApi to fetch Google search results.
7691
+ *
7692
+ * @private <- TODO: !!!! Export via some package
7693
+ */
7694
+ class SerpSearchEngine {
7695
+ get title() {
7696
+ return 'SerpApi Search Engine';
7697
+ }
7698
+ get description() {
7699
+ return 'Search engine that uses SerpApi to fetch Google search results';
7700
+ }
7701
+ checkConfiguration() {
7702
+ if (!process.env.SERP_API_KEY) {
7703
+ throw new Error('SERP_API_KEY is not configured');
7704
+ }
7705
+ }
7706
+ async search(query) {
7707
+ const apiKey = process.env.SERP_API_KEY;
7708
+ if (!apiKey) {
7709
+ throw new Error('SERP_API_KEY is not configured');
7710
+ }
7711
+ const url = new URL('https://serpapi.com/search');
7712
+ url.searchParams.set('q', query);
7713
+ url.searchParams.set('api_key', apiKey);
7714
+ url.searchParams.set('engine', 'google');
7715
+ const response = await fetch(url.toString());
7716
+ if (!response.ok) {
7717
+ const body = await response.text();
7718
+ throw new Error(`SerpApi failed with status ${response.status}: ${response.statusText}\n${body}`);
7719
+ }
7720
+ const data = (await response.json());
7721
+ return (data.organic_results || []).map((item) => ({
7722
+ title: item.title,
7723
+ url: item.link,
7724
+ snippet: item.snippet || '',
7725
+ }));
7726
+ }
7727
+ }
7728
+
6908
7729
  /**
6909
7730
  * USE SEARCH ENGINE commitment definition
6910
7731
  *
@@ -6981,18 +7802,13 @@ class UseSearchEngineCommitmentDefinition extends BaseCommitmentDefinition {
6981
7802
  ? existingTools
6982
7803
  : [
6983
7804
  ...existingTools,
6984
- { type: 'web_search' },
6985
- // <- Note: [🔰] This is just using simple native search tool by OpenAI @see https://platform.openai.com/docs/guides/tools-web-search
6986
- // In future we will use proper MCP search tool:
6987
- /*
6988
-
6989
7805
  {
6990
7806
  name: 'web_search',
6991
- description: spaceTrim(`
6992
- Search the internet for information.
6993
- Use this tool when you need to find up-to-date information or facts that you don't know.
6994
- ${!content ? '' : `Search scope / instructions: ${content}`}
6995
- `),
7807
+ description: spaceTrim$1(`
7808
+ Search the internet for information.
7809
+ Use this tool when you need to find up-to-date information or facts that you don't know.
7810
+ ${!content ? '' : `Search scope / instructions: ${content}`}
7811
+ `),
6996
7812
  parameters: {
6997
7813
  type: 'object',
6998
7814
  properties: {
@@ -7004,7 +7820,6 @@ class UseSearchEngineCommitmentDefinition extends BaseCommitmentDefinition {
7004
7820
  required: ['query'],
7005
7821
  },
7006
7822
  },
7007
- */
7008
7823
  ];
7009
7824
  // Return requirements with updated tools and metadata
7010
7825
  return {
@@ -7016,6 +7831,33 @@ class UseSearchEngineCommitmentDefinition extends BaseCommitmentDefinition {
7016
7831
  },
7017
7832
  };
7018
7833
  }
7834
+ /**
7835
+ * Gets the `web_search` tool function implementation.
7836
+ */
7837
+ getToolFunctions() {
7838
+ return {
7839
+ async web_search(args) {
7840
+ console.log('!!!! [Tool] web_search called', { args });
7841
+ const { query } = args;
7842
+ if (!query) {
7843
+ throw new Error('Search query is required');
7844
+ }
7845
+ const searchEngine = new SerpSearchEngine();
7846
+ const results = await searchEngine.search(query);
7847
+ return spaceTrim$1((block) => `
7848
+ Search results for "${query}":
7849
+
7850
+ ${block(results
7851
+ .map((result) => spaceTrim$1(`
7852
+ - **${result.title}**
7853
+ ${result.url}
7854
+ ${result.snippet}
7855
+ `))
7856
+ .join('\n\n'))}
7857
+ `);
7858
+ },
7859
+ };
7860
+ }
7019
7861
  }
7020
7862
  /**
7021
7863
  * Note: [💞] Ignore a discrepancy between file name and entity name
@@ -7259,6 +8101,7 @@ const COMMITMENT_REGISTRY = [
7259
8101
  new NoteCommitmentDefinition('NOTES'),
7260
8102
  new NoteCommitmentDefinition('COMMENT'),
7261
8103
  new NoteCommitmentDefinition('NONCE'),
8104
+ new NoteCommitmentDefinition('TODO'),
7262
8105
  new GoalCommitmentDefinition('GOAL'),
7263
8106
  new GoalCommitmentDefinition('GOALS'),
7264
8107
  new InitialMessageCommitmentDefinition(),
@@ -18809,8 +19652,7 @@ AgentLlmExecutionTools.assistantCache = new Map();
18809
19652
  * TODO: [🧠] Adding parameter substitution support (here or should be responsibility of the underlying LLM Tools)
18810
19653
  */
18811
19654
 
18812
- var _Agent_instances, _Agent_selfLearnSamples;
18813
- // !!!!! import { RemoteAgent } from './RemoteAgent'; // <- [💞] <- !!!!!
19655
+ var _Agent_instances, _Agent_selfLearnNonce, _Agent_selfLearnSamples, _Agent_selfLearnTeacher;
18814
19656
  /**
18815
19657
  * Represents one AI Agent
18816
19658
  *
@@ -18880,6 +19722,7 @@ class Agent extends AgentLlmExecutionTools {
18880
19722
  this.meta = {};
18881
19723
  // TODO: [🐱‍🚀] Add `Agent` simple "mocked" learning by appending to agent source
18882
19724
  // TODO: [🐱‍🚀] Add `Agent` learning by promptbookAgent
19725
+ this.teacherAgent = options.teacherAgent;
18883
19726
  this.agentSource = agentSource;
18884
19727
  this.agentSource.subscribe((source) => {
18885
19728
  this.updateAgentSource(source);
@@ -18950,26 +19793,42 @@ class Agent extends AgentLlmExecutionTools {
18950
19793
  if ((_a = modelRequirements.metadata) === null || _a === void 0 ? void 0 : _a.isClosed) {
18951
19794
  return result;
18952
19795
  }
18953
- // TODO: !!!!! Is this timed properly?
19796
+ // TODO: !!!!! Return the answer and do the learning asynchronously
19797
+ // Note: [0] Asynchronously add nonce
19798
+ if (just(false)) {
19799
+ await __classPrivateFieldGet(this, _Agent_instances, "m", _Agent_selfLearnNonce).call(this);
19800
+ }
18954
19801
  // Note: [1] Do the append of the samples
18955
- __classPrivateFieldGet(this, _Agent_instances, "m", _Agent_selfLearnSamples).call(this, prompt, result);
18956
- /*
18957
- !!!!!
19802
+ await __classPrivateFieldGet(this, _Agent_instances, "m", _Agent_selfLearnSamples).call(this, prompt, result);
18958
19803
  // Note: [2] Asynchronously call the teacher agent and invoke the silver link. When the teacher fails, keep just the samples
18959
- this.#selfLearnTeacher(prompt, result).catch((error) => {
18960
- if (this.options.isVerbose) {
18961
- console.error('Failed to self-learn from teacher agent', error);
18962
- }
19804
+ await __classPrivateFieldGet(this, _Agent_instances, "m", _Agent_selfLearnTeacher).call(this, prompt, result).catch((error) => {
19805
+ // !!!!! if (this.options.isVerbose) {
19806
+ console.error(colors.bgCyan('[Self-learning]') + colors.red(' Failed to learn from teacher agent'));
19807
+ console.error(error);
19808
+ // }
18963
19809
  });
18964
- */
18965
19810
  return result;
18966
19811
  }
18967
19812
  }
18968
- _Agent_instances = new WeakSet(), _Agent_selfLearnSamples = function _Agent_selfLearnSamples(prompt, result) {
19813
+ _Agent_instances = new WeakSet(), _Agent_selfLearnNonce =
19814
+ /**
19815
+ * Self-learning Step 0: Asynchronously with random timing add nonce to the agent source
19816
+ */
19817
+ async function _Agent_selfLearnNonce() {
19818
+ await forTime(Math.random() * 5000);
19819
+ // <- TODO: [🕓] `await forRandom(...)`
19820
+ console.info(colors.bgCyan('[Self-learning]') + colors.cyan(' Nonce'));
19821
+ const nonce = `NONCE ${await linguisticHash(Math.random().toString())}`;
19822
+ // Append to the current source
19823
+ const currentSource = this.agentSource.value;
19824
+ const newSource = padBook(validateBook(spaceTrim$2(currentSource) + '\n\n---\n\n' + nonce));
19825
+ // <- TODO: [🈲] Use some object-based way how to append on book (with sections `---`)
19826
+ // Update the source (which will trigger the subscription and update the underlying tools)
19827
+ this.agentSource.next(newSource);
19828
+ }, _Agent_selfLearnSamples = function _Agent_selfLearnSamples(prompt, result) {
19829
+ console.info(colors.bgCyan('[Self-learning]') + colors.cyan(' Sampling'));
18969
19830
  const learningExample = spaceTrim$2((block) => `
18970
19831
 
18971
- ---
18972
-
18973
19832
  USER MESSAGE
18974
19833
  ${block(prompt.content)}
18975
19834
 
@@ -18979,9 +19838,80 @@ _Agent_instances = new WeakSet(), _Agent_selfLearnSamples = function _Agent_self
18979
19838
  `);
18980
19839
  // Append to the current source
18981
19840
  const currentSource = this.agentSource.value;
18982
- const newSource = padBook(validateBook(spaceTrim$2(currentSource) + '\n\n' + learningExample));
19841
+ const newSource = padBook(validateBook(spaceTrim$2(currentSource) + '\n\n---\n\n' + learningExample));
19842
+ // <- TODO: [🈲] Use some object-based way how to append on book (with sections `---`)
18983
19843
  // Update the source (which will trigger the subscription and update the underlying tools)
18984
19844
  this.agentSource.next(newSource);
19845
+ }, _Agent_selfLearnTeacher =
19846
+ /**
19847
+ * Self-learning Step 2: Asynchronously call the teacher agent and invoke the silver link
19848
+ */
19849
+ async function _Agent_selfLearnTeacher(prompt, result) {
19850
+ // [1] Call the teacher agent // <- !!!!! Emojis
19851
+ if (this.teacherAgent === null) {
19852
+ return;
19853
+ }
19854
+ console.info(colors.bgCyan('[Self-learning]') + colors.cyan(' Teacher'));
19855
+ const teacherResult = await this.teacherAgent.callChatModel({
19856
+ title: 'Self-learning',
19857
+ modelRequirements: {
19858
+ modelVariant: 'CHAT',
19859
+ },
19860
+ // TODO: !!!! Use prompt notation
19861
+ content: spaceTrim$2((block) => `
19862
+
19863
+ You are a teacher agent helping another agent to learn from its interactions.
19864
+
19865
+ Here is your current client which you are teaching:
19866
+
19867
+ \`\`\`book
19868
+ ${block(this.agentSource.value)}
19869
+ \`\`\`
19870
+
19871
+ **And here is the latest interaction:**
19872
+
19873
+ **User:**
19874
+ ${block(prompt.content)}
19875
+
19876
+ **Agent:**
19877
+ ${block(result.content)}
19878
+
19879
+
19880
+ **Rules:**
19881
+
19882
+ - Decide what the agent should learn from this interaction.
19883
+ - Append new commitments at the end of the agent source.
19884
+ - Do not modify the current agent source, just return new commitments (KNOWLEDGE, RULE, etc.).
19885
+ - If there is nothing new to learn, return empty book code block
19886
+ - Wrap the commitments in a book code block.
19887
+ - Do not explain anything, just return the commitments wrapped in a book code block.
19888
+ - Write the learned commitments in the same style and language as in the original agent source.
19889
+
19890
+
19891
+ This is how book code block looks like:
19892
+
19893
+ \`\`\`book
19894
+ KNOWLEDGE The sky is blue.
19895
+ RULE Always be polite.
19896
+ \`\`\`
19897
+ `),
19898
+ // pipelineUrl: 'https://github.com/webgptorg/promptbook/blob/main/prompts/self-learning.ptbk.md',
19899
+ // <- TODO: !!!! Remove and `pipelineUrl` for agent purposes
19900
+ parameters: {},
19901
+ });
19902
+ console.log('!!!! teacherResult', teacherResult);
19903
+ const teacherCommitments = unwrapResult(teacherResult.content);
19904
+ if (teacherCommitments === '') {
19905
+ console.info(colors.bgCyan('[Self-learning]') +
19906
+ colors.cyan(' Teacher agent did not provide new commitments to learn'));
19907
+ return;
19908
+ }
19909
+ // [2] Append to the current source
19910
+ const currentSource = this.agentSource.value;
19911
+ const newSource = padBook(validateBook(spaceTrim$2(currentSource) + '\n\n' + teacherCommitments));
19912
+ // <- TODO: [🈲] Use some object-based way how to append on book (with sections `---`)
19913
+ // [3] Update the source
19914
+ this.agentSource.next(newSource);
18985
19915
  };
18986
19916
  /**
18987
19917
  * TODO: [🧠][😰]Agent is not working with the parameters, should it be?
@@ -19001,10 +19931,25 @@ _Agent_instances = new WeakSet(), _Agent_selfLearnSamples = function _Agent_self
19001
19931
  */
19002
19932
  class RemoteAgent extends Agent {
19003
19933
  static async connect(options) {
19004
- console.log('[🐱‍🚀]', `${options.agentUrl}/api/profile`);
19005
- const profileResponse = await fetch(`${options.agentUrl}/api/profile`);
19934
+ const agentProfileUrl = `${options.agentUrl}/api/profile`;
19935
+ const profileResponse = await fetch(agentProfileUrl);
19006
19936
  // <- TODO: [🐱‍🚀] What about closed-source agents?
19007
19937
  // <- TODO: [🐱‍🚀] Maybe use promptbookFetch
19938
+ if (!profileResponse.ok) {
19939
+ throw new Error(spaceTrim$2((block) => `
19940
+ Failed to fetch remote agent profile:
19941
+
19942
+ Agent URL:
19943
+ ${options.agentUrl}
19944
+
19945
+ Agent Profile URL:
19946
+ ${agentProfileUrl}
19947
+
19948
+ Http Error:
19949
+ ${block(profileResponse.statusText)}
19950
+
19951
+ `));
19952
+ }
19008
19953
  const profile = await profileResponse.json();
19009
19954
  // Note: We are creating dummy agent source because we don't have the source from the remote agent
19010
19955
  // But we populate the metadata from the profile
@@ -19031,6 +19976,7 @@ class RemoteAgent extends Agent {
19031
19976
  */
19032
19977
  },
19033
19978
  agentSource,
19979
+ teacherAgent: null, // <- Note:
19034
19980
  });
19035
19981
  remoteAgent._remoteAgentName = profile.agentName;
19036
19982
  remoteAgent._remoteAgentHash = profile.agentHash;