Skip to content
Draft
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
25 changes: 23 additions & 2 deletions packages/ai-sdk-mobx/ReadMe.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
# AI SDK for MobX

MobX models for AI SDK interactions, built on [mobx-restful][1].
MobX models for [AI SDK][2] interactions, built on [mobx-restful][1].

This package is being prepared; its public model API is not available yet.
Each stateful React hook in `@ai-sdk/react` has a corresponding MobX model:

| AI SDK hook | MobX model |
| -------------------------- | ----------------- |
| `useChat` | `ChatModel` |
| `useCompletion` | `CompletionModel` |
| `useObject` | `ObjectModel` |
| `experimental_useRealtime` | `RealtimeModel` |

```ts
import { ChatModel, CompletionModel } from 'ai-sdk-mobx';

const chat = new ChatModel();
await chat.sendMessage({ text: 'Hello!' });

const completion = new CompletionModel();
await completion.complete('Write a greeting');
```

The models expose their state as MobX observables. `ChatModel.chat` provides the
underlying AI SDK chat instance for the full chat API.

## Install

Expand All @@ -11,3 +31,4 @@ npm install ai-sdk-mobx
```

[1]: https://github.com/idea2app/MobX-RESTful
[2]: https://github.com/vercel/ai/tree/main/packages/react
15 changes: 13 additions & 2 deletions packages/ai-sdk-mobx/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
{
"name": "ai-sdk-mobx",
"version": "0.1.0",
"type": "module",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"license": "AGPL-3.0-only",
"author": "shiy2008@gmail.com",
"description": "MobX models for AI SDK interactions.",
Expand All @@ -15,8 +24,10 @@
"dist/"
],
"dependencies": {
"ai": "^7.0.173",
"mobx": "^7.1.7",
"mobx-restful": "^2.1.5"
"mobx-restful": "^2.1.5",
"zod": "^4.6.7"
},
"devDependencies": {
"@swc-node/register": "^1.12.1",
Expand All @@ -27,6 +38,6 @@
"scripts": {
"check": "cross-env SWCRC=true SWC_CONFIG_FILE=../../.swcrc node --import @swc-node/register/esm-register --test test/*.test.ts",
"test": "tsc --noEmit && npm run check",
"build": "echo Building ai-sdk-mobx"
"build": "tsc --project tsconfig.build.json"
}
}
124 changes: 124 additions & 0 deletions packages/ai-sdk-mobx/source/chat.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { action, observable, runInAction } from 'mobx';
import { BaseModel } from 'mobx-restful';
import { AbstractChat, type ChatInit, type ChatState, type ChatStatus, type UIMessage } from 'ai';

class MobXChat<UI_MESSAGE extends UIMessage> extends AbstractChat<UI_MESSAGE> {}

export class ChatModel<UI_MESSAGE extends UIMessage = UIMessage> extends BaseModel {
@observable accessor status: ChatStatus = 'ready';
@observable accessor error: Error | undefined = undefined;
@observable accessor messages: UI_MESSAGE[] = [];
@observable accessor experimental_queuedMessages: UI_MESSAGE[] = [];

readonly chat: MobXChat<UI_MESSAGE>;

constructor({ messages = [], ...options }: ChatInit<UI_MESSAGE> = {}) {
super();
runInAction(() => {
this.messages = messages;
});
const model = this;
const state: ChatState<UI_MESSAGE> = {
get status() {
return model.status;
},
set status(value) {
runInAction(() => {
model.status = value;
});
},
get error() {
return model.error;
},
set error(value) {
runInAction(() => {
model.error = value;
});
},
get messages() {
return model.messages;
},
set messages(value) {
runInAction(() => {
model.messages = value;
});
},
get experimental_queuedMessages() {
return model.experimental_queuedMessages;
},
set experimental_queuedMessages(value) {
runInAction(() => {
model.experimental_queuedMessages = value;
});
},
pushMessage: this.pushMessage,
popMessage: this.popMessage,
replaceMessage: this.replaceMessage,
snapshot: this.snapshot,
};
this.chat = new MobXChat({ ...options, state });
}

@action
pushMessage = (message: UI_MESSAGE) => {
this.messages = [...this.messages, message];
};

@action
popMessage = () => {
this.messages = this.messages.slice(0, -1);
};

@action
replaceMessage = (index: number, message: UI_MESSAGE) => {
this.messages = this.messages.map((current, position) =>
position === index ? this.snapshot(message) : current,
);
};

snapshot = <T>(value: T): T => {
if (
value == null ||
typeof value !== 'object' ||
!('parts' in value) ||
!Array.isArray(value.parts)
)
return value;

return {
...value,
parts: value.parts.map(part =>
part != null && typeof part === 'object' ? { ...part } : part,
),
...('metadata' in value && value.metadata != null && typeof value.metadata === 'object'
? { metadata: Array.isArray(value.metadata) ? [...value.metadata] : { ...value.metadata } }
: {}),
} as T;
};

get id() {
return this.chat.id;
}

sendMessage: MobXChat<UI_MESSAGE>['sendMessage'] = (...args) => this.chat.sendMessage(...args);
regenerate: MobXChat<UI_MESSAGE>['regenerate'] = (...args) => this.chat.regenerate(...args);
stop = () => this.chat.stop();
resumeStream = (...args: Parameters<MobXChat<UI_MESSAGE>['resumeStream']>) =>
this.chat.resumeStream(...args);
addToolOutput: MobXChat<UI_MESSAGE>['addToolOutput'] = (...args) =>
this.chat.addToolOutput(...args);
addToolApprovalResponse: MobXChat<UI_MESSAGE>['addToolApprovalResponse'] = (...args) =>
this.chat.addToolApprovalResponse(...args);
clearError = () => this.chat.clearError();
dispose = () => this.chat.dispose();

@action
override clear() {
void this.chat.stop();
this.messages = [];
this.experimental_queuedMessages = [];
this.status = 'ready';
this.error = undefined;
super.clear();
}
}
113 changes: 113 additions & 0 deletions packages/ai-sdk-mobx/source/completion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { action, observable, runInAction } from 'mobx';
import { BaseModel } from 'mobx-restful';
import { callCompletionApi, type CompletionRequestOptions, type UseCompletionOptions } from 'ai';

export class CompletionModel<BODY extends object = object> extends BaseModel {
@observable accessor completion = '';
@observable accessor error: Error | undefined = undefined;
@observable accessor input = '';

private abortController: AbortController | null = null;
private requestId = 0;
private readonly options: UseCompletionOptions<BODY>;

constructor(options: UseCompletionOptions<BODY> = {}) {
super();
this.options = options;
runInAction(() => {
this.completion = options.initialCompletion ?? '';
this.input = options.initialInput ?? '';
});
}

async complete(prompt: string, requestOptions?: CompletionRequestOptions<BODY>) {
const requestId = ++this.requestId;
const { api = '/api/completion', ...options } = this.options;

return callCompletionApi({
api,
prompt,
credentials: options.credentials,
headers: this.mergeHeaders(options.headers, requestOptions?.headers),
body: { ...options.body, ...requestOptions?.body },
streamProtocol: options.streamProtocol,
fetch: options.fetch,
setCompletion: completion => {
if (requestId === this.requestId) this.setCompletion(completion);
},
setLoading: loading => {
if (requestId === this.requestId)
runInAction(() => {
this.downloading = Number(loading);
});
},
setError: error => {
if (requestId === this.requestId)
runInAction(() => {
this.error = error;
});
},
setAbortController: controller => {
if (requestId === this.requestId) this.abortController = controller;
},
getAbortController: () => this.abortController,
onFinish: options.onFinish,
onError: options.onError,
});
}

@action
setCompletion = (completion: string) => {
this.completion = completion;
};

@action
setInput = (input: string) => {
this.input = input;
};

handleInputChange = (event: { target: { value: string } }) => {
this.setInput(event.target.value);
};

async handleSubmit(event?: { preventDefault?: () => void }) {
event?.preventDefault?.();
if (!this.input) return;

const input = this.input;
this.setInput('');
return this.complete(input);
}

stop = () => {
this.abortController?.abort();
};

@action
override clear() {
this.stop();
this.requestId++;
this.abortController = null;
this.completion = '';
this.error = undefined;
super.clear();
}

get isLoading() {
return this.downloading > 0;
}

private mergeHeaders(...sources: Array<Record<string, string> | Headers | undefined>) {
const headers = new Headers();

for (const source of sources) {
if (source instanceof Headers) {
source.forEach((value, key) => headers.set(key, value));
} else {
for (const [key, value] of Object.entries(source ?? {})) headers.set(key, value);
}
}

return headers;
}
}
4 changes: 4 additions & 0 deletions packages/ai-sdk-mobx/source/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from './chat.js';
export * from './completion.js';
export * from './object.js';
export * from './realtime.js';
Loading