@charivo/llm 0.4.2 → 0.5.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 CHANGED
@@ -53,14 +53,8 @@ Use `maxHistoryTurns: null` to opt out and keep unbounded history.
53
53
 
54
54
  ## Exports
55
55
 
56
- - `LLMManager`
57
56
  - `createLLMManager(client, options?)`
58
57
  - `LLMManagerOptions`
59
- - `CharacterPromptBuilder`
60
- - `MessageHistoryManager`
61
- - `MessageConverter`
62
- - `ResponseMessageBuilder`
63
- - `LLMValidators`
64
58
 
65
59
  ## Manager API
66
60
 
package/dist/index.d.mts CHANGED
@@ -1,125 +1,11 @@
1
- import { Character, Message, LLMClient } from '@charivo/core';
2
-
3
- /**
4
- * 캐릭터 정보를 시스템 프롬프트로 변환하는 유틸리티
5
- */
6
- declare class CharacterPromptBuilder {
7
- static buildSystemPrompt(character: Character): string;
8
- static buildSystemPromptOrDefault(character?: Character): string;
9
- }
10
-
11
- interface MessageHistoryManagerOptions {
12
- maxMessages?: number | null;
13
- pruneBatchSize?: number;
14
- }
15
- interface AddMessageOptions {
16
- /**
17
- * Internal escape hatch for workflows that need multiple appends to become
18
- * visible as one pruning boundary, such as user/assistant turn pairs.
19
- */
20
- prune?: boolean;
21
- }
22
- /**
23
- * 메시지 히스토리 관리
24
- */
25
- declare class MessageHistoryManager {
26
- private history;
27
- private readonly maxMessages?;
28
- private readonly pruneBatchSize;
29
- constructor(options?: MessageHistoryManagerOptions);
30
- add(message: Message, options?: AddMessageOptions): void;
31
- removeLast(): Message | undefined;
32
- clear(): void;
33
- getAll(): Message[];
34
- getRecent(maxMessages?: number): Message[];
35
- size(): number;
36
- pruneToMax(): void;
37
- }
38
-
39
- /**
40
- * 메시지 형식 변환 유틸리티
41
- */
42
- declare class MessageConverter {
43
- /**
44
- * Charivo Message를 OpenAI 형식으로 변환
45
- */
46
- static toOpenAIFormat(messages: Message[]): Array<{
47
- role: string;
48
- content: string;
49
- }>;
50
- /**
51
- * 시스템 프롬프트와 메시지들을 OpenAI 형식으로 결합
52
- */
53
- static combineWithSystemPrompt(systemPrompt: string, messages: Message[]): Array<{
54
- role: string;
55
- content: string;
56
- }>;
57
- }
58
-
59
- /**
60
- * AI 응답 메시지 생성 헬퍼
61
- */
62
- declare class ResponseMessageBuilder {
63
- static create(content: string, characterId: string, messageId?: string): Message;
64
- }
65
-
66
- /**
67
- * LLM 관련 검증 유틸리티
68
- */
69
- declare class LLMValidators {
70
- static validateCharacterSet(character: Character | null): asserts character is Character;
71
- static validateMessage(message: Message): void;
72
- }
1
+ import { LLMClient, LLMManager } from '@charivo/core';
73
2
 
74
3
  interface LLMManagerOptions {
75
4
  maxHistoryTurns?: number | null;
76
5
  }
77
6
  /**
78
- * LLM Manager - LLM 세션의 상태 관리를 담당하는 클래스
79
- *
80
- * 역할:
81
- * - 캐릭터 설정 및 관리
82
- * - 메시지 히스토리 관리
83
- * - LLM 클라이언트와의 통신
84
- * - 메시지 형식 변환
85
- * - 프롬프트 생성
86
- */
87
- declare class LLMManager {
88
- private llmClient;
89
- private readonly historyManager;
90
- private readonly maxHistoryMessages?;
91
- private character;
92
- constructor(llmClient: LLMClient, options?: LLMManagerOptions);
93
- /**
94
- * 캐릭터 설정
95
- * 캐릭터가 변경되는 경우에만 히스토리를 초기화합니다.
96
- */
97
- setCharacter(character: Character): void;
98
- /**
99
- * 현재 설정된 캐릭터 반환
100
- */
101
- getCharacter(): Character | null;
102
- /**
103
- * 히스토리 초기화
104
- */
105
- clearHistory(): void;
106
- /**
107
- * 현재 히스토리 반환
108
- */
109
- getHistory(): Message[];
110
- /**
111
- * 메시지 응답 생성
112
- */
113
- generateResponse(message: Message): Promise<string>;
114
- /**
115
- * LLM API 호출을 위한 메시지 준비
116
- */
117
- private prepareApiMessages;
118
- private getHistoryForApiCall;
119
- }
120
- /**
121
- * LLM Manager 생성 헬퍼 함수
7
+ * Helper function to create an LLM Manager
122
8
  */
123
9
  declare function createLLMManager(llmClient: LLMClient, options?: LLMManagerOptions): LLMManager;
124
10
 
125
- export { type AddMessageOptions, CharacterPromptBuilder, LLMManager, type LLMManagerOptions, LLMValidators, MessageConverter, MessageHistoryManager, type MessageHistoryManagerOptions, ResponseMessageBuilder, createLLMManager };
11
+ export { type LLMManagerOptions, createLLMManager };
package/dist/index.d.ts CHANGED
@@ -1,125 +1,11 @@
1
- import { Character, Message, LLMClient } from '@charivo/core';
2
-
3
- /**
4
- * 캐릭터 정보를 시스템 프롬프트로 변환하는 유틸리티
5
- */
6
- declare class CharacterPromptBuilder {
7
- static buildSystemPrompt(character: Character): string;
8
- static buildSystemPromptOrDefault(character?: Character): string;
9
- }
10
-
11
- interface MessageHistoryManagerOptions {
12
- maxMessages?: number | null;
13
- pruneBatchSize?: number;
14
- }
15
- interface AddMessageOptions {
16
- /**
17
- * Internal escape hatch for workflows that need multiple appends to become
18
- * visible as one pruning boundary, such as user/assistant turn pairs.
19
- */
20
- prune?: boolean;
21
- }
22
- /**
23
- * 메시지 히스토리 관리
24
- */
25
- declare class MessageHistoryManager {
26
- private history;
27
- private readonly maxMessages?;
28
- private readonly pruneBatchSize;
29
- constructor(options?: MessageHistoryManagerOptions);
30
- add(message: Message, options?: AddMessageOptions): void;
31
- removeLast(): Message | undefined;
32
- clear(): void;
33
- getAll(): Message[];
34
- getRecent(maxMessages?: number): Message[];
35
- size(): number;
36
- pruneToMax(): void;
37
- }
38
-
39
- /**
40
- * 메시지 형식 변환 유틸리티
41
- */
42
- declare class MessageConverter {
43
- /**
44
- * Charivo Message를 OpenAI 형식으로 변환
45
- */
46
- static toOpenAIFormat(messages: Message[]): Array<{
47
- role: string;
48
- content: string;
49
- }>;
50
- /**
51
- * 시스템 프롬프트와 메시지들을 OpenAI 형식으로 결합
52
- */
53
- static combineWithSystemPrompt(systemPrompt: string, messages: Message[]): Array<{
54
- role: string;
55
- content: string;
56
- }>;
57
- }
58
-
59
- /**
60
- * AI 응답 메시지 생성 헬퍼
61
- */
62
- declare class ResponseMessageBuilder {
63
- static create(content: string, characterId: string, messageId?: string): Message;
64
- }
65
-
66
- /**
67
- * LLM 관련 검증 유틸리티
68
- */
69
- declare class LLMValidators {
70
- static validateCharacterSet(character: Character | null): asserts character is Character;
71
- static validateMessage(message: Message): void;
72
- }
1
+ import { LLMClient, LLMManager } from '@charivo/core';
73
2
 
74
3
  interface LLMManagerOptions {
75
4
  maxHistoryTurns?: number | null;
76
5
  }
77
6
  /**
78
- * LLM Manager - LLM 세션의 상태 관리를 담당하는 클래스
79
- *
80
- * 역할:
81
- * - 캐릭터 설정 및 관리
82
- * - 메시지 히스토리 관리
83
- * - LLM 클라이언트와의 통신
84
- * - 메시지 형식 변환
85
- * - 프롬프트 생성
86
- */
87
- declare class LLMManager {
88
- private llmClient;
89
- private readonly historyManager;
90
- private readonly maxHistoryMessages?;
91
- private character;
92
- constructor(llmClient: LLMClient, options?: LLMManagerOptions);
93
- /**
94
- * 캐릭터 설정
95
- * 캐릭터가 변경되는 경우에만 히스토리를 초기화합니다.
96
- */
97
- setCharacter(character: Character): void;
98
- /**
99
- * 현재 설정된 캐릭터 반환
100
- */
101
- getCharacter(): Character | null;
102
- /**
103
- * 히스토리 초기화
104
- */
105
- clearHistory(): void;
106
- /**
107
- * 현재 히스토리 반환
108
- */
109
- getHistory(): Message[];
110
- /**
111
- * 메시지 응답 생성
112
- */
113
- generateResponse(message: Message): Promise<string>;
114
- /**
115
- * LLM API 호출을 위한 메시지 준비
116
- */
117
- private prepareApiMessages;
118
- private getHistoryForApiCall;
119
- }
120
- /**
121
- * LLM Manager 생성 헬퍼 함수
7
+ * Helper function to create an LLM Manager
122
8
  */
123
9
  declare function createLLMManager(llmClient: LLMClient, options?: LLMManagerOptions): LLMManager;
124
10
 
125
- export { type AddMessageOptions, CharacterPromptBuilder, LLMManager, type LLMManagerOptions, LLMValidators, MessageConverter, MessageHistoryManager, type MessageHistoryManagerOptions, ResponseMessageBuilder, createLLMManager };
11
+ export { type LLMManagerOptions, createLLMManager };
package/dist/index.js CHANGED
@@ -2,25 +2,7 @@
2
2
 
3
3
  var core = require('@charivo/core');
4
4
 
5
- // src/character-prompt-builder.ts
6
- var CharacterPromptBuilder = class {
7
- static buildSystemPrompt(character) {
8
- const name = character.name;
9
- const description = character.description || "";
10
- const personality = character.personality || "";
11
- return `You are ${name}. ${description} ${personality}
12
-
13
- Respond naturally in plain text with no bracketed emotion tags or control markup.`.trim();
14
- }
15
- static buildSystemPromptOrDefault(character) {
16
- if (character) {
17
- return this.buildSystemPrompt(character);
18
- }
19
- return `You are a helpful assistant.
20
-
21
- Respond naturally in plain text with no bracketed emotion tags or control markup.`.trim();
22
- }
23
- };
5
+ // src/llm-manager.ts
24
6
 
25
7
  // src/message-history-manager.ts
26
8
  var MessageHistoryManager = class {
@@ -79,10 +61,30 @@ var MessageHistoryManager = class {
79
61
  }
80
62
  };
81
63
 
64
+ // src/character-prompt-builder.ts
65
+ var CharacterPromptBuilder = class {
66
+ static buildSystemPrompt(character) {
67
+ const name = character.name;
68
+ const description = character.description || "";
69
+ const personality = character.personality || "";
70
+ return `You are ${name}. ${description} ${personality}
71
+
72
+ Respond naturally in plain text with no bracketed emotion tags or control markup.`.trim();
73
+ }
74
+ static buildSystemPromptOrDefault(character) {
75
+ if (character) {
76
+ return this.buildSystemPrompt(character);
77
+ }
78
+ return `You are a helpful assistant.
79
+
80
+ Respond naturally in plain text with no bracketed emotion tags or control markup.`.trim();
81
+ }
82
+ };
83
+
82
84
  // src/message-converter.ts
83
85
  var MessageConverter = class {
84
86
  /**
85
- * Charivo Message를 OpenAI 형식으로 변환
87
+ * Convert a Charivo Message to the OpenAI format
86
88
  */
87
89
  static toOpenAIFormat(messages) {
88
90
  return messages.map((msg) => ({
@@ -91,7 +93,7 @@ var MessageConverter = class {
91
93
  }));
92
94
  }
93
95
  /**
94
- * 시스템 프롬프트와 메시지들을 OpenAI 형식으로 결합
96
+ * Combine the system prompt and messages into the OpenAI format
95
97
  */
96
98
  static combineWithSystemPrompt(systemPrompt, messages) {
97
99
  return [
@@ -101,19 +103,6 @@ var MessageConverter = class {
101
103
  }
102
104
  };
103
105
 
104
- // src/response-message-builder.ts
105
- var ResponseMessageBuilder = class {
106
- static create(content, characterId, messageId) {
107
- return {
108
- id: messageId || "ai-" + Date.now(),
109
- content,
110
- timestamp: /* @__PURE__ */ new Date(),
111
- type: "character",
112
- characterId
113
- };
114
- }
115
- };
116
-
117
106
  // src/validators.ts
118
107
  var LLMValidators = class {
119
108
  static validateCharacterSet(character) {
@@ -127,6 +116,21 @@ var LLMValidators = class {
127
116
  }
128
117
  }
129
118
  };
119
+
120
+ // src/response-message-builder.ts
121
+ var ResponseMessageBuilder = class {
122
+ static create(content, characterId, messageId) {
123
+ return {
124
+ id: messageId || "ai-" + Date.now(),
125
+ content,
126
+ timestamp: /* @__PURE__ */ new Date(),
127
+ type: "character",
128
+ characterId
129
+ };
130
+ }
131
+ };
132
+
133
+ // src/llm-manager.ts
130
134
  var DEFAULT_MAX_HISTORY_TURNS = 40;
131
135
  var LLMManager = class {
132
136
  constructor(llmClient, options = {}) {
@@ -141,8 +145,8 @@ var LLMManager = class {
141
145
  maxHistoryMessages;
142
146
  character = null;
143
147
  /**
144
- * 캐릭터 설정
145
- * 캐릭터가 변경되는 경우에만 히스토리를 초기화합니다.
148
+ * Set the character
149
+ * Clears the history only when the character changes.
146
150
  */
147
151
  setCharacter(character) {
148
152
  if (this.character?.id !== character.id) {
@@ -151,25 +155,25 @@ var LLMManager = class {
151
155
  this.character = character;
152
156
  }
153
157
  /**
154
- * 현재 설정된 캐릭터 반환
158
+ * Return the currently configured character
155
159
  */
156
160
  getCharacter() {
157
161
  return this.character;
158
162
  }
159
163
  /**
160
- * 히스토리 초기화
164
+ * Clear the history
161
165
  */
162
166
  clearHistory() {
163
167
  this.historyManager.clear();
164
168
  }
165
169
  /**
166
- * 현재 히스토리 반환
170
+ * Return the current history
167
171
  */
168
172
  getHistory() {
169
173
  return this.historyManager.getAll();
170
174
  }
171
175
  /**
172
- * 메시지 응답 생성
176
+ * Generate a response to a message
173
177
  */
174
178
  async generateResponse(message) {
175
179
  try {
@@ -186,7 +190,7 @@ var LLMManager = class {
186
190
  const responseMessage = ResponseMessageBuilder.create(
187
191
  assistantMessage,
188
192
  this.character.id
189
- // validateCharacterSet 후 character는 non-null 보장됨
193
+ // character is guaranteed non-null after validateCharacterSet
190
194
  );
191
195
  this.historyManager.add(responseMessage, { prune: false });
192
196
  this.historyManager.pruneToMax();
@@ -197,7 +201,7 @@ var LLMManager = class {
197
201
  }
198
202
  }
199
203
  /**
200
- * LLM API 호출을 위한 메시지 준비
204
+ * Prepare messages for the LLM API call
201
205
  */
202
206
  prepareApiMessages(messages) {
203
207
  if (!this.character) {
@@ -232,12 +236,6 @@ function resolveMaxHistoryMessages(options) {
232
236
  return maxHistoryTurns * 2;
233
237
  }
234
238
 
235
- exports.CharacterPromptBuilder = CharacterPromptBuilder;
236
- exports.LLMManager = LLMManager;
237
- exports.LLMValidators = LLMValidators;
238
- exports.MessageConverter = MessageConverter;
239
- exports.MessageHistoryManager = MessageHistoryManager;
240
- exports.ResponseMessageBuilder = ResponseMessageBuilder;
241
239
  exports.createLLMManager = createLLMManager;
242
240
  //# sourceMappingURL=index.js.map
243
241
  //# sourceMappingURL=index.js.map
package/dist/index.js.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":["toCharivoError"],"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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A,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.js","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","../src/message-converter.ts","../src/validators.ts","../src/response-message-builder.ts","../src/llm-manager.ts"],"names":["toCharivoError"],"mappings":";;;;;;;AAkBO,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,I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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.js","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"]}