Skip to content

Commit f00c9a3

Browse files
committed
refactor ai templates and requests
1 parent df3f04c commit f00c9a3

File tree

5 files changed

+40
-63
lines changed

5 files changed

+40
-63
lines changed

prisma/migrations/20250604174413_remove_name_from_ai_template/migration.sql

Lines changed: 0 additions & 8 deletions
This file was deleted.

prisma/migrations/20250602195519_add_ai_models/migration.sql renamed to prisma/migrations/20250608170858_add_ai_models/migration.sql

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,13 @@
11
-- CreateTable
22
CREATE TABLE "ai_templates" (
33
"id" UUID NOT NULL DEFAULT gen_random_uuid(),
4-
"name" TEXT NOT NULL DEFAULT '',
4+
"author_id" UUID NOT NULL,
55
"rate_limit" INTEGER NOT NULL DEFAULT 0,
66
"rate_limit_period_ms" BIGINT NOT NULL DEFAULT 3600000,
77
"is_active" BOOLEAN NOT NULL DEFAULT true,
8-
"model" TEXT NOT NULL,
98
"api_key" TEXT NOT NULL,
109
"api_url" TEXT NOT NULL,
11-
"temperature" DOUBLE PRECISION NOT NULL DEFAULT 0.5,
12-
"max_tokens" INTEGER NOT NULL DEFAULT 2048,
13-
"top_p" DOUBLE PRECISION NOT NULL DEFAULT 0.8,
14-
"system_message" TEXT,
15-
"json_schema" JSONB,
10+
"config" JSONB NOT NULL,
1611
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
1712
"updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
1813

@@ -34,6 +29,9 @@ CREATE TABLE "ai_requests" (
3429
CONSTRAINT "ai_requests_pkey" PRIMARY KEY ("id")
3530
);
3631

32+
-- AddForeignKey
33+
ALTER TABLE "ai_templates" ADD CONSTRAINT "ai_templates_author_id_fkey" FOREIGN KEY ("author_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
34+
3735
-- AddForeignKey
3836
ALTER TABLE "ai_requests" ADD CONSTRAINT "ai_requests_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
3937

prisma/schema.prisma

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,25 +29,24 @@ model User {
2929
cmsSettings CmsSettings?
3030
studentGroups UserStudentGroup[] @relation("user_student_groups")
3131
aiRequests AiRequest[]
32+
aiTemplates AiTemplate[] @relation("ai_templates")
3233
3334
@@map("users")
3435
}
3536

3637
model AiTemplate {
37-
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
38+
id String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
39+
40+
author User @relation("ai_templates", fields: [authorId], references: [id], onDelete: Cascade)
41+
authorId String @map("author_id") @db.Uuid
3842
rateLimit Int @default(0) @map("rate_limit")
3943
rateLimitPeriodMs BigInt @default(3600000) @map("rate_limit_period_ms") // Default to 1 hour
4044
isActive Boolean @default(true) @map("is_active")
4145
42-
model String @map("model")
4346
apiKey String @map("api_key")
4447
apiUrl String @map("api_url")
4548
46-
temperature Float @default(0.5) @map("temperature")
47-
maxTokens Int @default(2048) @map("max_tokens")
48-
topP Float @default(0.8) @map("top_p")
49-
systemMessage String? @map("system_message")
50-
jsonSchema Json? @map("json_schema")
49+
config Json @map("config") // Configuration for the AI template, e.g., model, parameters
5150
5251
aiRequests AiRequest[]
5352

src/models/AiRequest.ts

Lines changed: 11 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -48,19 +48,16 @@ function AiRequest(db: PrismaClient['aiRequest']) {
4848
baseURL: template.apiUrl
4949
});
5050

51-
const requestInput: OpenAI.Responses.ResponseInput = [];
52-
if (template.systemMessage) {
53-
requestInput.push({
54-
role: 'system',
55-
content: [
56-
{
57-
type: 'input_text',
58-
text: template.systemMessage
59-
}
60-
]
61-
});
62-
}
63-
requestInput.push({
51+
const templateConfig =
52+
template.config as unknown as OpenAI.Responses.ResponseCreateParamsNonStreaming;
53+
const config: OpenAI.Responses.ResponseCreateParamsNonStreaming = {
54+
...templateConfig,
55+
input: Array.isArray(templateConfig.input)
56+
? (templateConfig.input as OpenAI.Responses.ResponseInput)
57+
: [templateConfig.input as unknown as OpenAI.Responses.ResponseInputItem]
58+
};
59+
60+
(config.input as OpenAI.Responses.ResponseInput).push({
6461
role: 'user',
6562
content: [
6663
{
@@ -81,26 +78,7 @@ function AiRequest(db: PrismaClient['aiRequest']) {
8178
});
8279

8380
client.responses
84-
.create({
85-
model: template.model,
86-
input: requestInput,
87-
text: {
88-
format: template.jsonSchema
89-
? {
90-
type: 'json_schema',
91-
name: 'tdev-ai-response',
92-
schema: {},
93-
...(template.jsonSchema as unknown as Partial<OpenAI.ResponseFormatJSONSchema>)
94-
}
95-
: ({ type: 'text' } as OpenAI.ResponseFormatText)
96-
},
97-
reasoning: {},
98-
tools: [],
99-
temperature: template.temperature,
100-
max_output_tokens: template.maxTokens,
101-
top_p: template.topP,
102-
store: false
103-
})
81+
.create(config)
10482
.then((response) => {
10583
db.update({
10684
where: { id: aiRequest.id },

src/models/AiTemplate.ts

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,19 +30,24 @@ function AiTemplate(db: PrismaClient['aiTemplate']) {
3030
throw new HTTP403Error('Not authorized to update AI templates');
3131
}
3232
const record = await this.findModel(actor, id);
33+
if (record.authorId !== actor.id) {
34+
throw new HTTP403Error('Not authorized to update this AI template');
35+
}
36+
const updateData: Prisma.AiTemplateUpdateInput = {
37+
config: data.config as Prisma.InputJsonValue,
38+
apiKey: data.apiKey,
39+
apiUrl: data.apiUrl,
40+
isActive: data.isActive,
41+
rateLimit: data.rateLimit,
42+
rateLimitPeriodMs: data.rateLimitPeriodMs
43+
};
3344
/** remove fields not updatable*/
3445
return db
3546
.update({
3647
where: {
3748
id: record.id
3849
},
39-
data: {
40-
...data,
41-
jsonSchema:
42-
typeof data.jsonSchema === 'object'
43-
? (data.jsonSchema as Prisma.JsonObject)
44-
: undefined
45-
}
50+
data: updateData
4651
})
4752
.then((v) => prepareAiTemplate(v));
4853
},
@@ -59,7 +64,12 @@ function AiTemplate(db: PrismaClient['aiTemplate']) {
5964
}
6065
return db
6166
.create({
62-
data: data
67+
data: {
68+
...data,
69+
author: {
70+
connect: { id: actor.id }
71+
}
72+
}
6373
})
6474
.then((v) => prepareAiTemplate(v));
6575
},

0 commit comments

Comments
 (0)