Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"@langchain/community": "^0.3.53",
"@langchain/core": "^0.3.72",
"ai": "^4.3.19",
"dedent": "^1.7.0",
"react-basic-contenteditable": "^1.0.6",
"react-markdown": "^10.1.0"
},
Expand Down
3 changes: 3 additions & 0 deletions src/plugin/Panel/ChatInput/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ export const ChatInput: FC = () => {
content: input,
},
],
context: {
canvas: state.activeCanvas,
},
};

if (state.selectedMedia.length) {
Expand Down
16 changes: 3 additions & 13 deletions src/plugin/Panel/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,10 @@ export function PluginPanelComponent(props: CloverPlugin & PluginProps) {
useEffect(() => {
if (provider) {
provider.update_dispatch(dispatch);
provider.update_plugin_state(state);
provider.set_system_prompt();
dispatch({ type: "updateProvider", provider });
}

if (!state.systemPrompt) {
dispatch({
type: "setSystemPrompt",
systemPrompt: `You are a helpful assistant that can answer questions about the item in the viewer`,
});
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps

useEffect(() => {
Expand All @@ -51,16 +46,11 @@ export function PluginPanelComponent(props: CloverPlugin & PluginProps) {

useEffect(() => {
if (state.manifest) {
// Update system prompt with manifest metadata
dispatch({
type: "setSystemPrompt",
systemPrompt: `You are a helpful assistant that can answer questions about the item in the viewer. Here is the manifest data for the item:\n\n${JSON.stringify(state.manifest["metadata"], null, 2)}`,
});
const label = state.manifest?.label ?? undefined;
const title = getLabelByUserLanguage(label);
setItemTitle(title.length > 0 ? title[0] : "this item");
}
}, [state.manifest, dispatch]);
}, [state.manifest]);

useEffect(() => {
dispatch({
Expand Down
75 changes: 63 additions & 12 deletions src/plugin/base_provider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import type { PluginContextActions } from "@context";
import type { PluginContextActions, PluginContextStore } from "@context";
import { ManifestNormalized } from "@iiif/presentation-3-normalized";
import type { ConversationState, Message } from "@types";
import { getLabelByUserLanguage } from "@utils";
import dedent from "dedent";
import type { Dispatch } from "react";

type ProviderStatus = "initializing" | "ready" | "error";
Expand All @@ -9,42 +12,74 @@ type ProviderStatus = "initializing" | "ready" | "error";
*
*/
export abstract class BaseProvider {
#dispatch: Dispatch<PluginContextActions> | undefined;
#plugin_dispatch: Dispatch<PluginContextActions> | undefined;
#plugin_state: PluginContextStore | undefined;
#status: ProviderStatus;

constructor() {
this.#status = "ready";
}

private get dispatch(): Dispatch<PluginContextActions> {
if (!this.#dispatch) {
private get plugin_dispatch(): Dispatch<PluginContextActions> {
if (!this.#plugin_dispatch) {
throw new Error("Provider dispatch not initialized.");
}
return this.#dispatch;
return this.#plugin_dispatch;
}

/**
* Sets the dispatch function to allow the provider to update Plugin state
*/
private set dispatch(dispatch: Dispatch<PluginContextActions>) {
this.#dispatch = dispatch;
private set plugin_dispatch(dispatch: Dispatch<PluginContextActions>) {
this.#plugin_dispatch = dispatch;
}

protected get plugin_state(): PluginContextStore {
if (!this.#plugin_state) {
throw new Error("Provider plugin_state not initialized.");
}
return this.#plugin_state;
}

protected set plugin_state(state: PluginContextStore) {
this.#plugin_state = state;
}

/**
* Add messages to the Plugin state
*/
protected add_messages(messages: Message[]) {
this.dispatch({
this.plugin_dispatch({
type: "addMessages",
messages,
});
}

/**
* Generate a system prompt based on the provided manifest
*
* @param manifest the IIIF manifest
* @returns a system prompt string based on the manifest data
*/
protected generate_system_prompt(manifest: ManifestNormalized) {
const title = getLabelByUserLanguage(manifest.label ?? undefined)?.[0] ?? "N/A";
const summary = getLabelByUserLanguage(manifest.summary ?? undefined)?.[0] ?? "N/A";
return dedent`
You are a helpful assistant that can answer questions about the item in the image viewer.

Here is the manifest data for the item:

## Title: ${title}
## Summary: ${summary}
## Raw Metadata: ${JSON.stringify(manifest.metadata)}
`;
}

/**
* Update the Plugin's conversation state.
*/
protected set_conversation_state(state: ConversationState) {
this.dispatch({
this.plugin_dispatch({
type: "setConversationState",
conversationState: state,
});
Expand All @@ -54,7 +89,7 @@ export abstract class BaseProvider {
* Update the last message in the Plugin state.
*/
protected update_last_message(message: Message) {
this.dispatch({
this.plugin_dispatch({
type: "updateLastMessage",
message,
});
Expand All @@ -64,7 +99,7 @@ export abstract class BaseProvider {
* Update the Plugin state with the current provider.
*/
protected update_plugin_provider() {
this.dispatch({
this.plugin_dispatch({
type: "updateProvider",
provider: this,
});
Expand All @@ -83,6 +118,18 @@ export abstract class BaseProvider {
this.#status = value;
}

/**
* Set the system prompt in the Plugin state based on the current manifest.
*/
set_system_prompt() {
const systemPrompt = this.generate_system_prompt(this.plugin_state.manifest);

this.plugin_dispatch({
type: "setSystemPrompt",
systemPrompt,
});
}

/**
* A component that providers can implement to set up their UI.
*/
Expand All @@ -91,6 +138,10 @@ export abstract class BaseProvider {
}

update_dispatch(dispatch: Dispatch<PluginContextActions>) {
this.dispatch = dispatch;
this.plugin_dispatch = dispatch;
}

update_plugin_state(context: PluginContextStore) {
this.plugin_state = context;
}
}
10 changes: 6 additions & 4 deletions src/plugin/context/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// using a barrel file helps tsc-alias resolve the path correctly
import type { PluginContextActions } from "./plugin-context";
import { PluginContextProvider, usePlugin } from "./plugin-context";

export { PluginContextProvider, usePlugin };
export type { PluginContextActions };
export {
PluginContextProvider,
usePlugin,
type PluginContextActions,
type PluginContextStore,
} from "./plugin-context";
66 changes: 61 additions & 5 deletions src/providers/userTokenProvider/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ import { createAnthropic, type AnthropicProvider } from "@ai-sdk/anthropic";
import { createGoogleGenerativeAI, type google } from "@ai-sdk/google";
import { createOpenAI, type OpenAIProvider } from "@ai-sdk/openai";
import { Button, Heading, Input } from "@components";
import { serializeConfigPresentation3, Traverse } from "@iiif/parser";
import type { Canvas } from "@iiif/presentation-3";
import { Tool } from "@langchain/core/tools";
import type { AssistantMessage, Message } from "@types";
import { streamText, tool } from "ai";
import { getLabelByUserLanguage } from "@utils";
import { CoreMessage, streamText, tool } from "ai";
import dedent from "dedent";
import React from "react";
import { BaseProvider } from "../../plugin/base_provider";
import { ModelSelection } from "./components/ModelSelection";
Expand Down Expand Up @@ -44,8 +48,12 @@ export class UserTokenProvider extends BaseProvider {
*
* @param message
* @returns a formatted message
*
* @privateRemarks
*
* Use an arrow function so `this` references the `UserTokenProvider` class
*/
#format_message(message: Message) {
#format_message = (message: Message, index: number, messages: Message[]): CoreMessage => {
Copy link

Copilot AI Sep 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The method signature has changed from a private method to an arrow function property with additional parameters. This is a breaking change that affects the method's binding and parameters. Consider maintaining backward compatibility or documenting this breaking change.

Suggested change
#format_message = (message: Message, index: number, messages: Message[]): CoreMessage => {
// Backward compatibility: provide previous method signature as a private method
#format_message(message: Message): CoreMessage {
// Call the new arrow function with default values for index and messages
return this.#format_message_arrow(message, 0, []);
}
// New implementation with additional parameters
#format_message_arrow = (message: Message, index: number, messages: Message[]): CoreMessage => {

Copilot uses AI. Check for mistakes.
switch (message.role) {
case "user":
return {
Expand All @@ -54,7 +62,56 @@ export class UserTokenProvider extends BaseProvider {
if (c.type === "media") {
return { type: "image", image: c.content.src };
}
return { type: "text", text: c.content };

const prevMessages = messages.slice(0, index);
const lastUserMessage = prevMessages.findLast((m) => m.role === "user");
Comment on lines +66 to +67
Copy link

Copilot AI Sep 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The prevMessages.slice(0, index) operation creates a new array for every message being processed, and findLast searches through all previous messages. This results in O(n²) complexity when processing multiple messages. Consider caching the last user message or restructuring to avoid repeated array operations.

Copilot uses AI. Check for mistakes.
let context = "";

// only add new context to the messages when it changes to save on tokens
if (
!lastUserMessage ||
lastUserMessage.context.canvas.id !== message.context.canvas.id
) {
const canvas = this.plugin_state.vault.serialize<Canvas>(
{
type: "Canvas",
id: message.context.canvas.id,
},
serializeConfigPresentation3,
);
Comment on lines +75 to +81
Copy link

Copilot AI Sep 8, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Canvas serialization is performed for every user message when the Canvas changes. This could be expensive for large Canvas objects. Consider caching the serialized Canvas or extracting annotations separately to avoid full serialization overhead.

Copilot uses AI. Check for mistakes.

const annotationTexts: string[] = [];
const traverse = new Traverse({
annotation: [
(a) => {
if (
a.body &&
typeof a.body === "object" &&
"type" in a.body &&
a.body.type === "TextualBody" &&
a.body.value
) {
annotationTexts.push(a.body.value);
}
},
],
});

traverse.traverseCanvas(canvas);

// prettier-ignore
context = dedent.withOptions({ alignValues: true })`
## Context
The following context is about the latest Canvas in the image viewer.
Use this information if possible to inform your answer.

### Canvas${canvas.label ? `
- Label: ${getLabelByUserLanguage(canvas.label)[0]}` : ""}${annotationTexts.length ? `
- Annotations: ${annotationTexts.join(", ")}` : ""}
`;
}

return { type: "text", text: c.content + `${context ? "\n" + context : ""}` };
}),
};
case "assistant":
Expand All @@ -65,7 +122,7 @@ export class UserTokenProvider extends BaseProvider {
// @ts-expect-error - this is a catch-all for unsupported roles
throw new Error(`Unsupported message role: ${message.role}`);
}
}
};

#is_valid_model_provider_model(provider: Provider, model: string): boolean {
return this.models_by_provider[provider].includes(model);
Expand Down Expand Up @@ -181,7 +238,6 @@ export class UserTokenProvider extends BaseProvider {
model,
tools: this.#transform_tools(),
maxSteps: this.max_steps,
// @ts-expect-error - there is a type mismatch here, but it works
messages: all_messages.map(this.#format_message),
});

Expand Down
5 changes: 5 additions & 0 deletions src/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { CanvasNormalized } from "@iiif/presentation-3-normalized";
export type ConversationState = "idle" | "assistant_responding" | "error";

export type Role = "assistant" | "system" | "user";
Expand Down Expand Up @@ -39,6 +40,10 @@ export type AssistantMessage = {

export interface UserMessage {
content: (TextContent | MediaContent)[];
/** Context that can be added to user messages when generating a response */
context: {
canvas: CanvasNormalized;
};
role: Extract<Role, "user">;
}

Expand Down