can you design me eav schema for prisma, user can define the attribute with promp for schema, it's for second brain memory and when user do llm it will parse it to the selected entity user create, and parse it to zod validation with the attribute description/prompt
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
EAV Schema for Prisma with Dynamic Attribute Definition
Here's a Prisma schema design for your second brain application with EAV (Entity-Attribute-Value) pattern that allows user-defined attributes and LLM parsing:
prisma
// User model
model User {
id String @id @default(uuid())
email String @unique
name String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
entityTypes EntityType[]
entities Entity[]
attributes Attribute[]
values AttributeValue[]
}
// Entity types (categories like Note, Task, Person)
model EntityType {
id String @id @default(uuid())
name String
description String?
prompt String? // LLM prompt for identifying this entity type
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId String
user User @relation(fields: [userId], references: [id])
entities Entity[]
attributes Attribute[]
@@unique([userId, name])
}
// Attribute definitions
model Attribute {
id String @id @default(uuid())
name String
description String?
prompt String? // LLM prompt for extracting this attribute
dataType AttributeDataType
isRequired Boolean @default(false)
defaultValue String?
zodValidation String? // Custom Zod validation as JSON
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId String
user User @relation(fields: [userId], references: [id])
entityTypeId String
entityType EntityType @relation(fields: [entityTypeId], references: [id])
attributeValues AttributeValue[]
@@unique([entityTypeId, name])
}
enum AttributeDataType {
STRING
TEXT
NUMBER
BOOLEAN
DATE
DATETIME
URL
EMAIL
JSON
REFERENCE
}
// Entities (actual instances)
model Entity {
id String @id @default(uuid())
name String
content String? // Original raw content
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId String
user User @relation(fields: [userId], references: [id])
entityTypeId String
entityType EntityType @relation(fields: [entityTypeId], references: [id])
values AttributeValue[]
references AttributeValue[] @relation("EntityReference")
@@unique([userId, entityTypeId, name])
}
// Values for entity attributes
model AttributeValue {
id String @id @default(uuid())
value String // All values stored as strings
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
userId String
user User @relation(fields: [userId], references: [id])
entityId String
entity Entity @relation(fields: [entityId], references: [id])
attributeId String
attribute Attribute @relation(fields: [attributeId], references: [id])
// For REFERENCE type attributes
referenceEntityId String?
referenceEntity Entity? @relation("EntityReference", fields: [referenceEntityId], references: [id])
@@unique([entityId, attributeId])
}
Now here's a TypeScript utility to generate Zod validation schemas from attribute definitions:
typescript
import { z } from "zod";
import { AttributeDataType } from "@prisma/client";
export function generateZodSchema(attributes: Array<{
id: string;
name: string;
description?: string | null;
prompt?: string | null;
dataType: AttributeDataType;
isRequired: boolean;
defaultValue?: string | null;
zodValidation?: string | null;
}>) {
const schemaObject: Record<string, any> = {};
attributes.forEach(attr => {
let fieldSchema;
// Create base schema based on data type
switch (attr.dataType) {
case 'STRING':
case 'TEXT':
fieldSchema = z.string();
break;
case 'NUMBER':
fieldSchema = z.number();
break;
case 'BOOLEAN':
fieldSchema = z.boolean();
break;
case 'DATE':
case 'DATETIME':
fieldSchema = z.date();
break;
case 'URL':
fieldSchema = z.string().url();
break;
case 'EMAIL':
fieldSchema = z.string().email();
break;
case 'JSON':
fieldSchema = z.any();
break;
case 'REFERENCE':
fieldSchema = z.string().uuid();
break;
default:
fieldSchema = z.any();
}
// Apply required/optional
if (!attr.isRequired) {
fieldSchema = fieldSchema.optional();
}
// Apply custom Zod validation if provided
if (attr.zodValidation) {
try {
const customRules = JSON.parse(attr.zodValidation);
if (customRules.min && ['STRING', 'TEXT'].includes(attr.dataType)) {
fieldSchema = fieldSchema.min(customRules.min);
}
if (customRules.max && ['STRING', 'TEXT'].includes(attr.dataType)) {
fieldSchema = fieldSchema.max(customRules.max);
}
// Add other custom validations as needed
} catch (e) {
console.error("Invalid custom validation:", e);
}
}
schemaObject[attr.name] = fieldSchema;
});
return z.object(schemaObject);
}
And finally, a function to parse content with an LLM to extract entity attributes:
typescript
async function parseEntityFromContent(
content: string,
entityType: {
id: string;
name: string;
prompt?: string | null;
attributes: Array<{
id: string;
name: string;
description?: string | null;
prompt?: string | null;
dataType: AttributeDataType;
isRequired: boolean;
}>;
},
llmClient: any // Your LLM client
) {
// Build LLM prompt to extract attributes
const prompt = `
Extract the following attributes from this content for a "${entityType.name}":
${entityType.attributes.map(attr =>
`- ${attr.name}: ${attr.description || ''} ${attr.prompt || ''}`
).join('\n')}
${entityType.prompt || ''}
Content: ${content}
Return only a valid JSON object with attributes as keys.
`;
// Call LLM
const response = await llmClient.complete({
prompt,
responseFormat: "json"
});
// Parse and validate response with Zod
const extractedData = JSON.parse(response);
const zodSchema = generateZodSchema(entityType.attributes);
return zodSchema.parse(extractedData);
}
Would you like me to explain or break down the code?