@peam-ai/server 0.1.1
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/LICENSE +201 -0
- package/README.md +11 -0
- package/dist/index.d.mts +74 -0
- package/dist/index.d.ts +74 -0
- package/dist/index.js +206 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +169 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +49 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { SearchEngine } from '@peam-ai/search';
|
|
2
|
+
import { LanguageModel, UIMessage } from 'ai';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Metadata about the current page the user is on.
|
|
6
|
+
*/
|
|
7
|
+
interface CurrentPageMetadata {
|
|
8
|
+
/**
|
|
9
|
+
* The title of the page (optional).
|
|
10
|
+
*/
|
|
11
|
+
title?: string;
|
|
12
|
+
/**
|
|
13
|
+
* The origin of the page.
|
|
14
|
+
*/
|
|
15
|
+
origin: string;
|
|
16
|
+
/**
|
|
17
|
+
* The path of the page (e.g., "/about").
|
|
18
|
+
*/
|
|
19
|
+
path: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Function to retrieve the search engine instance.
|
|
23
|
+
*/
|
|
24
|
+
type GetSearchEngine = () => Promise<SearchEngine | undefined>;
|
|
25
|
+
/**
|
|
26
|
+
* Options for creating a chat handler.
|
|
27
|
+
*/
|
|
28
|
+
interface CreateHandlerOptions {
|
|
29
|
+
/**
|
|
30
|
+
* The language model to use for generating responses and summarization.
|
|
31
|
+
* Defaults to OpenAI GPT-4o if not provided.
|
|
32
|
+
*/
|
|
33
|
+
model?: LanguageModel;
|
|
34
|
+
/**
|
|
35
|
+
* Function to retrieve the search engine instance.
|
|
36
|
+
* If not provided, the handler will return an error when no search engine is available.
|
|
37
|
+
*/
|
|
38
|
+
getSearchEngine?: GetSearchEngine;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Request body structure for chat API.
|
|
42
|
+
*/
|
|
43
|
+
interface ChatRequestBody {
|
|
44
|
+
mode?: 'chat';
|
|
45
|
+
messages: UIMessage[];
|
|
46
|
+
summary?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Creates a HTTP handler for the chat API.
|
|
51
|
+
* This handler processes incoming chat messages and streams responses back to the client.
|
|
52
|
+
*
|
|
53
|
+
* @param options - Configuration options for the handler
|
|
54
|
+
* @param options.model - The language model to use (default: GPT-4o)
|
|
55
|
+
* @param options.getSearchEngine - An optional function to retrieve the search engine
|
|
56
|
+
* @returns An async function that handles HTTP requests
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```typescript
|
|
60
|
+
* // Next.js
|
|
61
|
+
* import { createHandler } from 'peam/server';
|
|
62
|
+
* import { openai } from '@ai-sdk/openai';
|
|
63
|
+
*
|
|
64
|
+
* export const POST = createHandler({
|
|
65
|
+
* model: openai('gpt-4o'),
|
|
66
|
+
* getSearchEngine: async () => mySearchEngine,
|
|
67
|
+
* });
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
declare function createHandler(options?: CreateHandlerOptions): (req: Request) => Promise<Response>;
|
|
71
|
+
|
|
72
|
+
declare function getSearchEngine(): Promise<SearchEngine | undefined>;
|
|
73
|
+
|
|
74
|
+
export { type ChatRequestBody, type CreateHandlerOptions, type CurrentPageMetadata, type GetSearchEngine, createHandler, getSearchEngine };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { SearchEngine } from '@peam-ai/search';
|
|
2
|
+
import { LanguageModel, UIMessage } from 'ai';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Metadata about the current page the user is on.
|
|
6
|
+
*/
|
|
7
|
+
interface CurrentPageMetadata {
|
|
8
|
+
/**
|
|
9
|
+
* The title of the page (optional).
|
|
10
|
+
*/
|
|
11
|
+
title?: string;
|
|
12
|
+
/**
|
|
13
|
+
* The origin of the page.
|
|
14
|
+
*/
|
|
15
|
+
origin: string;
|
|
16
|
+
/**
|
|
17
|
+
* The path of the page (e.g., "/about").
|
|
18
|
+
*/
|
|
19
|
+
path: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Function to retrieve the search engine instance.
|
|
23
|
+
*/
|
|
24
|
+
type GetSearchEngine = () => Promise<SearchEngine | undefined>;
|
|
25
|
+
/**
|
|
26
|
+
* Options for creating a chat handler.
|
|
27
|
+
*/
|
|
28
|
+
interface CreateHandlerOptions {
|
|
29
|
+
/**
|
|
30
|
+
* The language model to use for generating responses and summarization.
|
|
31
|
+
* Defaults to OpenAI GPT-4o if not provided.
|
|
32
|
+
*/
|
|
33
|
+
model?: LanguageModel;
|
|
34
|
+
/**
|
|
35
|
+
* Function to retrieve the search engine instance.
|
|
36
|
+
* If not provided, the handler will return an error when no search engine is available.
|
|
37
|
+
*/
|
|
38
|
+
getSearchEngine?: GetSearchEngine;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Request body structure for chat API.
|
|
42
|
+
*/
|
|
43
|
+
interface ChatRequestBody {
|
|
44
|
+
mode?: 'chat';
|
|
45
|
+
messages: UIMessage[];
|
|
46
|
+
summary?: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Creates a HTTP handler for the chat API.
|
|
51
|
+
* This handler processes incoming chat messages and streams responses back to the client.
|
|
52
|
+
*
|
|
53
|
+
* @param options - Configuration options for the handler
|
|
54
|
+
* @param options.model - The language model to use (default: GPT-4o)
|
|
55
|
+
* @param options.getSearchEngine - An optional function to retrieve the search engine
|
|
56
|
+
* @returns An async function that handles HTTP requests
|
|
57
|
+
*
|
|
58
|
+
* @example
|
|
59
|
+
* ```typescript
|
|
60
|
+
* // Next.js
|
|
61
|
+
* import { createHandler } from 'peam/server';
|
|
62
|
+
* import { openai } from '@ai-sdk/openai';
|
|
63
|
+
*
|
|
64
|
+
* export const POST = createHandler({
|
|
65
|
+
* model: openai('gpt-4o'),
|
|
66
|
+
* getSearchEngine: async () => mySearchEngine,
|
|
67
|
+
* });
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
declare function createHandler(options?: CreateHandlerOptions): (req: Request) => Promise<Response>;
|
|
71
|
+
|
|
72
|
+
declare function getSearchEngine(): Promise<SearchEngine | undefined>;
|
|
73
|
+
|
|
74
|
+
export { type ChatRequestBody, type CreateHandlerOptions, type CurrentPageMetadata, type GetSearchEngine, createHandler, getSearchEngine };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
var __async = (__this, __arguments, generator) => {
|
|
30
|
+
return new Promise((resolve, reject) => {
|
|
31
|
+
var fulfilled = (value) => {
|
|
32
|
+
try {
|
|
33
|
+
step(generator.next(value));
|
|
34
|
+
} catch (e) {
|
|
35
|
+
reject(e);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
var rejected = (value) => {
|
|
39
|
+
try {
|
|
40
|
+
step(generator.throw(value));
|
|
41
|
+
} catch (e) {
|
|
42
|
+
reject(e);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
46
|
+
step((generator = generator.apply(__this, __arguments)).next());
|
|
47
|
+
});
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
// src/index.ts
|
|
51
|
+
var index_exports = {};
|
|
52
|
+
__export(index_exports, {
|
|
53
|
+
createHandler: () => createHandler,
|
|
54
|
+
getSearchEngine: () => getSearchEngine
|
|
55
|
+
});
|
|
56
|
+
module.exports = __toCommonJS(index_exports);
|
|
57
|
+
|
|
58
|
+
// src/createHandler.ts
|
|
59
|
+
var import_openai = require("@ai-sdk/openai");
|
|
60
|
+
var import_ai = require("@peam-ai/ai");
|
|
61
|
+
var import_logger2 = require("@peam-ai/logger");
|
|
62
|
+
var import_ai2 = require("ai");
|
|
63
|
+
|
|
64
|
+
// src/utils/getCurrentPage.ts
|
|
65
|
+
var getCurrentPage = ({
|
|
66
|
+
request,
|
|
67
|
+
message
|
|
68
|
+
}) => {
|
|
69
|
+
const messageMetadata = message.metadata;
|
|
70
|
+
const messageCurrentPage = messageMetadata.currentPage;
|
|
71
|
+
if (messageCurrentPage && messageCurrentPage.path && messageCurrentPage.origin) {
|
|
72
|
+
return {
|
|
73
|
+
title: messageCurrentPage.title,
|
|
74
|
+
origin: messageCurrentPage.origin,
|
|
75
|
+
path: messageCurrentPage.path
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
if (request.headers.has("referer")) {
|
|
80
|
+
const refererUrl = new URL(request.headers.get("referer") || "");
|
|
81
|
+
return {
|
|
82
|
+
path: refererUrl.pathname,
|
|
83
|
+
origin: refererUrl.origin
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
} catch (e) {
|
|
87
|
+
}
|
|
88
|
+
return void 0;
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// src/utils/getSearchEngine.ts
|
|
92
|
+
var import_logger = require("@peam-ai/logger");
|
|
93
|
+
var import_search = require("@peam-ai/search");
|
|
94
|
+
var log = import_logger.loggers.server;
|
|
95
|
+
var searchEngine = null;
|
|
96
|
+
function getSearchEngine() {
|
|
97
|
+
return __async(this, null, function* () {
|
|
98
|
+
var _a;
|
|
99
|
+
if (searchEngine) return searchEngine;
|
|
100
|
+
try {
|
|
101
|
+
const indexFile = (_a = yield import("peam_index/generated")) == null ? void 0 : _a.default;
|
|
102
|
+
if (!indexFile || !indexFile.data || !indexFile.keys || indexFile.keys.length === 0) {
|
|
103
|
+
log.debug("Search index not yet generated. Run build first to generate the index.");
|
|
104
|
+
return void 0;
|
|
105
|
+
}
|
|
106
|
+
searchEngine = new import_search.SearchEngine();
|
|
107
|
+
yield searchEngine.import((key) => __async(null, null, function* () {
|
|
108
|
+
return indexFile.data[key];
|
|
109
|
+
}), indexFile.keys);
|
|
110
|
+
const totalDocs = searchEngine.count();
|
|
111
|
+
log.debug("Index loaded successfully with", totalDocs, "documents");
|
|
112
|
+
return searchEngine;
|
|
113
|
+
} catch (error) {
|
|
114
|
+
log.error("Failed to load search index:", error);
|
|
115
|
+
}
|
|
116
|
+
return void 0;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// src/createHandler.ts
|
|
121
|
+
var MAX_MESSAGE_LENGTH = 3e4;
|
|
122
|
+
var log2 = import_logger2.loggers.server;
|
|
123
|
+
function createHandler(options = {}) {
|
|
124
|
+
const model = options.model || (0, import_openai.openai)("gpt-4o");
|
|
125
|
+
const handler = (req) => __async(null, null, function* () {
|
|
126
|
+
try {
|
|
127
|
+
const body = yield req.json();
|
|
128
|
+
const { messages, mode } = body;
|
|
129
|
+
if (!messages || messages.length === 0) {
|
|
130
|
+
return new Response(
|
|
131
|
+
JSON.stringify({
|
|
132
|
+
error: "No messages provided"
|
|
133
|
+
}),
|
|
134
|
+
{
|
|
135
|
+
status: 400,
|
|
136
|
+
headers: { "Content-Type": "application/json" }
|
|
137
|
+
}
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
for (const message of messages) {
|
|
141
|
+
const messageContent = message.parts.filter((part) => part.type === "text").map((part) => "text" in part ? part.text : "").join("");
|
|
142
|
+
if (messageContent.length > MAX_MESSAGE_LENGTH) {
|
|
143
|
+
return new Response(
|
|
144
|
+
JSON.stringify({
|
|
145
|
+
error: `Message exceeds maximum length of ${MAX_MESSAGE_LENGTH} characters`
|
|
146
|
+
}),
|
|
147
|
+
{
|
|
148
|
+
status: 400,
|
|
149
|
+
headers: { "Content-Type": "application/json" }
|
|
150
|
+
}
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
if (mode === "summarize") {
|
|
155
|
+
const { previousSummary } = body;
|
|
156
|
+
const stream2 = (0, import_ai.streamSummarize)({
|
|
157
|
+
model,
|
|
158
|
+
messages,
|
|
159
|
+
previousSummary
|
|
160
|
+
});
|
|
161
|
+
return (0, import_ai2.createUIMessageStreamResponse)({ stream: stream2 });
|
|
162
|
+
}
|
|
163
|
+
const { summary } = body;
|
|
164
|
+
const lastMessage = messages[messages.length - 1];
|
|
165
|
+
const currentPage = getCurrentPage({ request: req, message: lastMessage });
|
|
166
|
+
const searchEngine2 = options.getSearchEngine ? yield options.getSearchEngine() : yield getSearchEngine();
|
|
167
|
+
if (!searchEngine2) {
|
|
168
|
+
return new Response(
|
|
169
|
+
JSON.stringify({
|
|
170
|
+
error: "Search engine not available"
|
|
171
|
+
}),
|
|
172
|
+
{
|
|
173
|
+
status: 500,
|
|
174
|
+
headers: { "Content-Type": "application/json" }
|
|
175
|
+
}
|
|
176
|
+
);
|
|
177
|
+
}
|
|
178
|
+
const stream = (0, import_ai.streamSearchText)({
|
|
179
|
+
model,
|
|
180
|
+
searchEngine: searchEngine2,
|
|
181
|
+
messages,
|
|
182
|
+
currentPage,
|
|
183
|
+
summary
|
|
184
|
+
});
|
|
185
|
+
return (0, import_ai2.createUIMessageStreamResponse)({ stream });
|
|
186
|
+
} catch (error) {
|
|
187
|
+
log2.error("Error in the chat route:", error);
|
|
188
|
+
return new Response(
|
|
189
|
+
JSON.stringify({
|
|
190
|
+
error: "Error while processing the chat request"
|
|
191
|
+
}),
|
|
192
|
+
{
|
|
193
|
+
status: 500,
|
|
194
|
+
headers: { "Content-Type": "application/json" }
|
|
195
|
+
}
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
});
|
|
199
|
+
return handler;
|
|
200
|
+
}
|
|
201
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
202
|
+
0 && (module.exports = {
|
|
203
|
+
createHandler,
|
|
204
|
+
getSearchEngine
|
|
205
|
+
});
|
|
206
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/createHandler.ts","../src/utils/getCurrentPage.ts","../src/utils/getSearchEngine.ts"],"sourcesContent":["export { createHandler } from './createHandler';\nexport type { ChatRequestBody, CreateHandlerOptions, CurrentPageMetadata, GetSearchEngine } from './types';\nexport { getSearchEngine } from './utils/getSearchEngine';\n","import { openai } from '@ai-sdk/openai';\nimport { streamSearchText, streamSummarize } from '@peam-ai/ai';\nimport { loggers } from '@peam-ai/logger';\nimport { createUIMessageStreamResponse } from 'ai';\nimport { type CreateHandlerOptions, type HandlerRequestBody } from './types';\nimport { getCurrentPage } from './utils/getCurrentPage';\nimport { getSearchEngine } from './utils/getSearchEngine';\n\nconst MAX_MESSAGE_LENGTH = 30000;\nconst log = loggers.server;\n\n/**\n * Creates a HTTP handler for the chat API.\n * This handler processes incoming chat messages and streams responses back to the client.\n *\n * @param options - Configuration options for the handler\n * @param options.model - The language model to use (default: GPT-4o)\n * @param options.getSearchEngine - An optional function to retrieve the search engine\n * @returns An async function that handles HTTP requests\n *\n * @example\n * ```typescript\n * // Next.js\n * import { createHandler } from 'peam/server';\n * import { openai } from '@ai-sdk/openai';\n *\n * export const POST = createHandler({\n * model: openai('gpt-4o'),\n * getSearchEngine: async () => mySearchEngine,\n * });\n * ```\n */\nexport function createHandler(options: CreateHandlerOptions = {}) {\n const model = options.model || openai('gpt-4o');\n\n const handler = async (req: Request): Promise<Response> => {\n try {\n const body = (await req.json()) as HandlerRequestBody;\n const { messages, mode } = body;\n\n if (!messages || messages.length === 0) {\n return new Response(\n JSON.stringify({\n error: 'No messages provided',\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n\n // Validate message length\n for (const message of messages) {\n const messageContent = message.parts\n .filter((part) => part.type === 'text')\n .map((part) => ('text' in part ? part.text : ''))\n .join('');\n\n if (messageContent.length > MAX_MESSAGE_LENGTH) {\n return new Response(\n JSON.stringify({\n error: `Message exceeds maximum length of ${MAX_MESSAGE_LENGTH} characters`,\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n }\n\n // Handle summarization\n if (mode === 'summarize') {\n const { previousSummary } = body;\n const stream = streamSummarize({\n model,\n messages,\n previousSummary,\n });\n\n return createUIMessageStreamResponse({ stream });\n }\n\n // Handle chat\n const { summary } = body;\n const lastMessage = messages[messages.length - 1];\n const currentPage = getCurrentPage({ request: req, message: lastMessage });\n\n // Get search engine using the provided function\n const searchEngine = options.getSearchEngine ? await options.getSearchEngine() : await getSearchEngine();\n\n if (!searchEngine) {\n return new Response(\n JSON.stringify({\n error: 'Search engine not available',\n }),\n {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n\n const stream = streamSearchText({\n model,\n searchEngine,\n messages,\n currentPage,\n summary,\n });\n\n return createUIMessageStreamResponse({ stream });\n } catch (error) {\n log.error('Error in the chat route:', error);\n\n return new Response(\n JSON.stringify({\n error: 'Error while processing the chat request',\n }),\n {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n };\n\n return handler;\n}\n","import { UIMessage } from 'ai';\nimport { type CurrentPageMetadata } from '../types';\n\n/**\n * Extracts the current page metadata from the request and message.\n */\nexport const getCurrentPage = ({\n request,\n message,\n}: {\n request: Request;\n message: UIMessage;\n}): CurrentPageMetadata | undefined => {\n const messageMetadata = message.metadata as { currentPage?: { title: string; origin: string; path: string } };\n const messageCurrentPage = messageMetadata.currentPage;\n\n if (messageCurrentPage && messageCurrentPage.path && messageCurrentPage.origin) {\n return {\n title: messageCurrentPage.title,\n origin: messageCurrentPage.origin,\n path: messageCurrentPage.path,\n };\n }\n\n try {\n if (request.headers.has('referer')) {\n const refererUrl = new URL(request.headers.get('referer') || '');\n return {\n path: refererUrl.pathname,\n origin: refererUrl.origin,\n };\n }\n } catch {\n // Invalid referer URL\n }\n\n return undefined;\n};\n","import { loggers } from '@peam-ai/logger';\nimport { SearchEngine } from '@peam-ai/search';\n\nconst log = loggers.server;\nlet searchEngine: SearchEngine | null = null;\n\nexport async function getSearchEngine(): Promise<SearchEngine | undefined> {\n if (searchEngine) return searchEngine;\n\n try {\n // @ts-expect-error - peam_index/generated is resolved via webpack/turbopack alias\n const indexFile = (await import('peam_index/generated'))?.default;\n\n // Check if this is the stub\n if (!indexFile || !indexFile.data || !indexFile.keys || indexFile.keys.length === 0) {\n log.debug('Search index not yet generated. Run build first to generate the index.');\n return undefined;\n }\n\n searchEngine = new SearchEngine();\n await searchEngine.import(async (key: string) => {\n return indexFile.data[key];\n }, indexFile.keys);\n\n const totalDocs = searchEngine.count();\n log.debug('Index loaded successfully with', totalDocs, 'documents');\n return searchEngine;\n } catch (error) {\n log.error('Failed to load search index:', error);\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAAuB;AACvB,gBAAkD;AAClD,IAAAA,iBAAwB;AACxB,IAAAC,aAA8C;;;ACGvC,IAAM,iBAAiB,CAAC;AAAA,EAC7B;AAAA,EACA;AACF,MAGuC;AACrC,QAAM,kBAAkB,QAAQ;AAChC,QAAM,qBAAqB,gBAAgB;AAE3C,MAAI,sBAAsB,mBAAmB,QAAQ,mBAAmB,QAAQ;AAC9E,WAAO;AAAA,MACL,OAAO,mBAAmB;AAAA,MAC1B,QAAQ,mBAAmB;AAAA,MAC3B,MAAM,mBAAmB;AAAA,IAC3B;AAAA,EACF;AAEA,MAAI;AACF,QAAI,QAAQ,QAAQ,IAAI,SAAS,GAAG;AAClC,YAAM,aAAa,IAAI,IAAI,QAAQ,QAAQ,IAAI,SAAS,KAAK,EAAE;AAC/D,aAAO;AAAA,QACL,MAAM,WAAW;AAAA,QACjB,QAAQ,WAAW;AAAA,MACrB;AAAA,IACF;AAAA,EACF,SAAQ;AAAA,EAER;AAEA,SAAO;AAC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,UACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,QAChD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["import_logger","import_ai","log","stream","searchEngine"]}
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
var __async = (__this, __arguments, generator) => {
|
|
2
|
+
return new Promise((resolve, reject) => {
|
|
3
|
+
var fulfilled = (value) => {
|
|
4
|
+
try {
|
|
5
|
+
step(generator.next(value));
|
|
6
|
+
} catch (e) {
|
|
7
|
+
reject(e);
|
|
8
|
+
}
|
|
9
|
+
};
|
|
10
|
+
var rejected = (value) => {
|
|
11
|
+
try {
|
|
12
|
+
step(generator.throw(value));
|
|
13
|
+
} catch (e) {
|
|
14
|
+
reject(e);
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
|
|
18
|
+
step((generator = generator.apply(__this, __arguments)).next());
|
|
19
|
+
});
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// src/createHandler.ts
|
|
23
|
+
import { openai } from "@ai-sdk/openai";
|
|
24
|
+
import { streamSearchText, streamSummarize } from "@peam-ai/ai";
|
|
25
|
+
import { loggers as loggers2 } from "@peam-ai/logger";
|
|
26
|
+
import { createUIMessageStreamResponse } from "ai";
|
|
27
|
+
|
|
28
|
+
// src/utils/getCurrentPage.ts
|
|
29
|
+
var getCurrentPage = ({
|
|
30
|
+
request,
|
|
31
|
+
message
|
|
32
|
+
}) => {
|
|
33
|
+
const messageMetadata = message.metadata;
|
|
34
|
+
const messageCurrentPage = messageMetadata.currentPage;
|
|
35
|
+
if (messageCurrentPage && messageCurrentPage.path && messageCurrentPage.origin) {
|
|
36
|
+
return {
|
|
37
|
+
title: messageCurrentPage.title,
|
|
38
|
+
origin: messageCurrentPage.origin,
|
|
39
|
+
path: messageCurrentPage.path
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
if (request.headers.has("referer")) {
|
|
44
|
+
const refererUrl = new URL(request.headers.get("referer") || "");
|
|
45
|
+
return {
|
|
46
|
+
path: refererUrl.pathname,
|
|
47
|
+
origin: refererUrl.origin
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
} catch (e) {
|
|
51
|
+
}
|
|
52
|
+
return void 0;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
// src/utils/getSearchEngine.ts
|
|
56
|
+
import { loggers } from "@peam-ai/logger";
|
|
57
|
+
import { SearchEngine } from "@peam-ai/search";
|
|
58
|
+
var log = loggers.server;
|
|
59
|
+
var searchEngine = null;
|
|
60
|
+
function getSearchEngine() {
|
|
61
|
+
return __async(this, null, function* () {
|
|
62
|
+
var _a;
|
|
63
|
+
if (searchEngine) return searchEngine;
|
|
64
|
+
try {
|
|
65
|
+
const indexFile = (_a = yield import("peam_index/generated")) == null ? void 0 : _a.default;
|
|
66
|
+
if (!indexFile || !indexFile.data || !indexFile.keys || indexFile.keys.length === 0) {
|
|
67
|
+
log.debug("Search index not yet generated. Run build first to generate the index.");
|
|
68
|
+
return void 0;
|
|
69
|
+
}
|
|
70
|
+
searchEngine = new SearchEngine();
|
|
71
|
+
yield searchEngine.import((key) => __async(null, null, function* () {
|
|
72
|
+
return indexFile.data[key];
|
|
73
|
+
}), indexFile.keys);
|
|
74
|
+
const totalDocs = searchEngine.count();
|
|
75
|
+
log.debug("Index loaded successfully with", totalDocs, "documents");
|
|
76
|
+
return searchEngine;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
log.error("Failed to load search index:", error);
|
|
79
|
+
}
|
|
80
|
+
return void 0;
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// src/createHandler.ts
|
|
85
|
+
var MAX_MESSAGE_LENGTH = 3e4;
|
|
86
|
+
var log2 = loggers2.server;
|
|
87
|
+
function createHandler(options = {}) {
|
|
88
|
+
const model = options.model || openai("gpt-4o");
|
|
89
|
+
const handler = (req) => __async(null, null, function* () {
|
|
90
|
+
try {
|
|
91
|
+
const body = yield req.json();
|
|
92
|
+
const { messages, mode } = body;
|
|
93
|
+
if (!messages || messages.length === 0) {
|
|
94
|
+
return new Response(
|
|
95
|
+
JSON.stringify({
|
|
96
|
+
error: "No messages provided"
|
|
97
|
+
}),
|
|
98
|
+
{
|
|
99
|
+
status: 400,
|
|
100
|
+
headers: { "Content-Type": "application/json" }
|
|
101
|
+
}
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
for (const message of messages) {
|
|
105
|
+
const messageContent = message.parts.filter((part) => part.type === "text").map((part) => "text" in part ? part.text : "").join("");
|
|
106
|
+
if (messageContent.length > MAX_MESSAGE_LENGTH) {
|
|
107
|
+
return new Response(
|
|
108
|
+
JSON.stringify({
|
|
109
|
+
error: `Message exceeds maximum length of ${MAX_MESSAGE_LENGTH} characters`
|
|
110
|
+
}),
|
|
111
|
+
{
|
|
112
|
+
status: 400,
|
|
113
|
+
headers: { "Content-Type": "application/json" }
|
|
114
|
+
}
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
if (mode === "summarize") {
|
|
119
|
+
const { previousSummary } = body;
|
|
120
|
+
const stream2 = streamSummarize({
|
|
121
|
+
model,
|
|
122
|
+
messages,
|
|
123
|
+
previousSummary
|
|
124
|
+
});
|
|
125
|
+
return createUIMessageStreamResponse({ stream: stream2 });
|
|
126
|
+
}
|
|
127
|
+
const { summary } = body;
|
|
128
|
+
const lastMessage = messages[messages.length - 1];
|
|
129
|
+
const currentPage = getCurrentPage({ request: req, message: lastMessage });
|
|
130
|
+
const searchEngine2 = options.getSearchEngine ? yield options.getSearchEngine() : yield getSearchEngine();
|
|
131
|
+
if (!searchEngine2) {
|
|
132
|
+
return new Response(
|
|
133
|
+
JSON.stringify({
|
|
134
|
+
error: "Search engine not available"
|
|
135
|
+
}),
|
|
136
|
+
{
|
|
137
|
+
status: 500,
|
|
138
|
+
headers: { "Content-Type": "application/json" }
|
|
139
|
+
}
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
const stream = streamSearchText({
|
|
143
|
+
model,
|
|
144
|
+
searchEngine: searchEngine2,
|
|
145
|
+
messages,
|
|
146
|
+
currentPage,
|
|
147
|
+
summary
|
|
148
|
+
});
|
|
149
|
+
return createUIMessageStreamResponse({ stream });
|
|
150
|
+
} catch (error) {
|
|
151
|
+
log2.error("Error in the chat route:", error);
|
|
152
|
+
return new Response(
|
|
153
|
+
JSON.stringify({
|
|
154
|
+
error: "Error while processing the chat request"
|
|
155
|
+
}),
|
|
156
|
+
{
|
|
157
|
+
status: 500,
|
|
158
|
+
headers: { "Content-Type": "application/json" }
|
|
159
|
+
}
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
return handler;
|
|
164
|
+
}
|
|
165
|
+
export {
|
|
166
|
+
createHandler,
|
|
167
|
+
getSearchEngine
|
|
168
|
+
};
|
|
169
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/createHandler.ts","../src/utils/getCurrentPage.ts","../src/utils/getSearchEngine.ts"],"sourcesContent":["import { openai } from '@ai-sdk/openai';\nimport { streamSearchText, streamSummarize } from '@peam-ai/ai';\nimport { loggers } from '@peam-ai/logger';\nimport { createUIMessageStreamResponse } from 'ai';\nimport { type CreateHandlerOptions, type HandlerRequestBody } from './types';\nimport { getCurrentPage } from './utils/getCurrentPage';\nimport { getSearchEngine } from './utils/getSearchEngine';\n\nconst MAX_MESSAGE_LENGTH = 30000;\nconst log = loggers.server;\n\n/**\n * Creates a HTTP handler for the chat API.\n * This handler processes incoming chat messages and streams responses back to the client.\n *\n * @param options - Configuration options for the handler\n * @param options.model - The language model to use (default: GPT-4o)\n * @param options.getSearchEngine - An optional function to retrieve the search engine\n * @returns An async function that handles HTTP requests\n *\n * @example\n * ```typescript\n * // Next.js\n * import { createHandler } from 'peam/server';\n * import { openai } from '@ai-sdk/openai';\n *\n * export const POST = createHandler({\n * model: openai('gpt-4o'),\n * getSearchEngine: async () => mySearchEngine,\n * });\n * ```\n */\nexport function createHandler(options: CreateHandlerOptions = {}) {\n const model = options.model || openai('gpt-4o');\n\n const handler = async (req: Request): Promise<Response> => {\n try {\n const body = (await req.json()) as HandlerRequestBody;\n const { messages, mode } = body;\n\n if (!messages || messages.length === 0) {\n return new Response(\n JSON.stringify({\n error: 'No messages provided',\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n\n // Validate message length\n for (const message of messages) {\n const messageContent = message.parts\n .filter((part) => part.type === 'text')\n .map((part) => ('text' in part ? part.text : ''))\n .join('');\n\n if (messageContent.length > MAX_MESSAGE_LENGTH) {\n return new Response(\n JSON.stringify({\n error: `Message exceeds maximum length of ${MAX_MESSAGE_LENGTH} characters`,\n }),\n {\n status: 400,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n }\n\n // Handle summarization\n if (mode === 'summarize') {\n const { previousSummary } = body;\n const stream = streamSummarize({\n model,\n messages,\n previousSummary,\n });\n\n return createUIMessageStreamResponse({ stream });\n }\n\n // Handle chat\n const { summary } = body;\n const lastMessage = messages[messages.length - 1];\n const currentPage = getCurrentPage({ request: req, message: lastMessage });\n\n // Get search engine using the provided function\n const searchEngine = options.getSearchEngine ? await options.getSearchEngine() : await getSearchEngine();\n\n if (!searchEngine) {\n return new Response(\n JSON.stringify({\n error: 'Search engine not available',\n }),\n {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n\n const stream = streamSearchText({\n model,\n searchEngine,\n messages,\n currentPage,\n summary,\n });\n\n return createUIMessageStreamResponse({ stream });\n } catch (error) {\n log.error('Error in the chat route:', error);\n\n return new Response(\n JSON.stringify({\n error: 'Error while processing the chat request',\n }),\n {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n };\n\n return handler;\n}\n","import { UIMessage } from 'ai';\nimport { type CurrentPageMetadata } from '../types';\n\n/**\n * Extracts the current page metadata from the request and message.\n */\nexport const getCurrentPage = ({\n request,\n message,\n}: {\n request: Request;\n message: UIMessage;\n}): CurrentPageMetadata | undefined => {\n const messageMetadata = message.metadata as { currentPage?: { title: string; origin: string; path: string } };\n const messageCurrentPage = messageMetadata.currentPage;\n\n if (messageCurrentPage && messageCurrentPage.path && messageCurrentPage.origin) {\n return {\n title: messageCurrentPage.title,\n origin: messageCurrentPage.origin,\n path: messageCurrentPage.path,\n };\n }\n\n try {\n if (request.headers.has('referer')) {\n const refererUrl = new URL(request.headers.get('referer') || '');\n return {\n path: refererUrl.pathname,\n origin: refererUrl.origin,\n };\n }\n } catch {\n // Invalid referer URL\n }\n\n return undefined;\n};\n","import { loggers } from '@peam-ai/logger';\nimport { SearchEngine } from '@peam-ai/search';\n\nconst log = loggers.server;\nlet searchEngine: SearchEngine | null = null;\n\nexport async function getSearchEngine(): Promise<SearchEngine | undefined> {\n if (searchEngine) return searchEngine;\n\n try {\n // @ts-expect-error - peam_index/generated is resolved via webpack/turbopack alias\n const indexFile = (await import('peam_index/generated'))?.default;\n\n // Check if this is the stub\n if (!indexFile || !indexFile.data || !indexFile.keys || indexFile.keys.length === 0) {\n log.debug('Search index not yet generated. Run build first to generate the index.');\n return undefined;\n }\n\n searchEngine = new SearchEngine();\n await searchEngine.import(async (key: string) => {\n return indexFile.data[key];\n }, indexFile.keys);\n\n const totalDocs = searchEngine.count();\n log.debug('Index loaded successfully with', totalDocs, 'documents');\n return searchEngine;\n } catch (error) {\n log.error('Failed to load search index:', error);\n }\n\n return undefined;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,cAAc;AACvB,SAAS,kBAAkB,uBAAuB;AAClD,SAAS,WAAAA,gBAAe;AACxB,SAAS,qCAAqC;;;ACGvC,IAAM,iBAAiB,CAAC;AAAA,EAC7B;AAAA,EACA;AACF,MAGuC;AACrC,QAAM,kBAAkB,QAAQ;AAChC,QAAM,qB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OAAO;AAAA,UACT,CAAC;AAAA,UACD;AAAA,YACE,QAAQ;AAAA,YACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,UAChD;AAAA,QACF;AAAA,MACF;AAEA,YAAM,SAAS,iBAAiB;AAAA,QAC9B;AAAA,QACA,cAAAA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAC;AAED,aAAO,8BAA8B,EAAE,OAAO,CAAC;AAAA,IACjD,SAAS,OAAO;AACd,MAAAH,KAAI,MAAM,4BAA4B,KAAK;AAE3C,aAAO,IAAI;AAAA,QACT,KAAK,UAAU;AAAA,UACb,OAAO;AAAA,QACT,CAAC;AAAA,QACD;AAAA,UACE,QAAQ;AAAA,UACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,QAChD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["loggers","log","loggers","stream","searchEngine"]}
|
package/package.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@peam-ai/server",
|
|
3
|
+
"description": "Server handler for Peam",
|
|
4
|
+
"version": "0.1.1",
|
|
5
|
+
"main": "./dist/index.js",
|
|
6
|
+
"module": "./dist/index.mjs",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"homepage": "https://peam.ai",
|
|
9
|
+
"author": "Afshin Mehrabani",
|
|
10
|
+
"license": "Apache-2.0",
|
|
11
|
+
"repository": {
|
|
12
|
+
"type": "git",
|
|
13
|
+
"url": "https://github.com/peam-ai/peam.git",
|
|
14
|
+
"directory": "packages/server"
|
|
15
|
+
},
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/peam-ai/peam/issues"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist/**/*"
|
|
21
|
+
],
|
|
22
|
+
"exports": {
|
|
23
|
+
"./package.json": "./package.json",
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/index.d.ts",
|
|
26
|
+
"import": "./dist/index.mjs",
|
|
27
|
+
"require": "./dist/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"@ai-sdk/openai": "^3.0.0",
|
|
32
|
+
"ai": "^6.0.1",
|
|
33
|
+
"@peam-ai/ai": "0.1.1",
|
|
34
|
+
"@peam-ai/search": "0.1.1",
|
|
35
|
+
"@peam-ai/logger": "0.1.1"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"tsup": "^8.2.4",
|
|
39
|
+
"typescript": "^5.5.4"
|
|
40
|
+
},
|
|
41
|
+
"scripts": {
|
|
42
|
+
"build": "tsup",
|
|
43
|
+
"clean": "rm -rf dist",
|
|
44
|
+
"dev": "tsup --watch",
|
|
45
|
+
"test:eslint": "eslint \"src/**/*.ts*\"",
|
|
46
|
+
"test:prettier": "prettier --check \"src/**/*.ts*\"",
|
|
47
|
+
"test:jest": "jest"
|
|
48
|
+
}
|
|
49
|
+
}
|