@tensorpass/aiconnect-react 0.1.9 → 0.1.10

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.
@@ -0,0 +1 @@
1
+ export declare function appendAnswer(answer: string, delta: string, newStep: boolean): string;
@@ -0,0 +1,13 @@
1
+ // The answer of a turn as the visitor reads it: the text the model writes before a tool call and the text
2
+ // it writes after the result are two paragraphs, where streaming them end to end ran a sentence into the
3
+ // next one ("how it works.You start").
4
+ const ENDS_IN_SPACE = /\s$/;
5
+ // Adds a streamed piece to the answer. The first piece of a step that follows a tool call opens a new
6
+ // paragraph, unless the answer is still empty or already ends in white space.
7
+ export function appendAnswer(answer, delta, newStep) {
8
+ if (!newStep || !answer || ENDS_IN_SPACE.test(answer)) {
9
+ return answer + delta;
10
+ }
11
+ return `${answer}\n\n${delta}`;
12
+ }
13
+ //# sourceMappingURL=answerSteps.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"answerSteps.js","sourceRoot":"","sources":["../src/answerSteps.ts"],"names":[],"mappings":"AAAA,0GAA0G;AAC1G,yGAAyG;AACzG,uCAAuC;AAEvC,MAAM,aAAa,GAAG,KAAK,CAAC;AAE5B,sGAAsG;AACtG,8EAA8E;AAC9E,MAAM,UAAU,YAAY,CAAC,MAAc,EAAE,KAAa,EAAE,OAAgB;IAC1E,IAAI,CAAC,OAAO,IAAI,CAAC,MAAM,IAAI,aAAa,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QACtD,OAAO,MAAM,GAAG,KAAK,CAAC;IACxB,CAAC;IACD,OAAO,GAAG,MAAM,OAAO,KAAK,EAAE,CAAC;AACjC,CAAC","sourcesContent":["// The answer of a turn as the visitor reads it: the text the model writes before a tool call and the text\n// it writes after the result are two paragraphs, where streaming them end to end ran a sentence into the\n// next one (\"how it works.You start\").\n\nconst ENDS_IN_SPACE = /\\s$/;\n\n// Adds a streamed piece to the answer. The first piece of a step that follows a tool call opens a new\n// paragraph, unless the answer is still empty or already ends in white space.\nexport function appendAnswer(answer: string, delta: string, newStep: boolean): string {\n if (!newStep || !answer || ENDS_IN_SPACE.test(answer)) {\n return answer + delta;\n }\n return `${answer}\\n\\n${delta}`;\n}\n"]}
package/dist/useAiChat.js CHANGED
@@ -10,26 +10,35 @@ import { createChatGuard, GuardStop, runConversation } from '@tensorpass/aiconne
10
10
  import { partsForModel, UNKNOWN_READS } from '@tensorpass/aiconnect/attachments';
11
11
  import { useAiConnect } from "./AiConnectProvider.js";
12
12
  import { failedAnswerText } from "./messages.js";
13
+ import { appendAnswer } from "./answerSteps.js";
13
14
  import { withinRequestBudget } from "./transcriptBudget.js";
14
15
  // Before the first question there is no answer, so no link to draw.
15
16
  const NO_LINKS = () => false;
16
17
  function updateLast(turns, change) {
17
18
  return [...turns.slice(0, -1), change(turns.at(-1))];
18
19
  }
19
- // Writes the conversation's progress into the last turn, as the answer streams and the tools run.
20
- // A conversation that was stopped writes nothing more, so a question sent right after it keeps its
21
- // own turn.
20
+ // Writes the conversation's progress into the last turn, as the answer streams and the tools run. The
21
+ // words the model writes after a tool's result start a paragraph of their own. A conversation that was
22
+ // stopped writes nothing more, so a question sent right after it keeps its own turn.
22
23
  function lastTurnHooks(setTurns, signal, guard) {
23
24
  const updateTurn = (change) => {
24
25
  if (!signal.aborted) {
25
26
  setTurns((current) => updateLast(current, change));
26
27
  }
27
28
  };
29
+ let newStep = false;
28
30
  return {
29
- onText: (delta) => updateTurn((turn) => ({ ...turn, answer: turn.answer + delta })),
30
- onToolCall: (call) => updateTurn((turn) => ({
31
- ...turn, tools: [...turn.tools, { call, result: null, visible: guard.toolVisible(call.name) }],
32
- })),
31
+ onText: (delta) => {
32
+ const opensStep = newStep;
33
+ newStep = false;
34
+ updateTurn((turn) => ({ ...turn, answer: appendAnswer(turn.answer, delta, opensStep) }));
35
+ },
36
+ onToolCall: (call) => {
37
+ newStep = true;
38
+ updateTurn((turn) => ({
39
+ ...turn, tools: [...turn.tools, { call, result: null, visible: guard.toolVisible(call.name) }],
40
+ }));
41
+ },
33
42
  onToolResult: (call, result) => updateTurn((turn) => ({
34
43
  ...turn, tools: turn.tools.map((activity) => (activity.call.id === call.id ? { ...activity, result } : activity)),
35
44
  })),
@@ -1 +1 @@
1
- {"version":3,"file":"useAiChat.js","sourceRoot":"","sources":["../src/useAiChat.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,gGAAgG;AAChG,mGAAmG;AACnG,gGAAgG;AAChG,6FAA6F;AAC7F,yGAAyG;AACzG,sFAAsF;AAEtF,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEtD,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAKpF,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAEjF,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAyB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAqC5D,oEAAoE;AACpE,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC;AAE7B,SAAS,UAAU,CAAC,KAAiB,EAAE,MAAoC;IACzE,OAAO,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,kGAAkG;AAClG,mGAAmG;AACnG,YAAY;AACZ,SAAS,aAAa,CACpB,QAA8C,EAAE,MAAmB,EAAE,KAAgB;IAErF,MAAM,UAAU,GAAG,CAAC,MAAoC,EAAE,EAAE;QAC1D,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACpB,QAAQ,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC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MAAM,cAAc,GAAG,WAAW,CAAC,GAAG,EAAE;QACtC,QAAQ,CAAC,CAAC,OAAO,EAAE,EAAE;YACnB,MAAM,IAAI,GAAG,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5B,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC;QAC1F,CAAC,CAAC,CAAC;QACH,UAAU,CAAC,IAAI,CAAC,CAAC;IACnB,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,OAAO;QACL,KAAK,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,cAAc,EAAE,IAAI,EAAE,KAAK,EAAE,OAAO,EAAE,IAAI,IAAI,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,IAAI,IAAI;QAC5G,SAAS,EAAE,KAAK,CAAC,MAAM,KAAK,WAAW;QACvC,KAAK,EAAE,CAAC,KAAK,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,aAAa;QAChF,SAAS,EAAE,CAAC,KAAK,CAAC,MAAM,KAAK,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,IAAI;QAC/E,WAAW,EAAE,KAAK,EAAE,WAAW,IAAI,QAAQ;KAC5C,CAAC;AACJ,CAAC","sourcesContent":["// A conversation with the visitor's own model, using the site's tools. The site renders `turns`:\n// what the visitor asked, the answer as it streams, and every tool call with its raw result, so\n// tool results can be shown as the site's own cards. `stop` ends the answer in the wallet too, and\n// the turn keeps the text streamed so far. Every conversation runs under its guards, tuned with\n// `guards`: a question or an answer they stop shows the site's safe answer in its place, and\n// `linkAllowed` tells the interface which links of an answer it may draw. A question may carry the files\n// the visitor attached, which reach the model as the account that answers reads them.\n\nimport { useCallback, useRef, useState } from 'react';\nimport type { Dispatch, RefObject, SetStateAction } from 'react';\nimport { createChatGuard, GuardStop, runConversation } from '@tensorpass/aiconnect';\nimport type {\n ChatGuard, ChatMessage, ConnectionState, ContentPart, ConversationHooks, GuardPolicy, ProviderSession, ToolCall,\n ToolSource,\n} from '@tensorpass/aiconnect';\nimport { partsForModel, UNKNOWN_READS } from '@tensorpass/aiconnect/attachments';\nimport type { PreparedAttachment } from '@tensorpass/aiconnect/attachments';\nimport { useAiConnect } from './AiConnectProvider.tsx';\nimport { failedAnswerText } from './messages.ts';\nimport type { ModuleMessages } from './messages.ts';\nimport { withinRequestBudget } from './transcriptBudget.ts';\n\nexport interface ToolActivity {\n call: ToolCall;\n result: string | null;\n // False for a tool the site keeps out of the `visibleTools` of its guards, whose activity the\n // interface does not show.\n visible?: boolean;\n}\n\n// A question as the visitor sends it: the text they typed or dictated and the files they attached.\nexport interface AskedQuestion {\n text: string;\n attachments: PreparedAttachment[];\n}\n\nexport interface ChatTurn {\n question: string;\n // The files the visitor attached to the question.\n attachments?: PreparedAttachment[];\n // The attached images and pages the answering model does not read, such as images for a text only model.\n unread?: number;\n answer: string;\n tools: ToolActivity[];\n // The guard stopped the question before it left the page, or the answer as it came; `answer` then\n // holds the site's safe answer.\n blocked?: 'question' | 'answer';\n}\n\nexport interface UseAiChatOptions {\n system: string;\n tools?: ToolSource;\n // The site's own values for the guards every conversation runs under, read at the conversation's first\n // question.\n guards?: GuardPolicy;\n}\n\n// Before the first question there is no answer, so no link to draw.\nconst NO_LINKS = () => false;\n\nfunction updateLast(turns: ChatTurn[], change: (turn: ChatTurn) => ChatTurn): ChatTurn[] {\n return [...turns.slice(0, -1), change(turns.at(-1)!)];\n}\n\n// Writes the conversation's progress into the last turn, as the answer streams and the tools run.\n// A conversation that was stopped writes nothing more, so a question sent right after it keeps its\n// own turn.\nfunction lastTurnHooks(\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>, signal: AbortSignal, guard: ChatGuard,\n): ConversationHooks {\n const updateTurn = (change: (turn: ChatTurn) => ChatTurn) => {\n if (!signal.aborted) {\n setTurns((current) => updateLast(current, change));\n }\n };\n return {\n onText: (delta) => updateTurn((turn) => ({ ...turn, answer: turn.answer + delta })),\n onToolCall: (call) => updateTurn((turn) => ({\n ...turn, tools: [...turn.tools, { call, result: null, visible: guard.toolVisible(call.name) }],\n })),\n onToolResult: (call, result) => updateTurn((turn) => ({\n ...turn, tools: turn.tools.map((activity) => (activity.call.id === call.id ? { ...activity, result } : activity)),\n })),\n };\n}\n\ninterface QuestionRun {\n session: ProviderSession;\n tools?: ToolSource;\n guard: ChatGuard;\n transcript: RefObject<ChatMessage[]>;\n asked: ChatMessage;\n controller: AbortController;\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>;\n}\n\n// Runs one question on the visitor's model and keeps the exchange in the transcript. A question that\n// was stopped or failed adds nothing to it.\nasync function answerQuestion({ session, tools, guard, transcript, asked, controller, setTurns }: QuestionRun) {\n const added = await runConversation({\n session,\n tools,\n guard,\n messages: withinRequestBudget([...transcript.current, asked]),\n signal: controller.signal,\n ...lastTurnHooks(setTurns, controller.signal, guard),\n });\n transcript.current = [...transcript.current, asked, ...added];\n}\n\n// Shows the safe answer in place of what a guard stopped: the site's own, or the module's words for a\n// stopped question or answer. A stopped answer stays in the transcript as the safe answer, so the model\n// reads the exchange without the text it should not have written; a stopped question never reaches it.\nfunction showStop(stop: GuardStop, run: QuestionRun, copy: ModuleMessages) {\n const safeAnswer = run.guard.policy.safeAnswer ?? (stop.stage === 'question' ? copy.guardQuestion : copy.guardAnswer);\n run.setTurns((current) => updateLast(current, (turn) => ({ ...turn, answer: safeAnswer, blocked: stop.stage })));\n if (stop.stage === 'answer') {\n run.transcript.current = [...run.transcript.current, run.asked, { role: 'assistant', content: safeAnswer }];\n }\n}\n\n// An answer that failed: its words, and the code the provider gave its refusal, such as `plan_inactive`\n// for a TensorPass account without a plan, by which the module offers what fits.\nexport interface AnswerFailure {\n text: string;\n code: string | null;\n}\n\n// A web account's 429 keeps the provider's own message, such as the gateway's limit of requests from one\n// site, since the module's words for a 429 send the visitor to another account in the wallet.\nfunction answerFailure(reason: unknown, connection: Extract<ConnectionState, { status: 'connected' }>,\n copy: ModuleMessages): AnswerFailure {\n const { status, code } = (reason ?? {}) as { status?: unknown; code?: unknown };\n const text = connection.account && status === 429 && reason instanceof Error\n ? reason.message\n : failedAnswerText(reason, connection.providerName, copy);\n return { text, code: typeof code === 'string' ? code : null };\n}\n\n// What a question's run needs from the hook besides the question.\ninterface SendContext {\n connection: Extract<ConnectionState, { status: 'connected' }>;\n guard: ChatGuard;\n tools?: ToolSource;\n transcript: RefObject<ChatMessage[]>;\n abort: RefObject<AbortController | null>;\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>;\n setFailure: Dispatch<SetStateAction<AnswerFailure | null>>;\n setBusy: Dispatch<SetStateAction<boolean>>;\n copy: ModuleMessages;\n}\n\n// The visitor's message: the text, then the attachments as the account that answers reads them.\nasync function askedMessage(question: AskedQuestion, context: SendContext): Promise<ChatMessage> {\n if (question.attachments.length === 0) {\n return { role: 'user', content: question.text };\n }\n const { parts, unread } = await partsForModel(question.attachments, context.connection.reads ?? UNKNOWN_READS);\n if (unread) {\n context.setTurns((current) => updateLast(current, (turn) => ({ ...turn, unread })));\n }\n const text: ContentPart[] = question.text ? [{ type: 'text', text: question.text }] : [];\n return { role: 'user', content: [...text, ...parts] };\n}\n\n// Sends one question and writes its outcome: the answer, the guard's safe answer, or the failure.\nasync function sendQuestion(question: AskedQuestion, context: SendContext): Promise<void> {\n const { connection, guard, tools, transcript, abort, setTurns, setFailure, setBusy, copy } = context;\n const controller = new AbortController();\n abort.current = controller;\n setBusy(true);\n setFailure(null);\n setTurns((current) => [...current, {\n question: question.text, attachments: question.attachments, answer: '', tools: [],\n }]);\n const run: QuestionRun = { session: connection.session, tools, guard, transcript, controller, setTurns,\n asked: { role: 'user', content: question.text } };\n try {\n run.asked = await askedMessage(question, context);\n await answerQuestion(run);\n } catch (reason) {\n if (reason instanceof GuardStop) {\n showStop(reason, run, copy);\n } else if (!controller.signal.aborted) {\n // An answer the site stopped itself ends without an error.\n setFailure(answerFailure(reason, connection, copy));\n }\n } finally {\n // A question sent after a stop has taken over; its own end clears `busy`.\n if (abort.current === controller) {\n setBusy(false);\n }\n }\n}\n\nexport function useAiChat({ system, tools, guards }: UseAiChatOptions) {\n const { client, state, moduleMessages } = useAiConnect();\n const transcript = useRef<ChatMessage[]>([{ role: 'system', content: system }]);\n const abort = useRef<AbortController | null>(null);\n // The conversation's guard: created at its first question and kept until `reset`, in a ref for the\n // questions and in the state for the links the interface draws.\n const activeGuard = useRef<ChatGuard | null>(null);\n const [guard, setGuard] = useState<ChatGuard | null>(null);\n const [turns, setTurns] = useState<ChatTurn[]>([]);\n const [busy, setBusy] = useState(false);\n const [failure, setFailure] = useState<AnswerFailure | null>(null);\n\n // The session is read from the client when the question is sent, so a question kept while the\n // wallet connected the site goes out as soon as the client is connected.\n const send = useCallback(async (question: string | AskedQuestion) => {\n const connection = client.state;\n const asked = typeof question === 'string' ? { text: question, attachments: [] } : question;\n const text = asked.text.trim();\n if (connection.status !== 'connected' || (!text && asked.attachments.length === 0)) {\n return;\n }\n activeGuard.current ??= createChatGuard(guards);\n setGuard(activeGuard.current);\n await sendQuestion({ ...asked, text }, { connection, guard: activeGuard.current, tools, transcript, abort,\n setTurns, setFailure, setBusy, copy: moduleMessages });\n }, [client, tools, guards, moduleMessages]);\n\n const stop = useCallback(() => abort.current?.abort(), []);\n\n const reset = useCallback(() => {\n abort.current?.abort();\n transcript.current = [{ role: 'system', content: system }];\n activeGuard.current = null;\n setGuard(null);\n setTurns([]);\n setFailure(null);\n }, [system]);\n\n // Takes back the last turn when it failed with nothing to show, so asking it again does not repeat it.\n const dropFailedTurn = useCallback(() => {\n setTurns((current) => {\n const last = current.at(-1);\n return last && !last.answer && last.tools.length === 0 ? current.slice(0, -1) : current;\n });\n setFailure(null);\n }, []);\n\n return {\n turns, send, stop, reset, dropFailedTurn, busy, error: failure?.text ?? null, refusal: failure?.code ?? null,\n connected: state.status === 'connected',\n reads: (state.status === 'connected' ? state.reads : undefined) ?? UNKNOWN_READS,\n dictation: (state.status === 'connected' ? state.dictation : undefined) ?? null,\n linkAllowed: guard?.linkAllowed ?? NO_LINKS,\n };\n}\n"]}
1
+ {"version":3,"file":"useAiChat.js","sourceRoot":"","sources":["../src/useAiChat.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,gGAAgG;AAChG,mGAAmG;AACnG,gGAAgG;AAChG,6FAA6F;AAC7F,yGAAyG;AACzG,sFAAsF;AAEtF,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAEtD,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAKpF,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,mCAAmC,CAAC;AAEjF,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAyB,CAAC;AACvD,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAEjD,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAC;AAChD,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAqC5D,oEAAoE;AACpE,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC;AAE7B,SAAS,UAAU,CAAC,KAAiB,EAAE,MAAoC;IACzE,OAAO,CAAC,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAE,CAAC,CAAC,CAAC;AACxD,CAAC;AAED,sGAAsG;AACtG,uGAAuG;AACvG,qFAAqF;AACrF,SAAS,aAAa,CACp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AAM,KAAK,WAAW,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,IAAI,IAAI;QAC/E,WAAW,EAAE,KAAK,EAAE,WAAW,IAAI,QAAQ;KAC5C,CAAC;AACJ,CAAC","sourcesContent":["// A conversation with the visitor's own model, using the site's tools. The site renders `turns`:\n// what the visitor asked, the answer as it streams, and every tool call with its raw result, so\n// tool results can be shown as the site's own cards. `stop` ends the answer in the wallet too, and\n// the turn keeps the text streamed so far. Every conversation runs under its guards, tuned with\n// `guards`: a question or an answer they stop shows the site's safe answer in its place, and\n// `linkAllowed` tells the interface which links of an answer it may draw. A question may carry the files\n// the visitor attached, which reach the model as the account that answers reads them.\n\nimport { useCallback, useRef, useState } from 'react';\nimport type { Dispatch, RefObject, SetStateAction } from 'react';\nimport { createChatGuard, GuardStop, runConversation } from '@tensorpass/aiconnect';\nimport type {\n ChatGuard, ChatMessage, ConnectionState, ContentPart, ConversationHooks, GuardPolicy, ProviderSession, ToolCall,\n ToolSource,\n} from '@tensorpass/aiconnect';\nimport { partsForModel, UNKNOWN_READS } from '@tensorpass/aiconnect/attachments';\nimport type { PreparedAttachment } from '@tensorpass/aiconnect/attachments';\nimport { useAiConnect } from './AiConnectProvider.tsx';\nimport { failedAnswerText } from './messages.ts';\nimport type { ModuleMessages } from './messages.ts';\nimport { appendAnswer } from './answerSteps.ts';\nimport { withinRequestBudget } from './transcriptBudget.ts';\n\nexport interface ToolActivity {\n call: ToolCall;\n result: string | null;\n // False for a tool the site keeps out of the `visibleTools` of its guards, whose activity the\n // interface does not show.\n visible?: boolean;\n}\n\n// A question as the visitor sends it: the text they typed or dictated and the files they attached.\nexport interface AskedQuestion {\n text: string;\n attachments: PreparedAttachment[];\n}\n\nexport interface ChatTurn {\n question: string;\n // The files the visitor attached to the question.\n attachments?: PreparedAttachment[];\n // The attached images and pages the answering model does not read, such as images for a text only model.\n unread?: number;\n answer: string;\n tools: ToolActivity[];\n // The guard stopped the question before it left the page, or the answer as it came; `answer` then\n // holds the site's safe answer.\n blocked?: 'question' | 'answer';\n}\n\nexport interface UseAiChatOptions {\n system: string;\n tools?: ToolSource;\n // The site's own values for the guards every conversation runs under, read at the conversation's first\n // question.\n guards?: GuardPolicy;\n}\n\n// Before the first question there is no answer, so no link to draw.\nconst NO_LINKS = () => false;\n\nfunction updateLast(turns: ChatTurn[], change: (turn: ChatTurn) => ChatTurn): ChatTurn[] {\n return [...turns.slice(0, -1), change(turns.at(-1)!)];\n}\n\n// Writes the conversation's progress into the last turn, as the answer streams and the tools run. The\n// words the model writes after a tool's result start a paragraph of their own. A conversation that was\n// stopped writes nothing more, so a question sent right after it keeps its own turn.\nfunction lastTurnHooks(\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>, signal: AbortSignal, guard: ChatGuard,\n): ConversationHooks {\n const updateTurn = (change: (turn: ChatTurn) => ChatTurn) => {\n if (!signal.aborted) {\n setTurns((current) => updateLast(current, change));\n }\n };\n let newStep = false;\n return {\n onText: (delta) => {\n const opensStep = newStep;\n newStep = false;\n updateTurn((turn) => ({ ...turn, answer: appendAnswer(turn.answer, delta, opensStep) }));\n },\n onToolCall: (call) => {\n newStep = true;\n updateTurn((turn) => ({\n ...turn, tools: [...turn.tools, { call, result: null, visible: guard.toolVisible(call.name) }],\n }));\n },\n onToolResult: (call, result) => updateTurn((turn) => ({\n ...turn, tools: turn.tools.map((activity) => (activity.call.id === call.id ? { ...activity, result } : activity)),\n })),\n };\n}\n\ninterface QuestionRun {\n session: ProviderSession;\n tools?: ToolSource;\n guard: ChatGuard;\n transcript: RefObject<ChatMessage[]>;\n asked: ChatMessage;\n controller: AbortController;\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>;\n}\n\n// Runs one question on the visitor's model and keeps the exchange in the transcript. A question that\n// was stopped or failed adds nothing to it.\nasync function answerQuestion({ session, tools, guard, transcript, asked, controller, setTurns }: QuestionRun) {\n const added = await runConversation({\n session,\n tools,\n guard,\n messages: withinRequestBudget([...transcript.current, asked]),\n signal: controller.signal,\n ...lastTurnHooks(setTurns, controller.signal, guard),\n });\n transcript.current = [...transcript.current, asked, ...added];\n}\n\n// Shows the safe answer in place of what a guard stopped: the site's own, or the module's words for a\n// stopped question or answer. A stopped answer stays in the transcript as the safe answer, so the model\n// reads the exchange without the text it should not have written; a stopped question never reaches it.\nfunction showStop(stop: GuardStop, run: QuestionRun, copy: ModuleMessages) {\n const safeAnswer = run.guard.policy.safeAnswer ?? (stop.stage === 'question' ? copy.guardQuestion : copy.guardAnswer);\n run.setTurns((current) => updateLast(current, (turn) => ({ ...turn, answer: safeAnswer, blocked: stop.stage })));\n if (stop.stage === 'answer') {\n run.transcript.current = [...run.transcript.current, run.asked, { role: 'assistant', content: safeAnswer }];\n }\n}\n\n// An answer that failed: its words, and the code the provider gave its refusal, such as `plan_inactive`\n// for a TensorPass account without a plan, by which the module offers what fits.\nexport interface AnswerFailure {\n text: string;\n code: string | null;\n}\n\n// A web account's 429 keeps the provider's own message, such as the gateway's limit of requests from one\n// site, since the module's words for a 429 send the visitor to another account in the wallet.\nfunction answerFailure(reason: unknown, connection: Extract<ConnectionState, { status: 'connected' }>,\n copy: ModuleMessages): AnswerFailure {\n const { status, code } = (reason ?? {}) as { status?: unknown; code?: unknown };\n const text = connection.account && status === 429 && reason instanceof Error\n ? reason.message\n : failedAnswerText(reason, connection.providerName, copy);\n return { text, code: typeof code === 'string' ? code : null };\n}\n\n// What a question's run needs from the hook besides the question.\ninterface SendContext {\n connection: Extract<ConnectionState, { status: 'connected' }>;\n guard: ChatGuard;\n tools?: ToolSource;\n transcript: RefObject<ChatMessage[]>;\n abort: RefObject<AbortController | null>;\n setTurns: Dispatch<SetStateAction<ChatTurn[]>>;\n setFailure: Dispatch<SetStateAction<AnswerFailure | null>>;\n setBusy: Dispatch<SetStateAction<boolean>>;\n copy: ModuleMessages;\n}\n\n// The visitor's message: the text, then the attachments as the account that answers reads them.\nasync function askedMessage(question: AskedQuestion, context: SendContext): Promise<ChatMessage> {\n if (question.attachments.length === 0) {\n return { role: 'user', content: question.text };\n }\n const { parts, unread } = await partsForModel(question.attachments, context.connection.reads ?? UNKNOWN_READS);\n if (unread) {\n context.setTurns((current) => updateLast(current, (turn) => ({ ...turn, unread })));\n }\n const text: ContentPart[] = question.text ? [{ type: 'text', text: question.text }] : [];\n return { role: 'user', content: [...text, ...parts] };\n}\n\n// Sends one question and writes its outcome: the answer, the guard's safe answer, or the failure.\nasync function sendQuestion(question: AskedQuestion, context: SendContext): Promise<void> {\n const { connection, guard, tools, transcript, abort, setTurns, setFailure, setBusy, copy } = context;\n const controller = new AbortController();\n abort.current = controller;\n setBusy(true);\n setFailure(null);\n setTurns((current) => [...current, {\n question: question.text, attachments: question.attachments, answer: '', tools: [],\n }]);\n const run: QuestionRun = { session: connection.session, tools, guard, transcript, controller, setTurns,\n asked: { role: 'user', content: question.text } };\n try {\n run.asked = await askedMessage(question, context);\n await answerQuestion(run);\n } catch (reason) {\n if (reason instanceof GuardStop) {\n showStop(reason, run, copy);\n } else if (!controller.signal.aborted) {\n // An answer the site stopped itself ends without an error.\n setFailure(answerFailure(reason, connection, copy));\n }\n } finally {\n // A question sent after a stop has taken over; its own end clears `busy`.\n if (abort.current === controller) {\n setBusy(false);\n }\n }\n}\n\nexport function useAiChat({ system, tools, guards }: UseAiChatOptions) {\n const { client, state, moduleMessages } = useAiConnect();\n const transcript = useRef<ChatMessage[]>([{ role: 'system', content: system }]);\n const abort = useRef<AbortController | null>(null);\n // The conversation's guard: created at its first question and kept until `reset`, in a ref for the\n // questions and in the state for the links the interface draws.\n const activeGuard = useRef<ChatGuard | null>(null);\n const [guard, setGuard] = useState<ChatGuard | null>(null);\n const [turns, setTurns] = useState<ChatTurn[]>([]);\n const [busy, setBusy] = useState(false);\n const [failure, setFailure] = useState<AnswerFailure | null>(null);\n\n // The session is read from the client when the question is sent, so a question kept while the\n // wallet connected the site goes out as soon as the client is connected.\n const send = useCallback(async (question: string | AskedQuestion) => {\n const connection = client.state;\n const asked = typeof question === 'string' ? { text: question, attachments: [] } : question;\n const text = asked.text.trim();\n if (connection.status !== 'connected' || (!text && asked.attachments.length === 0)) {\n return;\n }\n activeGuard.current ??= createChatGuard(guards);\n setGuard(activeGuard.current);\n await sendQuestion({ ...asked, text }, { connection, guard: activeGuard.current, tools, transcript, abort,\n setTurns, setFailure, setBusy, copy: moduleMessages });\n }, [client, tools, guards, moduleMessages]);\n\n const stop = useCallback(() => abort.current?.abort(), []);\n\n const reset = useCallback(() => {\n abort.current?.abort();\n transcript.current = [{ role: 'system', content: system }];\n activeGuard.current = null;\n setGuard(null);\n setTurns([]);\n setFailure(null);\n }, [system]);\n\n // Takes back the last turn when it failed with nothing to show, so asking it again does not repeat it.\n const dropFailedTurn = useCallback(() => {\n setTurns((current) => {\n const last = current.at(-1);\n return last && !last.answer && last.tools.length === 0 ? current.slice(0, -1) : current;\n });\n setFailure(null);\n }, []);\n\n return {\n turns, send, stop, reset, dropFailedTurn, busy, error: failure?.text ?? null, refusal: failure?.code ?? null,\n connected: state.status === 'connected',\n reads: (state.status === 'connected' ? state.reads : undefined) ?? UNKNOWN_READS,\n dictation: (state.status === 'connected' ? state.dictation : undefined) ?? null,\n linkAllowed: guard?.linkAllowed ?? NO_LINKS,\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tensorpass/aiconnect-react",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "description": "React provider picker and chat hook for AI Connect.",
5
5
  "type": "module",
6
6
  "sideEffects": [
@@ -34,8 +34,8 @@
34
34
  "build": "rm -rf dist tsconfig.tsbuildinfo && tsc -b && esbuild src/styles.css --bundle --outfile=dist/styles.css --log-level=warning && cp src/modules/styles/launchers.css dist/launchers.css"
35
35
  },
36
36
  "dependencies": {
37
- "@tensorpass/aiconnect": "0.1.9",
38
- "@tensorpass/aiconnect-design": "0.1.9"
37
+ "@tensorpass/aiconnect": "0.1.10",
38
+ "@tensorpass/aiconnect-design": "0.1.10"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "react": ">=19"