chatgsd 0.0.1 → 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/README.md +246 -3
- package/dist/index.cjs +436 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +66 -0
- package/dist/index.d.ts +66 -0
- package/dist/index.js +409 -0
- package/dist/index.js.map +1 -0
- package/dist/styles.css +236 -0
- package/package.json +45 -6
- package/index.js +0 -1
- package/tsconfig.json +0 -113
package/README.md
CHANGED
|
@@ -1,4 +1,247 @@
|
|
|
1
|
-
#
|
|
1
|
+
# ChatGSD
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
3
|
+
A conversational UI component where AI orchestrates the interface. The AI decides when to show calendars, collect payments, submit forms — chat becomes the control layer.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install chatgsd
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Quick Start
|
|
12
|
+
|
|
13
|
+
```tsx
|
|
14
|
+
import { ChatGSD } from "chatgsd";
|
|
15
|
+
import "chatgsd/styles.css";
|
|
16
|
+
|
|
17
|
+
function App() {
|
|
18
|
+
return (
|
|
19
|
+
<ChatGSD
|
|
20
|
+
endpoint="/api/chat"
|
|
21
|
+
brandName="assistant"
|
|
22
|
+
initialMessage="Hey! How can I help you today?"
|
|
23
|
+
/>
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## How It Works
|
|
29
|
+
|
|
30
|
+
Your backend streams responses to the chat. ChatGSD supports two formats:
|
|
31
|
+
|
|
32
|
+
### SSE Format (recommended)
|
|
33
|
+
|
|
34
|
+
Server-Sent Events with JSON payloads. Auto-detected via `Content-Type: text/event-stream`.
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
data: {"type": "text", "content": "Let me "}
|
|
38
|
+
data: {"type": "text", "content": "show you "}
|
|
39
|
+
data: {"type": "text", "content": "available times."}
|
|
40
|
+
data: {"type": "tool_call", "name": "show_slots", "args": {}}
|
|
41
|
+
data: {"type": "done"}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Plain Text Format
|
|
45
|
+
|
|
46
|
+
Raw streaming text with tool calls embedded. Falls back to this when not SSE.
|
|
47
|
+
|
|
48
|
+
```
|
|
49
|
+
Let me show you available times.
|
|
50
|
+
|
|
51
|
+
[TOOL:show_slots]
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Or with arguments:
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
[TOOL:show_slots({"date": "2024-01-15"})]
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Tools
|
|
61
|
+
|
|
62
|
+
Tools are handlers that run when the AI invokes them. They can render UI, call APIs, update parent state — anything.
|
|
63
|
+
|
|
64
|
+
```tsx
|
|
65
|
+
import { ChatGSD, Tool } from "chatgsd";
|
|
66
|
+
|
|
67
|
+
const tools: Record<string, Tool> = {
|
|
68
|
+
show_slots: {
|
|
69
|
+
handler: async (args, messages) => {
|
|
70
|
+
// Fetch data, update state, etc.
|
|
71
|
+
return { success: true };
|
|
72
|
+
},
|
|
73
|
+
renderSuccess: () => (
|
|
74
|
+
<div className="slots">
|
|
75
|
+
{slots.map(slot => (
|
|
76
|
+
<button key={slot.id} onClick={() => selectSlot(slot)}>
|
|
77
|
+
{slot.time}
|
|
78
|
+
</button>
|
|
79
|
+
))}
|
|
80
|
+
</div>
|
|
81
|
+
),
|
|
82
|
+
},
|
|
83
|
+
|
|
84
|
+
submit_inquiry: {
|
|
85
|
+
terminal: true, // Ends the conversation
|
|
86
|
+
handler: async (args, messages) => {
|
|
87
|
+
await fetch("/api/submit", {
|
|
88
|
+
method: "POST",
|
|
89
|
+
body: JSON.stringify({ messages }),
|
|
90
|
+
});
|
|
91
|
+
return { success: true, message: "Submitted!" };
|
|
92
|
+
},
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
<ChatGSD endpoint="/api/chat" tools={tools} />
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Tool Configuration
|
|
100
|
+
|
|
101
|
+
| Property | Type | Description |
|
|
102
|
+
|----------|------|-------------|
|
|
103
|
+
| `handler` | `(args, messages) => Promise<ToolResult>` | Called when tool is invoked |
|
|
104
|
+
| `terminal` | `boolean` | If true, ends the conversation |
|
|
105
|
+
| `renderCalling` | `() => ReactNode` | Custom UI while tool is running |
|
|
106
|
+
| `renderSuccess` | `(result) => ReactNode` | Custom UI on success |
|
|
107
|
+
| `renderError` | `(result) => ReactNode` | Custom UI on error |
|
|
108
|
+
|
|
109
|
+
### ToolResult
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
interface ToolResult {
|
|
113
|
+
success: boolean;
|
|
114
|
+
message?: string;
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
## Props
|
|
119
|
+
|
|
120
|
+
| Prop | Type | Default | Description |
|
|
121
|
+
|------|------|---------|-------------|
|
|
122
|
+
| `endpoint` | `string` | `"/api/chat"` | Chat API endpoint |
|
|
123
|
+
| `tools` | `Record<string, Tool>` | `{}` | Tool definitions |
|
|
124
|
+
| `context` | `Record<string, unknown>` | `{}` | Context sent with each request |
|
|
125
|
+
| `headers` | `Record<string, string>` | `{}` | Custom headers for API requests |
|
|
126
|
+
| `brandName` | `string` | `"assistant"` | Name shown in chat |
|
|
127
|
+
| `initialMessage` | `string` | `"How can I help?"` | First message displayed |
|
|
128
|
+
| `className` | `string` | `""` | Additional CSS class |
|
|
129
|
+
| `format` | `"auto" \| "sse" \| "text"` | `"auto"` | Stream format (auto-detects from Content-Type) |
|
|
130
|
+
| `onMessagesChange` | `(messages) => void` | - | Called when messages update |
|
|
131
|
+
| `onComplete` | `(messages) => void` | - | Called when conversation ends |
|
|
132
|
+
|
|
133
|
+
## Backend API
|
|
134
|
+
|
|
135
|
+
The component expects a streaming endpoint that accepts:
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
// Request
|
|
139
|
+
{
|
|
140
|
+
messages: Array<{ role: "system" | "user", content: string }>,
|
|
141
|
+
context: Record<string, unknown>
|
|
142
|
+
}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### SSE Response (Node.js)
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
app.post("/api/chat", async (req, res) => {
|
|
149
|
+
const { messages, context } = req.body;
|
|
150
|
+
|
|
151
|
+
res.setHeader("Content-Type", "text/event-stream");
|
|
152
|
+
res.setHeader("Cache-Control", "no-cache");
|
|
153
|
+
res.setHeader("Connection", "keep-alive");
|
|
154
|
+
|
|
155
|
+
const stream = await openai.chat.completions.create({
|
|
156
|
+
model: "gpt-4",
|
|
157
|
+
stream: true,
|
|
158
|
+
messages: [
|
|
159
|
+
{
|
|
160
|
+
role: "system",
|
|
161
|
+
content: `You are a helpful assistant. Available tools:
|
|
162
|
+
- show_slots: Show available meeting times
|
|
163
|
+
- submit_inquiry: Submit the inquiry
|
|
164
|
+
|
|
165
|
+
When you want to use a tool, I'll signal it in the stream.`
|
|
166
|
+
},
|
|
167
|
+
...messages
|
|
168
|
+
],
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
for await (const chunk of stream) {
|
|
172
|
+
const text = chunk.choices[0]?.delta?.content || "";
|
|
173
|
+
if (text) {
|
|
174
|
+
res.write(`data: ${JSON.stringify({ type: "text", content: text })}\n\n`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Send tool call if needed (based on your logic)
|
|
179
|
+
res.write(`data: ${JSON.stringify({ type: "tool_call", name: "show_slots", args: {} })}\n\n`);
|
|
180
|
+
res.write(`data: ${JSON.stringify({ type: "done" })}\n\n`);
|
|
181
|
+
res.end();
|
|
182
|
+
});
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### With Vercel AI SDK
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
import { streamText, tool } from "ai";
|
|
189
|
+
import { openai } from "@ai-sdk/openai";
|
|
190
|
+
|
|
191
|
+
export async function POST(req: Request) {
|
|
192
|
+
const { messages, context } = await req.json();
|
|
193
|
+
|
|
194
|
+
const result = await streamText({
|
|
195
|
+
model: openai("gpt-4"),
|
|
196
|
+
messages,
|
|
197
|
+
tools: {
|
|
198
|
+
show_slots: tool({
|
|
199
|
+
description: "Show available meeting times",
|
|
200
|
+
parameters: z.object({ date: z.string().optional() }),
|
|
201
|
+
}),
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
// AI SDK streams in a compatible format
|
|
206
|
+
return result.toDataStreamResponse();
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
## Styling
|
|
211
|
+
|
|
212
|
+
Import the default styles:
|
|
213
|
+
|
|
214
|
+
```tsx
|
|
215
|
+
import "chatgsd/styles.css";
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
Customize with CSS variables:
|
|
219
|
+
|
|
220
|
+
```css
|
|
221
|
+
:root {
|
|
222
|
+
--chatgsd-bg: #0a0a0a;
|
|
223
|
+
--chatgsd-border: #333;
|
|
224
|
+
--chatgsd-green: #27ca40;
|
|
225
|
+
--chatgsd-yellow: #ffbd2e;
|
|
226
|
+
--chatgsd-red: #ff5f56;
|
|
227
|
+
--chatgsd-text: #e0e0e0;
|
|
228
|
+
--chatgsd-muted: #666;
|
|
229
|
+
--chatgsd-font: ui-monospace, monospace;
|
|
230
|
+
}
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
Or write your own styles targeting `.chatgsd-*` classes.
|
|
234
|
+
|
|
235
|
+
## Example
|
|
236
|
+
|
|
237
|
+
Run the example app:
|
|
238
|
+
|
|
239
|
+
```bash
|
|
240
|
+
cd example
|
|
241
|
+
npm install
|
|
242
|
+
npm run dev
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
## License
|
|
246
|
+
|
|
247
|
+
MIT
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,436 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
ChatGSD: () => ChatGSD
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(index_exports);
|
|
26
|
+
|
|
27
|
+
// src/ChatGSD.tsx
|
|
28
|
+
var import_react = require("react");
|
|
29
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
30
|
+
function generateId() {
|
|
31
|
+
return Math.random().toString(36).substring(2, 11);
|
|
32
|
+
}
|
|
33
|
+
function parseSSELine(line) {
|
|
34
|
+
if (!line.startsWith("data: ")) return null;
|
|
35
|
+
const data = line.slice(6);
|
|
36
|
+
if (data === "[DONE]") return { type: "done" };
|
|
37
|
+
try {
|
|
38
|
+
const parsed = JSON.parse(data);
|
|
39
|
+
if (parsed.type === "text-delta" || parsed.type === "text_delta") {
|
|
40
|
+
return { type: "text", content: parsed.textDelta ?? parsed.text_delta ?? "" };
|
|
41
|
+
}
|
|
42
|
+
if (parsed.type === "tool-call" || parsed.type === "tool_call") {
|
|
43
|
+
return {
|
|
44
|
+
type: "tool_call",
|
|
45
|
+
name: parsed.toolName ?? parsed.tool_name ?? parsed.name,
|
|
46
|
+
args: parsed.args ?? parsed.arguments ?? {}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
if (parsed.type === "text") {
|
|
50
|
+
return { type: "text", content: parsed.content ?? "" };
|
|
51
|
+
}
|
|
52
|
+
if (parsed.type === "tool_call") {
|
|
53
|
+
return { type: "tool_call", name: parsed.name, args: parsed.args ?? {} };
|
|
54
|
+
}
|
|
55
|
+
if (parsed.type === "error") {
|
|
56
|
+
return { type: "error", message: parsed.message ?? "Unknown error" };
|
|
57
|
+
}
|
|
58
|
+
if (parsed.type === "done") {
|
|
59
|
+
return { type: "done" };
|
|
60
|
+
}
|
|
61
|
+
if (parsed.choices?.[0]?.delta?.content) {
|
|
62
|
+
return { type: "text", content: parsed.choices[0].delta.content };
|
|
63
|
+
}
|
|
64
|
+
return null;
|
|
65
|
+
} catch {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function parseToolCallFromText(content) {
|
|
70
|
+
const match = content.match(/\[TOOL:(\w+)(?:\((\{.*\})\))?\]\s*$/);
|
|
71
|
+
if (!match) return null;
|
|
72
|
+
const name = match[1];
|
|
73
|
+
let args = {};
|
|
74
|
+
if (match[2]) {
|
|
75
|
+
try {
|
|
76
|
+
args = JSON.parse(match[2]);
|
|
77
|
+
} catch {
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return { name, args };
|
|
81
|
+
}
|
|
82
|
+
function stripToolCall(content) {
|
|
83
|
+
return content.replace(/\n?\[TOOL:\w+(?:\(\{.*\}\))?\]\s*$/, "");
|
|
84
|
+
}
|
|
85
|
+
function ChatGSD({
|
|
86
|
+
initialMessage = "How can I help you today?",
|
|
87
|
+
onMessagesChange,
|
|
88
|
+
tools = {},
|
|
89
|
+
endpoint = "/api/chat",
|
|
90
|
+
headers = {},
|
|
91
|
+
context = {},
|
|
92
|
+
brandName = "assistant",
|
|
93
|
+
className = "",
|
|
94
|
+
onComplete,
|
|
95
|
+
format = "auto"
|
|
96
|
+
}) {
|
|
97
|
+
const [messages, setMessages] = (0, import_react.useState)([
|
|
98
|
+
{
|
|
99
|
+
id: generateId(),
|
|
100
|
+
role: "system",
|
|
101
|
+
content: initialMessage,
|
|
102
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
103
|
+
}
|
|
104
|
+
]);
|
|
105
|
+
const [input, setInput] = (0, import_react.useState)("");
|
|
106
|
+
const [cursorVisible, setCursorVisible] = (0, import_react.useState)(true);
|
|
107
|
+
const [isLoading, setIsLoading] = (0, import_react.useState)(false);
|
|
108
|
+
const [conversationEnded, setConversationEnded] = (0, import_react.useState)(false);
|
|
109
|
+
const [activeTool, setActiveTool] = (0, import_react.useState)(null);
|
|
110
|
+
const messagesEndRef = (0, import_react.useRef)(null);
|
|
111
|
+
const inputRef = (0, import_react.useRef)(null);
|
|
112
|
+
const toolTimeoutRef = (0, import_react.useRef)(null);
|
|
113
|
+
(0, import_react.useEffect)(() => {
|
|
114
|
+
const interval = setInterval(() => setCursorVisible((v) => !v), 530);
|
|
115
|
+
return () => clearInterval(interval);
|
|
116
|
+
}, []);
|
|
117
|
+
(0, import_react.useEffect)(() => {
|
|
118
|
+
messagesEndRef.current?.scrollIntoView({
|
|
119
|
+
behavior: "smooth",
|
|
120
|
+
block: "nearest"
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
(0, import_react.useEffect)(() => {
|
|
124
|
+
inputRef.current?.focus();
|
|
125
|
+
}, []);
|
|
126
|
+
(0, import_react.useEffect)(() => {
|
|
127
|
+
return () => {
|
|
128
|
+
if (toolTimeoutRef.current) {
|
|
129
|
+
clearTimeout(toolTimeoutRef.current);
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}, []);
|
|
133
|
+
const executeTool = (0, import_react.useCallback)(
|
|
134
|
+
async (toolName, args, currentMessages) => {
|
|
135
|
+
const tool = tools[toolName];
|
|
136
|
+
if (!tool) {
|
|
137
|
+
console.warn(`Unknown tool: ${toolName}`);
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
setActiveTool({ name: toolName, status: "calling" });
|
|
141
|
+
await new Promise((resolve) => {
|
|
142
|
+
toolTimeoutRef.current = setTimeout(resolve, 800);
|
|
143
|
+
});
|
|
144
|
+
try {
|
|
145
|
+
const result = await tool.handler(args, currentMessages);
|
|
146
|
+
setActiveTool({ name: toolName, status: result.success ? "success" : "error", result });
|
|
147
|
+
if (tool.terminal) {
|
|
148
|
+
setConversationEnded(true);
|
|
149
|
+
onComplete?.(currentMessages);
|
|
150
|
+
}
|
|
151
|
+
} catch (err) {
|
|
152
|
+
const message = err instanceof Error ? err.message : "Tool execution failed";
|
|
153
|
+
setActiveTool({ name: toolName, status: "error", result: { success: false, message } });
|
|
154
|
+
}
|
|
155
|
+
},
|
|
156
|
+
[tools, onComplete]
|
|
157
|
+
);
|
|
158
|
+
const processSSEStream = (0, import_react.useCallback)(
|
|
159
|
+
async (reader, onText) => {
|
|
160
|
+
const decoder = new TextDecoder();
|
|
161
|
+
let buffer = "";
|
|
162
|
+
let toolCall = null;
|
|
163
|
+
while (true) {
|
|
164
|
+
const { done, value } = await reader.read();
|
|
165
|
+
if (done) break;
|
|
166
|
+
buffer += decoder.decode(value, { stream: true });
|
|
167
|
+
const lines = buffer.split("\n");
|
|
168
|
+
buffer = lines.pop() || "";
|
|
169
|
+
for (const line of lines) {
|
|
170
|
+
const event = parseSSELine(line.trim());
|
|
171
|
+
if (!event) continue;
|
|
172
|
+
if (event.type === "text") {
|
|
173
|
+
onText(event.content);
|
|
174
|
+
} else if (event.type === "tool_call") {
|
|
175
|
+
toolCall = event;
|
|
176
|
+
} else if (event.type === "done") {
|
|
177
|
+
return toolCall;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (buffer.trim()) {
|
|
182
|
+
const event = parseSSELine(buffer.trim());
|
|
183
|
+
if (event?.type === "tool_call") {
|
|
184
|
+
toolCall = event;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return toolCall;
|
|
188
|
+
},
|
|
189
|
+
[]
|
|
190
|
+
);
|
|
191
|
+
const processTextStream = (0, import_react.useCallback)(
|
|
192
|
+
async (reader, onText) => {
|
|
193
|
+
const decoder = new TextDecoder();
|
|
194
|
+
let fullContent = "";
|
|
195
|
+
while (true) {
|
|
196
|
+
const { done, value } = await reader.read();
|
|
197
|
+
if (done) break;
|
|
198
|
+
const chunk = decoder.decode(value, { stream: true });
|
|
199
|
+
fullContent += chunk;
|
|
200
|
+
onText(stripToolCall(fullContent));
|
|
201
|
+
}
|
|
202
|
+
const toolCall = parseToolCallFromText(fullContent);
|
|
203
|
+
if (toolCall) {
|
|
204
|
+
return { type: "tool_call", name: toolCall.name, args: toolCall.args };
|
|
205
|
+
}
|
|
206
|
+
return null;
|
|
207
|
+
},
|
|
208
|
+
[]
|
|
209
|
+
);
|
|
210
|
+
const fetchAIResponse = (0, import_react.useCallback)(
|
|
211
|
+
async (updatedMessages) => {
|
|
212
|
+
setIsLoading(true);
|
|
213
|
+
const aiMessageId = generateId();
|
|
214
|
+
const aiMessage = {
|
|
215
|
+
id: aiMessageId,
|
|
216
|
+
role: "system",
|
|
217
|
+
content: "",
|
|
218
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
219
|
+
};
|
|
220
|
+
setMessages((prev) => [...prev, aiMessage]);
|
|
221
|
+
let currentContent = "";
|
|
222
|
+
const updateContent = (content) => {
|
|
223
|
+
currentContent = content;
|
|
224
|
+
setMessages((prev) => {
|
|
225
|
+
const updated = [...prev];
|
|
226
|
+
const msgIndex = updated.findIndex((m) => m.id === aiMessageId);
|
|
227
|
+
if (msgIndex !== -1) {
|
|
228
|
+
updated[msgIndex] = { ...updated[msgIndex], content };
|
|
229
|
+
}
|
|
230
|
+
return updated;
|
|
231
|
+
});
|
|
232
|
+
};
|
|
233
|
+
try {
|
|
234
|
+
const res = await fetch(endpoint, {
|
|
235
|
+
method: "POST",
|
|
236
|
+
headers: {
|
|
237
|
+
"Content-Type": "application/json",
|
|
238
|
+
Accept: "text/event-stream, text/plain",
|
|
239
|
+
...headers
|
|
240
|
+
},
|
|
241
|
+
body: JSON.stringify({
|
|
242
|
+
messages: updatedMessages.map((m) => ({
|
|
243
|
+
role: m.role,
|
|
244
|
+
content: m.content
|
|
245
|
+
})),
|
|
246
|
+
context
|
|
247
|
+
})
|
|
248
|
+
});
|
|
249
|
+
if (!res.ok || !res.body) {
|
|
250
|
+
throw new Error("Failed to fetch response");
|
|
251
|
+
}
|
|
252
|
+
const contentType = res.headers.get("Content-Type") || "";
|
|
253
|
+
const reader = res.body.getReader();
|
|
254
|
+
let useSSE = format === "sse";
|
|
255
|
+
if (format === "auto") {
|
|
256
|
+
useSSE = contentType.includes("text/event-stream");
|
|
257
|
+
}
|
|
258
|
+
let toolCallEvent = null;
|
|
259
|
+
if (useSSE) {
|
|
260
|
+
toolCallEvent = await processSSEStream(reader, (text) => {
|
|
261
|
+
currentContent += text;
|
|
262
|
+
updateContent(currentContent);
|
|
263
|
+
});
|
|
264
|
+
} else {
|
|
265
|
+
toolCallEvent = await processTextStream(reader, updateContent);
|
|
266
|
+
}
|
|
267
|
+
if (toolCallEvent?.type === "tool_call") {
|
|
268
|
+
const finalMessages = [
|
|
269
|
+
...updatedMessages,
|
|
270
|
+
{
|
|
271
|
+
id: aiMessageId,
|
|
272
|
+
role: "system",
|
|
273
|
+
content: currentContent,
|
|
274
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
275
|
+
}
|
|
276
|
+
];
|
|
277
|
+
await executeTool(toolCallEvent.name, toolCallEvent.args, finalMessages);
|
|
278
|
+
}
|
|
279
|
+
} catch (err) {
|
|
280
|
+
console.error("Chat error:", err);
|
|
281
|
+
} finally {
|
|
282
|
+
setIsLoading(false);
|
|
283
|
+
}
|
|
284
|
+
},
|
|
285
|
+
[endpoint, headers, context, format, processSSEStream, processTextStream, executeTool]
|
|
286
|
+
);
|
|
287
|
+
const handleSend = (0, import_react.useCallback)(async () => {
|
|
288
|
+
if (!input.trim() || isLoading || conversationEnded) return;
|
|
289
|
+
const newMessage = {
|
|
290
|
+
id: generateId(),
|
|
291
|
+
role: "user",
|
|
292
|
+
content: input.trim(),
|
|
293
|
+
timestamp: /* @__PURE__ */ new Date()
|
|
294
|
+
};
|
|
295
|
+
const updated = [...messages, newMessage];
|
|
296
|
+
setMessages(updated);
|
|
297
|
+
onMessagesChange?.(updated);
|
|
298
|
+
setInput("");
|
|
299
|
+
await fetchAIResponse(updated);
|
|
300
|
+
}, [input, isLoading, conversationEnded, messages, onMessagesChange, fetchAIResponse]);
|
|
301
|
+
const handleKeyDown = (0, import_react.useCallback)(
|
|
302
|
+
async (e) => {
|
|
303
|
+
if (e.key === "Enter" && !e.shiftKey) {
|
|
304
|
+
e.preventDefault();
|
|
305
|
+
await handleSend();
|
|
306
|
+
}
|
|
307
|
+
},
|
|
308
|
+
[handleSend]
|
|
309
|
+
);
|
|
310
|
+
const downloadTranscript = (0, import_react.useCallback)(() => {
|
|
311
|
+
const transcript = messages.map((m) => `${m.role === "system" ? `[${brandName}]` : "[you]"} ${m.content}`).join("\n\n");
|
|
312
|
+
const blob = new Blob([transcript], { type: "text/plain" });
|
|
313
|
+
const url = URL.createObjectURL(blob);
|
|
314
|
+
const a = document.createElement("a");
|
|
315
|
+
a.href = url;
|
|
316
|
+
a.download = `chat-${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}.txt`;
|
|
317
|
+
a.click();
|
|
318
|
+
URL.revokeObjectURL(url);
|
|
319
|
+
}, [messages, brandName]);
|
|
320
|
+
const renderToolStatus = () => {
|
|
321
|
+
if (!activeTool) return null;
|
|
322
|
+
const tool = tools[activeTool.name];
|
|
323
|
+
const { name, status, result } = activeTool;
|
|
324
|
+
if (status === "calling") {
|
|
325
|
+
if (tool?.renderCalling) {
|
|
326
|
+
return tool.renderCalling();
|
|
327
|
+
}
|
|
328
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-status-calling", children: [
|
|
329
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-message-prefix", children: "[tool]" }),
|
|
330
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "chatgsd-status-spinner", children: [
|
|
331
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-spinner", children: "\u25D0" }),
|
|
332
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
|
|
333
|
+
name,
|
|
334
|
+
"()"
|
|
335
|
+
] })
|
|
336
|
+
] })
|
|
337
|
+
] });
|
|
338
|
+
}
|
|
339
|
+
if (status === "success") {
|
|
340
|
+
if (tool?.renderSuccess && result) {
|
|
341
|
+
return tool.renderSuccess(result);
|
|
342
|
+
}
|
|
343
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-status-success", children: [
|
|
344
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-message-prefix", children: "[tool]" }),
|
|
345
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
|
|
346
|
+
"\u2713 ",
|
|
347
|
+
name,
|
|
348
|
+
"() \u2014 ",
|
|
349
|
+
result?.message || "success"
|
|
350
|
+
] })
|
|
351
|
+
] });
|
|
352
|
+
}
|
|
353
|
+
if (status === "error") {
|
|
354
|
+
if (tool?.renderError && result) {
|
|
355
|
+
return tool.renderError(result);
|
|
356
|
+
}
|
|
357
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-status-error", children: [
|
|
358
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-message-prefix", children: "[tool]" }),
|
|
359
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
|
|
360
|
+
"\u2717 ",
|
|
361
|
+
name,
|
|
362
|
+
"() \u2014 ",
|
|
363
|
+
result?.message || "failed"
|
|
364
|
+
] })
|
|
365
|
+
] });
|
|
366
|
+
}
|
|
367
|
+
return null;
|
|
368
|
+
};
|
|
369
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: `chatgsd ${className}`.trim(), children: [
|
|
370
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-messages", children: [
|
|
371
|
+
messages.map((msg) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "chatgsd-message", children: msg.role === "system" ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-message-system", children: [
|
|
372
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { className: "chatgsd-message-prefix", children: [
|
|
373
|
+
"[",
|
|
374
|
+
brandName,
|
|
375
|
+
"]"
|
|
376
|
+
] }),
|
|
377
|
+
" ",
|
|
378
|
+
msg.content
|
|
379
|
+
] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-message-user", children: [
|
|
380
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-message-prompt", children: ">" }),
|
|
381
|
+
" ",
|
|
382
|
+
msg.content
|
|
383
|
+
] }) }, msg.id)),
|
|
384
|
+
activeTool && activeTool.status !== "idle" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "chatgsd-tool-status", children: renderToolStatus() }),
|
|
385
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { ref: messagesEndRef })
|
|
386
|
+
] }),
|
|
387
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "chatgsd-input-area", children: conversationEnded ? /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-session-complete", children: [
|
|
388
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-session-label", children: "session complete" }),
|
|
389
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(
|
|
390
|
+
"button",
|
|
391
|
+
{
|
|
392
|
+
type: "button",
|
|
393
|
+
onClick: downloadTranscript,
|
|
394
|
+
className: "chatgsd-download-btn",
|
|
395
|
+
children: [
|
|
396
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { children: "\u2193" }),
|
|
397
|
+
" download transcript"
|
|
398
|
+
]
|
|
399
|
+
}
|
|
400
|
+
)
|
|
401
|
+
] }) : /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
|
|
402
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-input-line", children: [
|
|
403
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-message-prompt", children: ">" }),
|
|
404
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { className: "chatgsd-input-display", children: [
|
|
405
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { className: "chatgsd-input-text", children: input }),
|
|
406
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
407
|
+
"span",
|
|
408
|
+
{
|
|
409
|
+
className: `chatgsd-cursor ${cursorVisible ? "chatgsd-cursor-visible" : "chatgsd-cursor-hidden"}`,
|
|
410
|
+
children: "\u2588"
|
|
411
|
+
}
|
|
412
|
+
),
|
|
413
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
414
|
+
"textarea",
|
|
415
|
+
{
|
|
416
|
+
ref: inputRef,
|
|
417
|
+
value: input,
|
|
418
|
+
onChange: (e) => setInput(e.target.value),
|
|
419
|
+
onKeyDown: handleKeyDown,
|
|
420
|
+
rows: 1,
|
|
421
|
+
className: "chatgsd-sr-only",
|
|
422
|
+
disabled: conversationEnded,
|
|
423
|
+
"aria-label": "Chat input"
|
|
424
|
+
}
|
|
425
|
+
)
|
|
426
|
+
] })
|
|
427
|
+
] }),
|
|
428
|
+
/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", { className: "chatgsd-input-hint", children: "press enter to send \xB7 shift+enter for new line" })
|
|
429
|
+
] }) })
|
|
430
|
+
] });
|
|
431
|
+
}
|
|
432
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
433
|
+
0 && (module.exports = {
|
|
434
|
+
ChatGSD
|
|
435
|
+
});
|
|
436
|
+
//# sourceMappingURL=index.cjs.map
|