@charivo/llm 0.4.3 → 0.6.0
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/README.md +10 -6
- package/dist/index.d.mts +3 -117
- package/dist/index.d.ts +3 -117
- package/dist/index.js +46 -48
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +47 -43
- package/dist/index.mjs.map +1 -1
- package/dist/openai/index.d.mts +13 -17
- package/dist/openai/index.d.ts +13 -17
- package/dist/openai/index.js +2 -1
- package/dist/openai/index.js.map +1 -1
- package/dist/openai/index.mjs +1 -1
- package/dist/openai/index.mjs.map +1 -1
- package/dist/openclaw/index.d.mts +48 -17
- package/dist/openclaw/index.d.ts +48 -17
- package/dist/openclaw/index.js +25 -8
- package/dist/openclaw/index.js.map +1 -1
- package/dist/openclaw/index.mjs +24 -8
- package/dist/openclaw/index.mjs.map +1 -1
- package/dist/remote/index.d.mts +2 -13
- package/dist/remote/index.d.ts +2 -13
- package/dist/remote/index.js +0 -1
- package/dist/remote/index.js.map +1 -1
- package/dist/remote/index.mjs +1 -1
- package/dist/remote/index.mjs.map +1 -1
- package/dist/stub/index.d.mts +2 -16
- package/dist/stub/index.d.ts +2 -16
- package/dist/stub/index.js +0 -1
- package/dist/stub/index.js.map +1 -1
- package/dist/stub/index.mjs +1 -1
- package/dist/stub/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -1,24 +1,6 @@
|
|
|
1
1
|
import { toCharivoError } from '@charivo/core';
|
|
2
2
|
|
|
3
|
-
// src/
|
|
4
|
-
var CharacterPromptBuilder = class {
|
|
5
|
-
static buildSystemPrompt(character) {
|
|
6
|
-
const name = character.name;
|
|
7
|
-
const description = character.description || "";
|
|
8
|
-
const personality = character.personality || "";
|
|
9
|
-
return `You are ${name}. ${description} ${personality}
|
|
10
|
-
|
|
11
|
-
Respond naturally in plain text with no bracketed emotion tags or control markup.`.trim();
|
|
12
|
-
}
|
|
13
|
-
static buildSystemPromptOrDefault(character) {
|
|
14
|
-
if (character) {
|
|
15
|
-
return this.buildSystemPrompt(character);
|
|
16
|
-
}
|
|
17
|
-
return `You are a helpful assistant.
|
|
18
|
-
|
|
19
|
-
Respond naturally in plain text with no bracketed emotion tags or control markup.`.trim();
|
|
20
|
-
}
|
|
21
|
-
};
|
|
3
|
+
// src/llm-manager.ts
|
|
22
4
|
|
|
23
5
|
// src/message-history-manager.ts
|
|
24
6
|
var MessageHistoryManager = class {
|
|
@@ -77,10 +59,30 @@ var MessageHistoryManager = class {
|
|
|
77
59
|
}
|
|
78
60
|
};
|
|
79
61
|
|
|
62
|
+
// src/character-prompt-builder.ts
|
|
63
|
+
var CharacterPromptBuilder = class {
|
|
64
|
+
static buildSystemPrompt(character) {
|
|
65
|
+
const name = character.name;
|
|
66
|
+
const description = character.description || "";
|
|
67
|
+
const personality = character.personality || "";
|
|
68
|
+
return `You are ${name}. ${description} ${personality}
|
|
69
|
+
|
|
70
|
+
Respond naturally in plain text with no bracketed emotion tags or control markup.`.trim();
|
|
71
|
+
}
|
|
72
|
+
static buildSystemPromptOrDefault(character) {
|
|
73
|
+
if (character) {
|
|
74
|
+
return this.buildSystemPrompt(character);
|
|
75
|
+
}
|
|
76
|
+
return `You are a helpful assistant.
|
|
77
|
+
|
|
78
|
+
Respond naturally in plain text with no bracketed emotion tags or control markup.`.trim();
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
80
82
|
// src/message-converter.ts
|
|
81
83
|
var MessageConverter = class {
|
|
82
84
|
/**
|
|
83
|
-
* Charivo Message
|
|
85
|
+
* Convert a Charivo Message to the OpenAI format
|
|
84
86
|
*/
|
|
85
87
|
static toOpenAIFormat(messages) {
|
|
86
88
|
return messages.map((msg) => ({
|
|
@@ -89,7 +91,7 @@ var MessageConverter = class {
|
|
|
89
91
|
}));
|
|
90
92
|
}
|
|
91
93
|
/**
|
|
92
|
-
*
|
|
94
|
+
* Combine the system prompt and messages into the OpenAI format
|
|
93
95
|
*/
|
|
94
96
|
static combineWithSystemPrompt(systemPrompt, messages) {
|
|
95
97
|
return [
|
|
@@ -99,19 +101,6 @@ var MessageConverter = class {
|
|
|
99
101
|
}
|
|
100
102
|
};
|
|
101
103
|
|
|
102
|
-
// src/response-message-builder.ts
|
|
103
|
-
var ResponseMessageBuilder = class {
|
|
104
|
-
static create(content, characterId, messageId) {
|
|
105
|
-
return {
|
|
106
|
-
id: messageId || "ai-" + Date.now(),
|
|
107
|
-
content,
|
|
108
|
-
timestamp: /* @__PURE__ */ new Date(),
|
|
109
|
-
type: "character",
|
|
110
|
-
characterId
|
|
111
|
-
};
|
|
112
|
-
}
|
|
113
|
-
};
|
|
114
|
-
|
|
115
104
|
// src/validators.ts
|
|
116
105
|
var LLMValidators = class {
|
|
117
106
|
static validateCharacterSet(character) {
|
|
@@ -125,6 +114,21 @@ var LLMValidators = class {
|
|
|
125
114
|
}
|
|
126
115
|
}
|
|
127
116
|
};
|
|
117
|
+
|
|
118
|
+
// src/response-message-builder.ts
|
|
119
|
+
var ResponseMessageBuilder = class {
|
|
120
|
+
static create(content, characterId, messageId) {
|
|
121
|
+
return {
|
|
122
|
+
id: messageId || "ai-" + Date.now(),
|
|
123
|
+
content,
|
|
124
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
125
|
+
type: "character",
|
|
126
|
+
characterId
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
// src/llm-manager.ts
|
|
128
132
|
var DEFAULT_MAX_HISTORY_TURNS = 40;
|
|
129
133
|
var LLMManager = class {
|
|
130
134
|
constructor(llmClient, options = {}) {
|
|
@@ -139,8 +143,8 @@ var LLMManager = class {
|
|
|
139
143
|
maxHistoryMessages;
|
|
140
144
|
character = null;
|
|
141
145
|
/**
|
|
142
|
-
*
|
|
143
|
-
*
|
|
146
|
+
* Set the character
|
|
147
|
+
* Clears the history only when the character changes.
|
|
144
148
|
*/
|
|
145
149
|
setCharacter(character) {
|
|
146
150
|
if (this.character?.id !== character.id) {
|
|
@@ -149,25 +153,25 @@ var LLMManager = class {
|
|
|
149
153
|
this.character = character;
|
|
150
154
|
}
|
|
151
155
|
/**
|
|
152
|
-
*
|
|
156
|
+
* Return the currently configured character
|
|
153
157
|
*/
|
|
154
158
|
getCharacter() {
|
|
155
159
|
return this.character;
|
|
156
160
|
}
|
|
157
161
|
/**
|
|
158
|
-
*
|
|
162
|
+
* Clear the history
|
|
159
163
|
*/
|
|
160
164
|
clearHistory() {
|
|
161
165
|
this.historyManager.clear();
|
|
162
166
|
}
|
|
163
167
|
/**
|
|
164
|
-
*
|
|
168
|
+
* Return the current history
|
|
165
169
|
*/
|
|
166
170
|
getHistory() {
|
|
167
171
|
return this.historyManager.getAll();
|
|
168
172
|
}
|
|
169
173
|
/**
|
|
170
|
-
*
|
|
174
|
+
* Generate a response to a message
|
|
171
175
|
*/
|
|
172
176
|
async generateResponse(message) {
|
|
173
177
|
try {
|
|
@@ -184,7 +188,7 @@ var LLMManager = class {
|
|
|
184
188
|
const responseMessage = ResponseMessageBuilder.create(
|
|
185
189
|
assistantMessage,
|
|
186
190
|
this.character.id
|
|
187
|
-
//
|
|
191
|
+
// character is guaranteed non-null after validateCharacterSet
|
|
188
192
|
);
|
|
189
193
|
this.historyManager.add(responseMessage, { prune: false });
|
|
190
194
|
this.historyManager.pruneToMax();
|
|
@@ -195,7 +199,7 @@ var LLMManager = class {
|
|
|
195
199
|
}
|
|
196
200
|
}
|
|
197
201
|
/**
|
|
198
|
-
*
|
|
202
|
+
* Prepare messages for the LLM API call
|
|
199
203
|
*/
|
|
200
204
|
prepareApiMessages(messages) {
|
|
201
205
|
if (!this.character) {
|
|
@@ -230,6 +234,6 @@ function resolveMaxHistoryMessages(options) {
|
|
|
230
234
|
return maxHistoryTurns * 2;
|
|
231
235
|
}
|
|
232
236
|
|
|
233
|
-
export {
|
|
237
|
+
export { createLLMManager };
|
|
234
238
|
//# sourceMappingURL=index.mjs.map
|
|
235
239
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/character-prompt-builder.ts","../src/message-history-manager.ts","../src/message-converter.ts","../src/response-message-builder.ts","../src/validators.ts","../src/llm-manager.ts"],"names":[],"mappings":";;;AAKO,IAAM,yBAAN,MAA6B;AAAA,EAClC,OAAO,kBAAkB,SAAA,EAA8B;AACrD,IAAA,MAAM,OAAO,SAAA,CAAU,IAAA;AACvB,IAAA,MAAM,WAAA,GAAc,UAAU,WAAA,IAAe,EAAA;AAC7C,IAAA,MAAM,WAAA,GAAc,UAAU,WAAA,IAAe,EAAA;AAE7C,IAAA,OAAO,CAAA,QAAA,EAAW,IAAI,CAAA,EAAA,EAAK,WAAW,IAAI,WAAW;;AAAA,iFAAA,CAAA,CAE0B,IAAA,EAAK;AAAA,EACtF;AAAA,EAEA,OAAO,2BAA2B,SAAA,EAA+B;AAC/D,IAAA,IAAI,SAAA,EAAW;AACb,MAAA,OAAO,IAAA,CAAK,kBAAkB,SAAS,CAAA;AAAA,IACzC;AACA,IAAA,OAAO,CAAA;;AAAA,iFAAA,CAAA,CAEwE,IAAA,EAAK;AAAA,EACtF;AACF;;;ACNO,IAAM,wBAAN,MAA4B;AAAA,EACzB,UAAqB,EAAC;AAAA,EACb,WAAA;AAAA,EACA,cAAA;AAAA,EAEjB,WAAA,CAAY,OAAA,GAAwC,EAAC,EAAG;AACtD,IAAA,IACE,OAAA,CAAQ,WAAA,KAAgB,MAAA,IACxB,OAAA,CAAQ,gBAAgB,IAAA,KACvB,CAAC,MAAA,CAAO,SAAA,CAAU,OAAA,CAAQ,WAAW,CAAA,IAAK,OAAA,CAAQ,eAAe,CAAA,CAAA,EAClE;AACA,MAAA,MAAM,IAAI,UAAU,gDAAgD,CAAA;AAAA,IACtE;AAEA,IAAA,IACE,OAAA,CAAQ,cAAA,KAAmB,MAAA,KAC1B,CAAC,MAAA,CAAO,SAAA,CAAU,O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YAAY,KAAK,CAAA;AAAA,IACxC;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKQ,mBACN,QAAA,EAC0C;AAC1C,IAAA,IAAI,CAAC,KAAK,SAAA,EAAW;AACnB,MAAA,OAAO,gBAAA,CAAiB,eAAe,QAAQ,CAAA;AAAA,IACjD;AAEA,IAAA,MAAM,eAAe,sBAAA,CAAuB,iBAAA;AAAA,MAC1C,IAAA,CAAK;AAAA,KACP;AACA,IAAA,OAAO,gBAAA,CAAiB,uBAAA,CAAwB,YAAA,EAAc,QAAQ,CAAA;AAAA,EACxE;AAAA,EAEQ,oBAAA,GAAkC;AACxC,IAAA,MAAM,eAAA,GAAkB,KAAK,cAAA,CAAe,SAAA;AAAA,MAC1C,IAAA,CAAK;AAAA,KACP;AAEA,IAAA,IAAI,eAAA,CAAgB,CAAC,CAAA,EAAG,IAAA,KAAS,WAAA,EAAa;AAC5C,MAAA,OAAO,eAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,IAChC;AAEA,IAAA,OAAO,eAAA;AAAA,EACT;AACF;AAKO,SAAS,gBAAA,CACd,WACA,OAAA,EACY;AACZ,EAAA,OAAO,IAAI,UAAA,CAAW,SAAA,EAAW,OAAO,CAAA;AAC1C;AAEA,SAAS,0BACP,OAAA,EACoB;AACpB,EAAA,IAAI,OAAA,CAAQ,oBAAoB,IAAA,EAAM;AACpC,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,eAAA,GAAkB,QAAQ,eAAA,IAAmB,yBAAA;AAEnD,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,eAAe,CAAA,IAAK,mBAAmB,CAAA,EAAG;AAC9D,IAAA,MAAM,IAAI,UAAU,oDAAoD,CAAA;AAAA,EAC1E;AAEA,EAAA,OAAO,eAAA,GAAkB,CAAA;AAC3B","file":"index.mjs","sourcesContent":["import { Character } from \"@charivo/core\";\n\n/**\n * 캐릭터 정보를 시스템 프롬프트로 변환하는 유틸리티\n */\nexport class CharacterPromptBuilder {\n static buildSystemPrompt(character: Character): string {\n const name = character.name;\n const description = character.description || \"\";\n const personality = character.personality || \"\";\n\n return `You are ${name}. ${description} ${personality}\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n\n static buildSystemPromptOrDefault(character?: Character): string {\n if (character) {\n return this.buildSystemPrompt(character);\n }\n return `You are a helpful assistant.\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n}\n","import { Message } from \"@charivo/core\";\n\nexport interface MessageHistoryManagerOptions {\n maxMessages?: number | null;\n pruneBatchSize?: number;\n}\n\nexport interface AddMessageOptions {\n /**\n * Internal escape hatch for workflows that need multiple appends to become\n * visible as one pruning boundary, such as user/assistant turn pairs.\n */\n prune?: boolean;\n}\n\n/**\n * 메시지 히스토리 관리\n */\nexport class MessageHistoryManager {\n private history: Message[] = [];\n private readonly maxMessages?: number;\n private readonly pruneBatchSize: number;\n\n constructor(options: MessageHistoryManagerOptions = {}) {\n if (\n options.maxMessages !== undefined &&\n options.maxMessages !== null &&\n (!Number.isInteger(options.maxMessages) || options.maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer or null\");\n }\n\n if (\n options.pruneBatchSize !== undefined &&\n (!Number.isInteger(options.pruneBatchSize) || options.pruneBatchSize <= 0)\n ) {\n throw new TypeError(\"pruneBatchSize must be a positive integer\");\n }\n\n this.maxMessages =\n options.maxMessages === null ? undefined : options.maxMessages;\n this.pruneBatchSize = options.pruneBatchSize ?? 1;\n }\n\n add(message: Message, options: AddMessageOptions = {}): void {\n this.history.push(message);\n\n if (options.prune !== false) {\n this.pruneToMax();\n }\n }\n\n removeLast(): Message | undefined {\n return this.history.pop();\n }\n\n clear(): void {\n this.history = [];\n }\n\n getAll(): Message[] {\n return [...this.history]; // 복사본 반환\n }\n\n getRecent(maxMessages?: number): Message[] {\n if (\n maxMessages !== undefined &&\n (!Number.isInteger(maxMessages) || maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer\");\n }\n\n if (maxMessages === undefined || this.history.length <= maxMessages) {\n return this.getAll();\n }\n\n return this.history.slice(-maxMessages);\n }\n\n size(): number {\n return this.history.length;\n }\n\n pruneToMax(): void {\n if (this.maxMessages === undefined) {\n return;\n }\n\n while (this.history.length > this.maxMessages) {\n const excess = this.history.length - this.maxMessages;\n const removeCount = Math.min(\n Math.ceil(excess / this.pruneBatchSize) * this.pruneBatchSize,\n this.history.length,\n );\n this.history.splice(0, removeCount);\n }\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * 메시지 형식 변환 유틸리티\n */\nexport class MessageConverter {\n /**\n * Charivo Message를 OpenAI 형식으로 변환\n */\n static toOpenAIFormat(\n messages: Message[],\n ): Array<{ role: string; content: string }> {\n return messages.map((msg) => ({\n role: msg.type === \"user\" ? \"user\" : \"assistant\",\n content: msg.content,\n }));\n }\n\n /**\n * 시스템 프롬프트와 메시지들을 OpenAI 형식으로 결합\n */\n static combineWithSystemPrompt(\n systemPrompt: string,\n messages: Message[],\n ): Array<{ role: string; content: string }> {\n return [\n { role: \"system\", content: systemPrompt },\n ...this.toOpenAIFormat(messages),\n ];\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * AI 응답 메시지 생성 헬퍼\n */\nexport class ResponseMessageBuilder {\n static create(\n content: string,\n characterId: string,\n messageId?: string,\n ): Message {\n return {\n id: messageId || \"ai-\" + Date.now(),\n content,\n timestamp: new Date(),\n type: \"character\",\n characterId,\n };\n }\n}\n","import { Character, Message } from \"@charivo/core\";\n\n/**\n * LLM 관련 검증 유틸리티\n */\nexport class LLMValidators {\n static validateCharacterSet(\n character: Character | null,\n ): asserts character is Character {\n if (!character) {\n throw new Error(\"Character must be set before generating response\");\n }\n }\n\n static validateMessage(message: Message): void {\n if (!message.content || typeof message.content !== \"string\") {\n throw new Error(\"Message content must be a non-empty string\");\n }\n }\n}\n","import { LLMClient, Message, Character, toCharivoError } from \"@charivo/core\";\nimport { MessageHistoryManager } from \"./message-history-manager\";\nimport { CharacterPromptBuilder } from \"./character-prompt-builder\";\nimport { MessageConverter } from \"./message-converter\";\nimport { LLMValidators } from \"./validators\";\nimport { ResponseMessageBuilder } from \"./response-message-builder\";\n\nconst DEFAULT_MAX_HISTORY_TURNS = 40;\n\nexport interface LLMManagerOptions {\n maxHistoryTurns?: number | null;\n}\n\n/**\n * LLM Manager - LLM 세션의 상태 관리를 담당하는 클래스\n *\n * 역할:\n * - 캐릭터 설정 및 관리\n * - 메시지 히스토리 관리\n * - LLM 클라이언트와의 통신\n * - 메시지 형식 변환\n * - 프롬프트 생성\n */\nexport class LLMManager {\n private readonly historyManager: MessageHistoryManager;\n private readonly maxHistoryMessages?: number;\n private character: Character | null = null;\n\n constructor(\n private llmClient: LLMClient,\n options: LLMManagerOptions = {},\n ) {\n this.maxHistoryMessages = resolveMaxHistoryMessages(options);\n this.historyManager = new MessageHistoryManager({\n maxMessages: this.maxHistoryMessages,\n pruneBatchSize: 2,\n });\n }\n\n /**\n * 캐릭터 설정\n * 캐릭터가 변경되는 경우에만 히스토리를 초기화합니다.\n */\n setCharacter(character: Character): void {\n // 캐릭터가 변경되는 경우에만 히스토리 초기화\n if (this.character?.id !== character.id) {\n this.historyManager.clear();\n }\n this.character = character;\n }\n\n /**\n * 현재 설정된 캐릭터 반환\n */\n getCharacter(): Character | null {\n return this.character;\n }\n\n /**\n * 히스토리 초기화\n */\n clearHistory(): void {\n this.historyManager.clear();\n }\n\n /**\n * 현재 히스토리 반환\n */\n getHistory(): Message[] {\n return this.historyManager.getAll();\n }\n\n /**\n * 메시지 응답 생성\n */\n async generateResponse(message: Message): Promise<string> {\n try {\n LLMValidators.validateCharacterSet(this.character);\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n\n // Defer pruning until the assistant message is appended. On failure we\n // only removeLast() the in-flight user message, so older history must\n // remain intact during the API call.\n this.historyManager.add(message, { prune: false });\n\n // 히스토리 메시지 가져오기\n const historyMessages = this.getHistoryForApiCall();\n\n // LLM API 형식으로 변환 (시스템 프롬프트 포함)\n const apiMessages = this.prepareApiMessages(historyMessages);\n\n try {\n // LLM 클라이언트를 통해 응답 생성\n const assistantMessage = await this.llmClient.call(apiMessages);\n\n // AI 응답 메시지 생성 및 히스토리에 추가\n const responseMessage = ResponseMessageBuilder.create(\n assistantMessage,\n this.character!.id, // validateCharacterSet 후 character는 non-null 보장됨\n );\n this.historyManager.add(responseMessage, { prune: false });\n this.historyManager.pruneToMax();\n\n return assistantMessage;\n } catch (error) {\n // 에러가 발생하면 마지막 메시지를 히스토리에서 제거\n this.historyManager.removeLast();\n throw toCharivoError(\"provider\", error);\n }\n }\n\n /**\n * LLM API 호출을 위한 메시지 준비\n */\n private prepareApiMessages(\n messages: Message[],\n ): Array<{ role: string; content: string }> {\n if (!this.character) {\n return MessageConverter.toOpenAIFormat(messages);\n }\n\n const systemPrompt = CharacterPromptBuilder.buildSystemPrompt(\n this.character,\n );\n return MessageConverter.combineWithSystemPrompt(systemPrompt, messages);\n }\n\n private getHistoryForApiCall(): Message[] {\n const historyMessages = this.historyManager.getRecent(\n this.maxHistoryMessages,\n );\n\n if (historyMessages[0]?.type === \"character\") {\n return historyMessages.slice(1);\n }\n\n return historyMessages;\n }\n}\n\n/**\n * LLM Manager 생성 헬퍼 함수\n */\nexport function createLLMManager(\n llmClient: LLMClient,\n options?: LLMManagerOptions,\n): LLMManager {\n return new LLMManager(llmClient, options);\n}\n\nfunction resolveMaxHistoryMessages(\n options: LLMManagerOptions,\n): number | undefined {\n if (options.maxHistoryTurns === null) {\n return undefined;\n }\n\n const maxHistoryTurns = options.maxHistoryTurns ?? DEFAULT_MAX_HISTORY_TURNS;\n\n if (!Number.isInteger(maxHistoryTurns) || maxHistoryTurns <= 0) {\n throw new TypeError(\"maxHistoryTurns must be a positive integer or null\");\n }\n\n return maxHistoryTurns * 2;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/message-history-manager.ts","../src/character-prompt-builder.ts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AC1C,IAAA,IAAI,CAAC,KAAK,SAAA,EAAW;AACnB,MAAA,OAAO,gBAAA,CAAiB,eAAe,QAAQ,CAAA;AAAA,IACjD;AAEA,IAAA,MAAM,eAAe,sBAAA,CAAuB,iBAAA;AAAA,MAC1C,IAAA,CAAK;AAAA,KACP;AACA,IAAA,OAAO,gBAAA,CAAiB,uBAAA,CAAwB,YAAA,EAAc,QAAQ,CAAA;AAAA,EACxE;AAAA,EAEQ,oBAAA,GAAkC;AACxC,IAAA,MAAM,eAAA,GAAkB,KAAK,cAAA,CAAe,SAAA;AAAA,MAC1C,IAAA,CAAK;AAAA,KACP;AAEA,IAAA,IAAI,eAAA,CAAgB,CAAC,CAAA,EAAG,IAAA,KAAS,WAAA,EAAa;AAC5C,MAAA,OAAO,eAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,IAChC;AAEA,IAAA,OAAO,eAAA;AAAA,EACT;AACF,CAAA;AAKO,SAAS,gBAAA,CACd,WACA,OAAA,EACgB;AAChB,EAAA,OAAO,IAAI,UAAA,CAAW,SAAA,EAAW,OAAO,CAAA;AAC1C;AAEA,SAAS,0BACP,OAAA,EACoB;AACpB,EAAA,IAAI,OAAA,CAAQ,oBAAoB,IAAA,EAAM;AACpC,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,eAAA,GAAkB,QAAQ,eAAA,IAAmB,yBAAA;AAEnD,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,eAAe,CAAA,IAAK,mBAAmB,CAAA,EAAG;AAC9D,IAAA,MAAM,IAAI,UAAU,oDAAoD,CAAA;AAAA,EAC1E;AAEA,EAAA,OAAO,eAAA,GAAkB,CAAA;AAC3B","file":"index.mjs","sourcesContent":["import { Message } from \"@charivo/core\";\n\nexport interface MessageHistoryManagerOptions {\n maxMessages?: number | null;\n pruneBatchSize?: number;\n}\n\nexport interface AddMessageOptions {\n /**\n * Internal escape hatch for workflows that need multiple appends to become\n * visible as one pruning boundary, such as user/assistant turn pairs.\n */\n prune?: boolean;\n}\n\n/**\n * Message history management\n */\nexport class MessageHistoryManager {\n private history: Message[] = [];\n private readonly maxMessages?: number;\n private readonly pruneBatchSize: number;\n\n constructor(options: MessageHistoryManagerOptions = {}) {\n if (\n options.maxMessages !== undefined &&\n options.maxMessages !== null &&\n (!Number.isInteger(options.maxMessages) || options.maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer or null\");\n }\n\n if (\n options.pruneBatchSize !== undefined &&\n (!Number.isInteger(options.pruneBatchSize) || options.pruneBatchSize <= 0)\n ) {\n throw new TypeError(\"pruneBatchSize must be a positive integer\");\n }\n\n this.maxMessages =\n options.maxMessages === null ? undefined : options.maxMessages;\n this.pruneBatchSize = options.pruneBatchSize ?? 1;\n }\n\n add(message: Message, options: AddMessageOptions = {}): void {\n this.history.push(message);\n\n if (options.prune !== false) {\n this.pruneToMax();\n }\n }\n\n removeLast(): Message | undefined {\n return this.history.pop();\n }\n\n clear(): void {\n this.history = [];\n }\n\n getAll(): Message[] {\n return [...this.history]; // Return a copy\n }\n\n getRecent(maxMessages?: number): Message[] {\n if (\n maxMessages !== undefined &&\n (!Number.isInteger(maxMessages) || maxMessages <= 0)\n ) {\n throw new TypeError(\"maxMessages must be a positive integer\");\n }\n\n if (maxMessages === undefined || this.history.length <= maxMessages) {\n return this.getAll();\n }\n\n return this.history.slice(-maxMessages);\n }\n\n size(): number {\n return this.history.length;\n }\n\n pruneToMax(): void {\n if (this.maxMessages === undefined) {\n return;\n }\n\n while (this.history.length > this.maxMessages) {\n const excess = this.history.length - this.maxMessages;\n const removeCount = Math.min(\n Math.ceil(excess / this.pruneBatchSize) * this.pruneBatchSize,\n this.history.length,\n );\n this.history.splice(0, removeCount);\n }\n }\n}\n","import { Character } from \"@charivo/core\";\n\n/**\n * Utility for converting character information into a system prompt\n */\nexport class CharacterPromptBuilder {\n static buildSystemPrompt(character: Character): string {\n const name = character.name;\n const description = character.description || \"\";\n const personality = character.personality || \"\";\n\n return `You are ${name}. ${description} ${personality}\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n\n static buildSystemPromptOrDefault(character?: Character): string {\n if (character) {\n return this.buildSystemPrompt(character);\n }\n return `You are a helpful assistant.\n\nRespond naturally in plain text with no bracketed emotion tags or control markup.`.trim();\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Message format conversion utility\n */\nexport class MessageConverter {\n /**\n * Convert a Charivo Message to the OpenAI format\n */\n static toOpenAIFormat(\n messages: Message[],\n ): Array<{ role: string; content: string }> {\n return messages.map((msg) => ({\n role: msg.type === \"user\" ? \"user\" : \"assistant\",\n content: msg.content,\n }));\n }\n\n /**\n * Combine the system prompt and messages into the OpenAI format\n */\n static combineWithSystemPrompt(\n systemPrompt: string,\n messages: Message[],\n ): Array<{ role: string; content: string }> {\n return [\n { role: \"system\", content: systemPrompt },\n ...this.toOpenAIFormat(messages),\n ];\n }\n}\n","import { Character, Message } from \"@charivo/core\";\n\n/**\n * LLM-related validation utilities\n */\nexport class LLMValidators {\n static validateCharacterSet(\n character: Character | null,\n ): asserts character is Character {\n if (!character) {\n throw new Error(\"Character must be set before generating response\");\n }\n }\n\n static validateMessage(message: Message): void {\n if (!message.content || typeof message.content !== \"string\") {\n throw new Error(\"Message content must be a non-empty string\");\n }\n }\n}\n","import { Message } from \"@charivo/core\";\n\n/**\n * Helper for building AI response messages\n */\nexport class ResponseMessageBuilder {\n static create(\n content: string,\n characterId: string,\n messageId?: string,\n ): Message {\n return {\n id: messageId || \"ai-\" + Date.now(),\n content,\n timestamp: new Date(),\n type: \"character\",\n characterId,\n };\n }\n}\n","import {\n LLMClient,\n Message,\n Character,\n toCharivoError,\n type LLMManager as CoreLLMManager,\n} from \"@charivo/core\";\nimport { MessageHistoryManager } from \"./message-history-manager\";\nimport { CharacterPromptBuilder } from \"./character-prompt-builder\";\nimport { MessageConverter } from \"./message-converter\";\nimport { LLMValidators } from \"./validators\";\nimport { ResponseMessageBuilder } from \"./response-message-builder\";\n\nconst DEFAULT_MAX_HISTORY_TURNS = 40;\n\nexport interface LLMManagerOptions {\n maxHistoryTurns?: number | null;\n}\n\n/**\n * LLM Manager - Class responsible for managing the state of an LLM session\n *\n * Responsibilities:\n * - Character configuration and management\n * - Message history management\n * - Communication with the LLM client\n * - Message format conversion\n * - Prompt generation\n */\nexport class LLMManager {\n private readonly historyManager: MessageHistoryManager;\n private readonly maxHistoryMessages?: number;\n private character: Character | null = null;\n\n constructor(\n private llmClient: LLMClient,\n options: LLMManagerOptions = {},\n ) {\n this.maxHistoryMessages = resolveMaxHistoryMessages(options);\n this.historyManager = new MessageHistoryManager({\n maxMessages: this.maxHistoryMessages,\n pruneBatchSize: 2,\n });\n }\n\n /**\n * Set the character\n * Clears the history only when the character changes.\n */\n setCharacter(character: Character): void {\n // Clear the history only when the character changes\n if (this.character?.id !== character.id) {\n this.historyManager.clear();\n }\n this.character = character;\n }\n\n /**\n * Return the currently configured character\n */\n getCharacter(): Character | null {\n return this.character;\n }\n\n /**\n * Clear the history\n */\n clearHistory(): void {\n this.historyManager.clear();\n }\n\n /**\n * Return the current history\n */\n getHistory(): Message[] {\n return this.historyManager.getAll();\n }\n\n /**\n * Generate a response to a message\n */\n async generateResponse(message: Message): Promise<string> {\n try {\n LLMValidators.validateCharacterSet(this.character);\n LLMValidators.validateMessage(message);\n } catch (error) {\n throw toCharivoError(\"state\", error);\n }\n\n // Defer pruning until the assistant message is appended. On failure we\n // only removeLast() the in-flight user message, so older history must\n // remain intact during the API call.\n this.historyManager.add(message, { prune: false });\n\n // Get the history messages\n const historyMessages = this.getHistoryForApiCall();\n\n // Convert to LLM API format (including the system prompt)\n const apiMessages = this.prepareApiMessages(historyMessages);\n\n try {\n // Generate a response via the LLM client\n const assistantMessage = await this.llmClient.call(apiMessages);\n\n // Build the AI response message and add it to the history\n const responseMessage = ResponseMessageBuilder.create(\n assistantMessage,\n this.character!.id, // character is guaranteed non-null after validateCharacterSet\n );\n this.historyManager.add(responseMessage, { prune: false });\n this.historyManager.pruneToMax();\n\n return assistantMessage;\n } catch (error) {\n // On error, remove the last message from the history\n this.historyManager.removeLast();\n throw toCharivoError(\"provider\", error);\n }\n }\n\n /**\n * Prepare messages for the LLM API call\n */\n private prepareApiMessages(\n messages: Message[],\n ): Array<{ role: string; content: string }> {\n if (!this.character) {\n return MessageConverter.toOpenAIFormat(messages);\n }\n\n const systemPrompt = CharacterPromptBuilder.buildSystemPrompt(\n this.character,\n );\n return MessageConverter.combineWithSystemPrompt(systemPrompt, messages);\n }\n\n private getHistoryForApiCall(): Message[] {\n const historyMessages = this.historyManager.getRecent(\n this.maxHistoryMessages,\n );\n\n if (historyMessages[0]?.type === \"character\") {\n return historyMessages.slice(1);\n }\n\n return historyMessages;\n }\n}\n\n/**\n * Helper function to create an LLM Manager\n */\nexport function createLLMManager(\n llmClient: LLMClient,\n options?: LLMManagerOptions,\n): CoreLLMManager {\n return new LLMManager(llmClient, options);\n}\n\nfunction resolveMaxHistoryMessages(\n options: LLMManagerOptions,\n): number | undefined {\n if (options.maxHistoryTurns === null) {\n return undefined;\n }\n\n const maxHistoryTurns = options.maxHistoryTurns ?? DEFAULT_MAX_HISTORY_TURNS;\n\n if (!Number.isInteger(maxHistoryTurns) || maxHistoryTurns <= 0) {\n throw new TypeError(\"maxHistoryTurns must be a positive integer or null\");\n }\n\n return maxHistoryTurns * 2;\n}\n"]}
|
package/dist/openai/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { LLMClient } from '@charivo/core';
|
|
1
|
+
import { LLMProvider, LLMClient } from '@charivo/core';
|
|
2
2
|
|
|
3
3
|
interface OpenAILLMConfig {
|
|
4
4
|
apiKey: string;
|
|
@@ -7,24 +7,20 @@ interface OpenAILLMConfig {
|
|
|
7
7
|
maxTokens?: number;
|
|
8
8
|
dangerouslyAllowBrowser?: boolean;
|
|
9
9
|
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
*
|
|
18
|
-
* Stateless 설계: 세션 관리는 외부에서 담당하고, 이 클라이언트는 API 호출만 담당
|
|
19
|
-
*/
|
|
20
|
-
declare class OpenAILLMClient implements LLMClient {
|
|
21
|
-
private provider;
|
|
22
|
-
constructor(config: OpenAILLMClientConfig);
|
|
23
|
-
call(messages: Array<{
|
|
10
|
+
declare class OpenAILLMProvider implements LLMProvider {
|
|
11
|
+
private openai;
|
|
12
|
+
private model;
|
|
13
|
+
private temperature;
|
|
14
|
+
private maxTokens;
|
|
15
|
+
constructor(config: OpenAILLMConfig);
|
|
16
|
+
generateResponse(messages: Array<{
|
|
24
17
|
role: string;
|
|
25
18
|
content: string;
|
|
26
19
|
}>): Promise<string>;
|
|
27
20
|
}
|
|
28
|
-
declare function
|
|
21
|
+
declare function createOpenAILLMProvider(config: OpenAILLMConfig): OpenAILLMProvider;
|
|
22
|
+
|
|
23
|
+
type OpenAILLMClientConfig = OpenAILLMConfig;
|
|
24
|
+
declare function createOpenAILLMClient(config: OpenAILLMClientConfig): LLMClient;
|
|
29
25
|
|
|
30
|
-
export {
|
|
26
|
+
export { type OpenAILLMClientConfig, type OpenAILLMConfig, OpenAILLMProvider, createOpenAILLMClient, createOpenAILLMProvider };
|
package/dist/openai/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { LLMClient } from '@charivo/core';
|
|
1
|
+
import { LLMProvider, LLMClient } from '@charivo/core';
|
|
2
2
|
|
|
3
3
|
interface OpenAILLMConfig {
|
|
4
4
|
apiKey: string;
|
|
@@ -7,24 +7,20 @@ interface OpenAILLMConfig {
|
|
|
7
7
|
maxTokens?: number;
|
|
8
8
|
dangerouslyAllowBrowser?: boolean;
|
|
9
9
|
}
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
*
|
|
18
|
-
* Stateless 설계: 세션 관리는 외부에서 담당하고, 이 클라이언트는 API 호출만 담당
|
|
19
|
-
*/
|
|
20
|
-
declare class OpenAILLMClient implements LLMClient {
|
|
21
|
-
private provider;
|
|
22
|
-
constructor(config: OpenAILLMClientConfig);
|
|
23
|
-
call(messages: Array<{
|
|
10
|
+
declare class OpenAILLMProvider implements LLMProvider {
|
|
11
|
+
private openai;
|
|
12
|
+
private model;
|
|
13
|
+
private temperature;
|
|
14
|
+
private maxTokens;
|
|
15
|
+
constructor(config: OpenAILLMConfig);
|
|
16
|
+
generateResponse(messages: Array<{
|
|
24
17
|
role: string;
|
|
25
18
|
content: string;
|
|
26
19
|
}>): Promise<string>;
|
|
27
20
|
}
|
|
28
|
-
declare function
|
|
21
|
+
declare function createOpenAILLMProvider(config: OpenAILLMConfig): OpenAILLMProvider;
|
|
22
|
+
|
|
23
|
+
type OpenAILLMClientConfig = OpenAILLMConfig;
|
|
24
|
+
declare function createOpenAILLMClient(config: OpenAILLMClientConfig): LLMClient;
|
|
29
25
|
|
|
30
|
-
export {
|
|
26
|
+
export { type OpenAILLMClientConfig, type OpenAILLMConfig, OpenAILLMProvider, createOpenAILLMClient, createOpenAILLMProvider };
|
package/dist/openai/index.js
CHANGED
|
@@ -87,7 +87,8 @@ function createOpenAILLMClient(config) {
|
|
|
87
87
|
return new OpenAILLMClient(config);
|
|
88
88
|
}
|
|
89
89
|
|
|
90
|
-
exports.
|
|
90
|
+
exports.OpenAILLMProvider = OpenAILLMProvider;
|
|
91
91
|
exports.createOpenAILLMClient = createOpenAILLMClient;
|
|
92
|
+
exports.createOpenAILLMProvider = createOpenAILLMProvider;
|
|
92
93
|
//# sourceMappingURL=index.js.map
|
|
93
94
|
//# sourceMappingURL=index.js.map
|
package/dist/openai/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/openai/provider.ts","../../src/openai/index.ts"],"names":["CharivoStateError","OpenAI","toCharivoError","CharivoTimeoutError"],"mappings":";;;;;;;;;;AAQA,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AAW,EAAA;AAAA,IACpD,SAAS,KAAA,EAAO;AACd,MAAA,MAAMC,mBAAA,CAAe,UAAA,EAAY,KAAA,EAAO,2BAA2B,CAAA;AAAA,IACrE;AAAA,EACF;AACF
|
|
1
|
+
{"version":3,"sources":["../../src/openai/provider.ts","../../src/openai/index.ts"],"names":["CharivoStateError","OpenAI","toCharivoError","CharivoTimeoutError"],"mappings":";;;;;;;;;;AAQA,IAAM,kBAAA,GAAqB,GAAA;AAUpB,IAAM,oBAAN,MAA+C;AAAA,EAC5C,MAAA;AAAA,EACA,KAAA;AAAA,EACA,WAAA;AAAA,EACA,SAAA;AAAA,EAER,YAAY,MAAA,EAAyB;AACnC,IAAA,IAAI,OAAO,MAAA,KAAW,WAAA,IAAe,CAAC,OAAO,uBAAA,EAAyB;AACpE,MAAA,MAAM,IAAIA,sBAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF;AAEA,IAAA,IAAA,CAAK,MAAA,GAAS,IAAIC,uBAAA,CAAO;AAAA,MACvB,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,yBAAyB,MAAA,CAAO;AAAA,KACjC,CAAA;AAED,IAAA,IAAA,CAAK,KAAA,GAAQ,OAAO,KAAA,IAAS,cAAA;AAC7B,IAAA,IAAA,CAAK,WAAA,GAAc,OAAO,WAAA,IAAe,GAAA;AACzC,IAAA,IAAA,CAAK,SAAA,GAAY,OAAO,SAAA,IAAa,GAAA;AAAA,EACvC;AAAA,EAEA,MAAM,iBACJ,QAAA,EACiB;AACjB,IAAA,IAAI;AACF,MAAA,MAAM,cAAA,GAAiB,QAAA,CAAS,GAAA,CAAI,CAAC,GAAA,MAAS;AAAA,QAC5C,MAAM,GAAA,CAAI,IAAA;AAAA,QACV,SAAS,GAAA,CAAI;AAAA,OACf,CAAE,CAAA;AAEF,MAAA,MAAM,aAAa,MAAM,WAAA;AAAA,QACvB,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,WAAA,CAAY,MAAA,CAAO;AAAA,UAClC,O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,MAAM,gBAAA,GAAmB,MAAM,IAAA,CAAK,QAAA,CAAS,iBAAiB,QAAQ,CAAA;AAEtE,IAAA,OAAO,gBAAA;AAAA,EACT;AACF,CAAA;AAEO,SAAS,sBACd,MAAA,EACW;AACX,EAAA,OAAO,IAAI,gBAAgB,MAAM,CAAA;AACnC","file":"index.js","sourcesContent":["import OpenAI from \"openai\";\nimport {\n CharivoStateError,\n CharivoTimeoutError,\n LLMProvider,\n toCharivoError,\n} from \"@charivo/core\";\n\nconst REQUEST_TIMEOUT_MS = 30_000;\n\nexport interface OpenAILLMConfig {\n apiKey: string;\n model?: string;\n temperature?: number;\n maxTokens?: number;\n dangerouslyAllowBrowser?: boolean;\n}\n\nexport class OpenAILLMProvider implements LLMProvider {\n private openai: OpenAI;\n private model: string;\n private temperature: number;\n private maxTokens: number;\n\n constructor(config: OpenAILLMConfig) {\n if (typeof window !== \"undefined\" && !config.dangerouslyAllowBrowser) {\n throw new CharivoStateError(\n \"OpenAI LLM provider is for server-side use only. Set dangerouslyAllowBrowser: true for testing\",\n );\n }\n\n this.openai = new OpenAI({\n apiKey: config.apiKey,\n dangerouslyAllowBrowser: config.dangerouslyAllowBrowser,\n });\n\n this.model = config.model || \"gpt-4.1-nano\";\n this.temperature = config.temperature || 0.7;\n this.maxTokens = config.maxTokens || 1000;\n }\n\n async generateResponse(\n messages: Array<{ role: string; content: string }>,\n ): Promise<string> {\n try {\n const openAIMessages = messages.map((msg) => ({\n role: msg.role as \"system\" | \"user\" | \"assistant\",\n content: msg.content,\n }));\n\n const completion = await withTimeout(\n this.openai.chat.completions.create({\n model: this.model,\n messages: openAIMessages,\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n }),\n `OpenAI LLM request timed out after ${REQUEST_TIMEOUT_MS}ms`,\n );\n\n return completion.choices[0]?.message?.content || \"\";\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"OpenAI LLM request failed\");\n }\n }\n}\n\nexport function createOpenAILLMProvider(\n config: OpenAILLMConfig,\n): OpenAILLMProvider {\n return new OpenAILLMProvider(config);\n}\n\nasync function withTimeout<T>(\n promise: Promise<T>,\n timeoutMessage: string,\n): Promise<T> {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const timeoutPromise = new Promise<T>((_, reject) => {\n timeoutId = setTimeout(\n () => reject(new CharivoTimeoutError(timeoutMessage)),\n REQUEST_TIMEOUT_MS,\n );\n });\n\n try {\n return await Promise.race([promise, timeoutPromise]);\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n}\n","import type { LLMClient } from \"@charivo/core\";\nimport {\n createOpenAILLMProvider,\n OpenAILLMConfig,\n OpenAILLMProvider,\n} from \"./provider\";\n\nexport {\n createOpenAILLMProvider,\n OpenAILLMProvider,\n type OpenAILLMConfig,\n} from \"./provider\";\n\n// Use OpenAILLMConfig directly\nexport type OpenAILLMClientConfig = OpenAILLMConfig;\n\n/**\n * OpenAI LLM Client - Stateless client that wraps the OpenAI provider for direct use on the client\n *\n * For use in local development or test environments. Not recommended for production for security reasons.\n * The API key is exposed to the client, so use it only in a server environment or for testing purposes.\n *\n * Stateless design: session management is handled externally, and this client only handles API calls\n */\nclass OpenAILLMClient implements LLMClient {\n private provider: OpenAILLMProvider;\n\n constructor(config: OpenAILLMClientConfig) {\n // Intentional dev/test escape hatch: this direct browser client exposes\n // credentials. For production, see docs/guide/choosing-packages.md#remote.\n this.provider = createOpenAILLMProvider({\n ...config,\n dangerouslyAllowBrowser: true,\n });\n }\n\n async call(\n messages: Array<{ role: string; content: string }>,\n ): Promise<string> {\n // Generate a response using the provider\n const assistantMessage = await this.provider.generateResponse(messages);\n\n return assistantMessage;\n }\n}\n\nexport function createOpenAILLMClient(\n config: OpenAILLMClientConfig,\n): LLMClient {\n return new OpenAILLMClient(config);\n}\n"]}
|
package/dist/openai/index.mjs
CHANGED
|
@@ -81,6 +81,6 @@ function createOpenAILLMClient(config) {
|
|
|
81
81
|
return new OpenAILLMClient(config);
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
-
export {
|
|
84
|
+
export { OpenAILLMProvider, createOpenAILLMClient, createOpenAILLMProvider };
|
|
85
85
|
//# sourceMappingURL=index.mjs.map
|
|
86
86
|
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/openai/provider.ts","../../src/openai/index.ts"],"names":[],"mappings":";;;;AAQA,IAAM,kBAAA,GAAqB,GAAA;AAUpB,IAAM,oBAAN,MAA+C;AAAA,EAC5C,MAAA;AAAA,EACA,KAAA;AAAA,EACA,WAAA;AAAA,EACA,SAAA;AAAA,EAER,YAAY,MAAA,EAAyB;AACnC,IAAA,IAAI,OAAO,MAAA,KAAW,WAAA,IAAe,CAAC,OAAO,uBAAA,EAAyB;AACpE,MAAA,MAAM,IAAI,iBAAA;AAAA,QACR;AAAA,OACF;AAAA,IACF;AAEA,IAAA,IAAA,CAAK,MAAA,GAAS,IAAI,MAAA,CAAO;AAAA,MACvB,QAAQ,MAAA,CAAO,MAAA;AAAA,MACf,yBAAyB,MAAA,CAAO;AAAA,KACjC,CAAA;AAED,IAAA,IAAA,CAAK,KAAA,GAAQ,OAAO,KAAA,IAAS,cAAA;AAC7B,IAAA,IAAA,CAAK,WAAA,GAAc,OAAO,WAAA,IAAe,GAAA;AACzC,IAAA,IAAA,CAAK,SAAA,GAAY,OAAO,SAAA,IAAa,GAAA;AAAA,EACvC;AAAA,EAEA,MAAM,iBACJ,QAAA,EACiB;AACjB,IAAA,IAAI;AACF,MAAA,MAAM,cAAA,GAAiB,QAAA,CAAS,GAAA,CAAI,CAAC,GAAA,MAAS;AAAA,QAC5C,MAAM,GAAA,CAAI,IAAA;AAAA,QACV,SAAS,GAAA,CAAI;AAAA,OACf,CAAE,CAAA;AAEF,MAAA,MAAM,aAAa,MAAM,WAAA;AAAA,QACvB,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,WAAA,CAAY,MAAA,CAAO;AAAA,UAClC,OAAO,IAAA,CAA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,YAAY,MAAA,EAA+B;AAGzC,IAAA,IAAA,CAAK,WAAW,uBAAA,CAAwB;AAAA,MACtC,GAAG,MAAA;AAAA,MACH,uBAAA,EAAyB;AAAA,KAC1B,CAAA;AAAA,EACH;AAAA,EAEA,MAAM,KACJ,QAAA,EACiB;AAEjB,IAAA,MAAM,gBAAA,GAAmB,MAAM,IAAA,CAAK,QAAA,CAAS,iBAAiB,QAAQ,CAAA;AAEtE,IAAA,OAAO,gBAAA;AAAA,EACT;AACF,CAAA;AAEO,SAAS,sBACd,MAAA,EACW;AACX,EAAA,OAAO,IAAI,gBAAgB,MAAM,CAAA;AACnC","file":"index.mjs","sourcesContent":["import OpenAI from \"openai\";\nimport {\n CharivoStateError,\n CharivoTimeoutError,\n LLMProvider,\n toCharivoError,\n} from \"@charivo/core\";\n\nconst REQUEST_TIMEOUT_MS = 30_000;\n\nexport interface OpenAILLMConfig {\n apiKey: string;\n model?: string;\n temperature?: number;\n maxTokens?: number;\n dangerouslyAllowBrowser?: boolean;\n}\n\nexport class OpenAILLMProvider implements LLMProvider {\n private openai: OpenAI;\n private model: string;\n private temperature: number;\n private maxTokens: number;\n\n constructor(config: OpenAILLMConfig) {\n if (typeof window !== \"undefined\" && !config.dangerouslyAllowBrowser) {\n throw new CharivoStateError(\n \"OpenAI LLM provider is for server-side use only. Set dangerouslyAllowBrowser: true for testing\",\n );\n }\n\n this.openai = new OpenAI({\n apiKey: config.apiKey,\n dangerouslyAllowBrowser: config.dangerouslyAllowBrowser,\n });\n\n this.model = config.model || \"gpt-4.1-nano\";\n this.temperature = config.temperature || 0.7;\n this.maxTokens = config.maxTokens || 1000;\n }\n\n async generateResponse(\n messages: Array<{ role: string; content: string }>,\n ): Promise<string> {\n try {\n const openAIMessages = messages.map((msg) => ({\n role: msg.role as \"system\" | \"user\" | \"assistant\",\n content: msg.content,\n }));\n\n const completion = await withTimeout(\n this.openai.chat.completions.create({\n model: this.model,\n messages: openAIMessages,\n temperature: this.temperature,\n max_tokens: this.maxTokens,\n }),\n `OpenAI LLM request timed out after ${REQUEST_TIMEOUT_MS}ms`,\n );\n\n return completion.choices[0]?.message?.content || \"\";\n } catch (error) {\n throw toCharivoError(\"provider\", error, \"OpenAI LLM request failed\");\n }\n }\n}\n\nexport function createOpenAILLMProvider(\n config: OpenAILLMConfig,\n): OpenAILLMProvider {\n return new OpenAILLMProvider(config);\n}\n\nasync function withTimeout<T>(\n promise: Promise<T>,\n timeoutMessage: string,\n): Promise<T> {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n\n const timeoutPromise = new Promise<T>((_, reject) => {\n timeoutId = setTimeout(\n () => reject(new CharivoTimeoutError(timeoutMessage)),\n REQUEST_TIMEOUT_MS,\n );\n });\n\n try {\n return await Promise.race([promise, timeoutPromise]);\n } finally {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n }\n}\n","import type { LLMClient } from \"@charivo/core\";\nimport {\n createOpenAILLMProvider,\n OpenAILLMConfig,\n OpenAILLMProvider,\n} from \"./provider\";\n\nexport {\n createOpenAILLMProvider,\n OpenAILLMProvider,\n type OpenAILLMConfig,\n} from \"./provider\";\n\n// Use OpenAILLMConfig directly\nexport type OpenAILLMClientConfig = OpenAILLMConfig;\n\n/**\n * OpenAI LLM Client - Stateless client that wraps the OpenAI provider for direct use on the client\n *\n * For use in local development or test environments. Not recommended for production for security reasons.\n * The API key is exposed to the client, so use it only in a server environment or for testing purposes.\n *\n * Stateless design: session management is handled externally, and this client only handles API calls\n */\nclass OpenAILLMClient implements LLMClient {\n private provider: OpenAILLMProvider;\n\n constructor(config: OpenAILLMClientConfig) {\n // Intentional dev/test escape hatch: this direct browser client exposes\n // credentials. For production, see docs/guide/choosing-packages.md#remote.\n this.provider = createOpenAILLMProvider({\n ...config,\n dangerouslyAllowBrowser: true,\n });\n }\n\n async call(\n messages: Array<{ role: string; content: string }>,\n ): Promise<string> {\n // Generate a response using the provider\n const assistantMessage = await this.provider.generateResponse(messages);\n\n return assistantMessage;\n }\n}\n\nexport function createOpenAILLMClient(\n config: OpenAILLMClientConfig,\n): LLMClient {\n return new OpenAILLMClient(config);\n}\n"]}
|
|
@@ -1,32 +1,63 @@
|
|
|
1
|
-
import { LLMClient } from '@charivo/core';
|
|
1
|
+
import { LLMProvider, LLMClient } from '@charivo/core';
|
|
2
2
|
|
|
3
3
|
interface OpenClawLLMConfig {
|
|
4
4
|
token: string;
|
|
5
5
|
baseURL?: string;
|
|
6
|
+
/**
|
|
7
|
+
* Target a specific agent on the gateway.
|
|
8
|
+
* When omitted, the gateway's configured default agent handles the request.
|
|
9
|
+
*/
|
|
6
10
|
agentId?: string;
|
|
11
|
+
/**
|
|
12
|
+
* Agent target, not a backend model name. The gateway resolves this to an
|
|
13
|
+
* agent: `openclaw`, `openclaw/default`, or `openclaw/<agentId>`.
|
|
14
|
+
*
|
|
15
|
+
* @default "openclaw/default"
|
|
16
|
+
*/
|
|
7
17
|
model?: string;
|
|
8
18
|
temperature?: number;
|
|
9
19
|
maxTokens?: number;
|
|
20
|
+
/**
|
|
21
|
+
* Pins the conversation to a server-side session on the gateway.
|
|
22
|
+
*
|
|
23
|
+
* The gateway keeps conversation state itself, but without an identifier it
|
|
24
|
+
* opens a fresh session per request: nothing is persisted between turns and
|
|
25
|
+
* each one strands a throwaway session. Sending this as the `user` field makes
|
|
26
|
+
* the gateway derive a stable session key from it.
|
|
27
|
+
*
|
|
28
|
+
* When set, past turns are not resent — the gateway already holds them. The
|
|
29
|
+
* system prompt is still sent every turn so the persona survives a dropped
|
|
30
|
+
* session.
|
|
31
|
+
*
|
|
32
|
+
* Treat it as a conversation-scoped identifier (e.g. a UUID per conversation,
|
|
33
|
+
* rotated when the user resets the chat). Rotating it is the only way to reset
|
|
34
|
+
* the conversation; the gateway keeps the old transcript under the old key.
|
|
35
|
+
*/
|
|
36
|
+
sessionKey?: string;
|
|
10
37
|
dangerouslyAllowBrowser?: boolean;
|
|
11
38
|
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
* Stateless 설계: 세션 관리는 외부에서 담당하고, 이 클라이언트는 API 호출만 담당
|
|
21
|
-
*/
|
|
22
|
-
declare class OpenClawLLMClient implements LLMClient {
|
|
23
|
-
private provider;
|
|
24
|
-
constructor(config: OpenClawLLMClientConfig);
|
|
25
|
-
call(messages: Array<{
|
|
39
|
+
declare class OpenClawLLMProvider implements LLMProvider {
|
|
40
|
+
private openai;
|
|
41
|
+
private model;
|
|
42
|
+
private temperature;
|
|
43
|
+
private maxTokens;
|
|
44
|
+
private sessionKey?;
|
|
45
|
+
constructor(config: OpenClawLLMConfig);
|
|
46
|
+
generateResponse(messages: Array<{
|
|
26
47
|
role: string;
|
|
27
48
|
content: string;
|
|
28
49
|
}>): Promise<string>;
|
|
50
|
+
/**
|
|
51
|
+
* With a pinned session the gateway already holds the past turns, and resending
|
|
52
|
+
* them would flatten a duplicate copy of the history on top of its own. Keep the
|
|
53
|
+
* system prompts (cheap persona insurance if the session was dropped) and the
|
|
54
|
+
* latest turn.
|
|
55
|
+
*/
|
|
56
|
+
private selectMessages;
|
|
29
57
|
}
|
|
30
|
-
declare function
|
|
58
|
+
declare function createOpenClawLLMProvider(config: OpenClawLLMConfig): OpenClawLLMProvider;
|
|
59
|
+
|
|
60
|
+
type OpenClawLLMClientConfig = Omit<OpenClawLLMConfig, "sessionKey">;
|
|
61
|
+
declare function createOpenClawLLMClient(config: OpenClawLLMClientConfig): LLMClient;
|
|
31
62
|
|
|
32
|
-
export {
|
|
63
|
+
export { type OpenClawLLMClientConfig, type OpenClawLLMConfig, OpenClawLLMProvider, createOpenClawLLMClient, createOpenClawLLMProvider };
|
package/dist/openclaw/index.d.ts
CHANGED
|
@@ -1,32 +1,63 @@
|
|
|
1
|
-
import { LLMClient } from '@charivo/core';
|
|
1
|
+
import { LLMProvider, LLMClient } from '@charivo/core';
|
|
2
2
|
|
|
3
3
|
interface OpenClawLLMConfig {
|
|
4
4
|
token: string;
|
|
5
5
|
baseURL?: string;
|
|
6
|
+
/**
|
|
7
|
+
* Target a specific agent on the gateway.
|
|
8
|
+
* When omitted, the gateway's configured default agent handles the request.
|
|
9
|
+
*/
|
|
6
10
|
agentId?: string;
|
|
11
|
+
/**
|
|
12
|
+
* Agent target, not a backend model name. The gateway resolves this to an
|
|
13
|
+
* agent: `openclaw`, `openclaw/default`, or `openclaw/<agentId>`.
|
|
14
|
+
*
|
|
15
|
+
* @default "openclaw/default"
|
|
16
|
+
*/
|
|
7
17
|
model?: string;
|
|
8
18
|
temperature?: number;
|
|
9
19
|
maxTokens?: number;
|
|
20
|
+
/**
|
|
21
|
+
* Pins the conversation to a server-side session on the gateway.
|
|
22
|
+
*
|
|
23
|
+
* The gateway keeps conversation state itself, but without an identifier it
|
|
24
|
+
* opens a fresh session per request: nothing is persisted between turns and
|
|
25
|
+
* each one strands a throwaway session. Sending this as the `user` field makes
|
|
26
|
+
* the gateway derive a stable session key from it.
|
|
27
|
+
*
|
|
28
|
+
* When set, past turns are not resent — the gateway already holds them. The
|
|
29
|
+
* system prompt is still sent every turn so the persona survives a dropped
|
|
30
|
+
* session.
|
|
31
|
+
*
|
|
32
|
+
* Treat it as a conversation-scoped identifier (e.g. a UUID per conversation,
|
|
33
|
+
* rotated when the user resets the chat). Rotating it is the only way to reset
|
|
34
|
+
* the conversation; the gateway keeps the old transcript under the old key.
|
|
35
|
+
*/
|
|
36
|
+
sessionKey?: string;
|
|
10
37
|
dangerouslyAllowBrowser?: boolean;
|
|
11
38
|
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
* Stateless 설계: 세션 관리는 외부에서 담당하고, 이 클라이언트는 API 호출만 담당
|
|
21
|
-
*/
|
|
22
|
-
declare class OpenClawLLMClient implements LLMClient {
|
|
23
|
-
private provider;
|
|
24
|
-
constructor(config: OpenClawLLMClientConfig);
|
|
25
|
-
call(messages: Array<{
|
|
39
|
+
declare class OpenClawLLMProvider implements LLMProvider {
|
|
40
|
+
private openai;
|
|
41
|
+
private model;
|
|
42
|
+
private temperature;
|
|
43
|
+
private maxTokens;
|
|
44
|
+
private sessionKey?;
|
|
45
|
+
constructor(config: OpenClawLLMConfig);
|
|
46
|
+
generateResponse(messages: Array<{
|
|
26
47
|
role: string;
|
|
27
48
|
content: string;
|
|
28
49
|
}>): Promise<string>;
|
|
50
|
+
/**
|
|
51
|
+
* With a pinned session the gateway already holds the past turns, and resending
|
|
52
|
+
* them would flatten a duplicate copy of the history on top of its own. Keep the
|
|
53
|
+
* system prompts (cheap persona insurance if the session was dropped) and the
|
|
54
|
+
* latest turn.
|
|
55
|
+
*/
|
|
56
|
+
private selectMessages;
|
|
29
57
|
}
|
|
30
|
-
declare function
|
|
58
|
+
declare function createOpenClawLLMProvider(config: OpenClawLLMConfig): OpenClawLLMProvider;
|
|
59
|
+
|
|
60
|
+
type OpenClawLLMClientConfig = Omit<OpenClawLLMConfig, "sessionKey">;
|
|
61
|
+
declare function createOpenClawLLMClient(config: OpenClawLLMClientConfig): LLMClient;
|
|
31
62
|
|
|
32
|
-
export {
|
|
63
|
+
export { type OpenClawLLMClientConfig, type OpenClawLLMConfig, OpenClawLLMProvider, createOpenClawLLMClient, createOpenClawLLMProvider };
|