Skip to content

Commit

Permalink
Add model schema validation logic
Browse files Browse the repository at this point in the history
  • Loading branch information
harishmohanraj committed Apr 17, 2024
1 parent 6a56653 commit 432d677
Show file tree
Hide file tree
Showing 6 changed files with 61 additions and 5 deletions.
5 changes: 5 additions & 0 deletions app/main.wasp
Original file line number Diff line number Diff line change
Expand Up @@ -270,6 +270,11 @@ action getModels {
entities: []
}

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

// 📚 Queries

query getDailyStats {
Expand Down
10 changes: 9 additions & 1 deletion app/src/client/app/ModelsPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import NotificationBox from '../components/NotificationBox';
const ModelsPage = () => {
const [modelsSchema, setModelsSchema] = useState<ModelSchema | null>(null);
const [initialModelSchema, setInitialModelSchema] = useState<JsonSchema | null>(null);
const [selectedModel, setSelectedModel] = useState<string>('');
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);

Expand All @@ -21,6 +22,7 @@ const ModelsPage = () => {
const response = await getModels();
setModelsSchema(response);
setInitialModelSchema(response.schemas[0].json_schema);
setSelectedModel(response.schemas[0].name);
} catch (error: any) {
setError('Something went wrong. Please try again later.');
console.log(error);
Expand All @@ -36,6 +38,7 @@ const ModelsPage = () => {
const foundSchema = modelsSchema?.schemas.find((schema) => schema.name === newModel);
if (foundSchema) {
setInitialModelSchema(foundSchema.json_schema);
setSelectedModel(foundSchema.name);
}
};

Expand All @@ -53,7 +56,12 @@ const ModelsPage = () => {
{modelsSchema && (
<>
<ModelFormContainer modelsSchema={modelsSchema} onModelChange={handleModelChange} />
{initialModelSchema && <DynamicFormBuilder jsonSchema={initialModelSchema} />}
{initialModelSchema && (
<DynamicFormBuilder
jsonSchema={initialModelSchema}
validationURL={`models/llms/${selectedModel}/validate`}
/>
)}
</>
)}
{error && <NotificationBox type={'error'} onClick={() => setError(null)} message={error} />}
Expand Down
9 changes: 6 additions & 3 deletions app/src/client/components/DynamicFormBuilder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,21 @@ import { useForm } from '../hooks/useForm';
import { JsonSchema } from '../interfaces/models';
import { TextInput } from './form/TextInput';
import { SelectInput } from './form/SelectInput';
import { validateForm } from '../services/commonService';

interface DynamicFormBuilderProps {
jsonSchema: JsonSchema;
validationURL: string;
}

const DynamicFormBuilder: React.FC<DynamicFormBuilderProps> = ({ jsonSchema }) => {
const DynamicFormBuilder: React.FC<DynamicFormBuilderProps> = ({ jsonSchema, validationURL }) => {
const { formData, handleChange } = useForm(jsonSchema);

const handleSubmit = (event: React.FormEvent) => {
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
console.log('Submitted Data:', formData);
// Add submission logic here
const response = await validateForm(formData, validationURL);
console.log('Validation Response:', response);
};

return (
Expand Down
11 changes: 11 additions & 0 deletions app/src/client/services/commonService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { validateForm as apiValidateForm } from 'wasp/client/operations';

export const validateForm = async (data: any, validationURL: string) => {
try {
const response = await apiValidateForm({ data, validationURL });
return response;
} catch (error) {
console.error('Failed to fetch models:', error);
throw error;
}
};
2 changes: 1 addition & 1 deletion app/src/client/tests/DynamicFormBuilder.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const jsonSchema: JsonSchema = {

describe('DynamicFormBuilder', () => {
test('renders form fields correctly', () => {
render(<DynamicFormBuilder jsonSchema={jsonSchema} />);
render(<DynamicFormBuilder jsonSchema={jsonSchema} validationURL='https://some-domain/some-route' />);

expect(screen.getByLabelText('Model')).toBeInTheDocument();
expect(screen.getByLabelText('API Key')).toBeInTheDocument();
Expand Down
29 changes: 29 additions & 0 deletions app/src/server/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type UpdateCurrentUser,
type UpdateUserById,
type GetModels,
type ValidateForm,
} from 'wasp/server/operations';
import Stripe from 'stripe';
import type { StripePaymentResult } from '../shared/types';
Expand Down Expand Up @@ -113,3 +114,31 @@ export const getModels: GetModels<void, any> = async (user, context) => {
throw new HttpError(500, error.message);
}
};

export const validateForm: ValidateForm<{ data: any; validationURL: string }, any> = async (
{ data, validationURL }: { data: any; validationURL: string },
context: any
) => {
if (!context.user) {
throw new HttpError(401);
}

try {
const response = await fetch(`${FASTAGENCY_SERVER_URL}/${validationURL}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(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);
}

return json;
} catch (error: any) {
throw new HttpError(500, error.message);
}
};

0 comments on commit 432d677

Please sign in to comment.