Skip to content

Commit

Permalink
Update existing model
Browse files Browse the repository at this point in the history
  • Loading branch information
harishmohanraj committed Apr 22, 2024
1 parent 88ba5c7 commit bfa0c82
Show file tree
Hide file tree
Showing 5 changed files with 66 additions and 13 deletions.
5 changes: 5 additions & 0 deletions app/main.wasp
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,11 @@ action updateUserModels {
entities: []
}

action addUserModels {
fn: import { addUserModels } from "@src/server/actions.js",
entities: []
}

action validateForm {
fn: import { validateForm } from "@src/server/actions.js",
entities: []
Expand Down
7 changes: 5 additions & 2 deletions app/src/client/app/ModelsPage.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react';

import { getModels, useQuery, updateUserModels } from 'wasp/client/operations';
import { getModels, useQuery, updateUserModels, addUserModels } from 'wasp/client/operations';

import { useModels, ModelsActionType } from '../hooks/useModels';
import CustomLayout from './layout/CustomLayout';
Expand All @@ -26,7 +26,10 @@ const ModelsPage = () => {
};

const onSuccessCallback = async (data: any) => {
await updateUserModels({ data });
state.updateExistingModel
? await updateUserModels({ data, uuid: state.updateExistingModel.uuid })
: await addUserModels({ data });

refetchModels();
dispatch({ type: ModelsActionType.TOGGLE_ADD_MODEL, payload: false });
};
Expand Down
11 changes: 4 additions & 7 deletions app/src/client/components/ModelForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,10 @@ const ModelForm: React.FC<ModelFormProps> = ({
<div>
{modelSchemas && (
<>
<ModelFormContainer
selectedModel={
updateExistingModel ? (updateExistingModel.api_type === 'openai' ? 'openai' : 'azureoai') : null
}
modelSchemas={modelSchemas}
onModelChange={onModelChange}
/>
{updateExistingModel && <h2 className='text-lg font-semibold text-airt-primary'>Update model</h2>}
{!updateExistingModel && (
<ModelFormContainer selectedModel={null} modelSchemas={modelSchemas} onModelChange={onModelChange} />
)}
{initialModelSchema && (
<DynamicFormBuilder
jsonSchema={initialModelSchema}
Expand Down
14 changes: 12 additions & 2 deletions app/src/client/hooks/useForm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,18 @@ export const useForm = ({ jsonSchema, defaultValues }: UseFormProps) => {
useEffect(() => {
const initialFormData: FormData = {};
Object.keys(jsonSchema.properties).forEach((key) => {
initialFormData[key] =
defaultValues && defaultValues.hasOwnProperty(key) ? getValueFromModel(defaultValues, key as keyof Model) : '';
const property = jsonSchema.properties[key];
if (defaultValues) {
initialFormData[key] = defaultValues.hasOwnProperty(key)
? getValueFromModel(defaultValues, key as keyof Model)
: '';
} else {
if (property.enum && property.enum.length === 1) {
initialFormData[key] = property.enum[0]; // Auto-set single enum value
} else {
initialFormData[key] = property.default ?? ''; // Use default or empty string if no default
}
}
});
setFormData(initialFormData);
setFormErrors({}); // Reset errors on schema change
Expand Down
42 changes: 40 additions & 2 deletions app/src/server/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
type GetAvailableModels,
type ValidateForm,
type UpdateUserModels,
type AddUserModels,
} from 'wasp/server/operations';
import Stripe from 'stripe';
import type { StripePaymentResult } from '../shared/types';
Expand Down Expand Up @@ -116,16 +117,53 @@ export const getAvailableModels: GetAvailableModels<void, any> = async (user, co
}
};

type AddModelsValues = {
userId: number;
model: string;
base_url: string;
api_type: string;
api_version?: string;
};

type AddUserModelsPayload = {
data: AddModelsValues;
};

export const addUserModels: AddUserModels<AddUserModelsPayload, void> = async (args, context) => {
if (!context.user) {
throw new HttpError(401);
}

try {
const response = await fetch(`${FASTAGENCY_SERVER_URL}/models/add`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: context.user.id, ...args.data }),
});
const json: any = (await response.json()) as { detail?: string }; // Parse JSON once

if (!response.ok) {
const errorMsg = json.detail || `HTTP error with status code ${response.status}`;
console.error('Server Error:', errorMsg);
throw new Error(errorMsg);
}
} catch (error: any) {
throw new HttpError(500, error.message);
}
};

type UpdateUserModelsValues = {
userId: number;
model: string;
base_url: string;
api_type: string;
api_version?: string;
uuid: string;
};

type UpdateUserModelsPayload = {
data: UpdateUserModelsValues;
uuid: string;
};

export const updateUserModels: UpdateUserModels<UpdateUserModelsPayload, void> = async (args, context) => {
Expand All @@ -135,9 +173,9 @@ export const updateUserModels: UpdateUserModels<UpdateUserModelsPayload, void> =

try {
const response = await fetch(`${FASTAGENCY_SERVER_URL}/models/update`, {
method: 'POST',
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId: context.user.id, ...args.data }),
body: JSON.stringify({ userId: context.user.id, ...args.data, uuid: args.uuid }),
});
const json: any = (await response.json()) as { detail?: string }; // Parse JSON once

Expand Down

0 comments on commit bfa0c82

Please sign in to comment.