@@ -18,7 +18,12 @@ function AiRequest(db: PrismaClient['aiRequest']) {
1818 } ) ;
1919 return requests ;
2020 } ,
21- async createModel ( actor : DbUser , aiTemplateId : string , input : string ) : Promise < DbAiRequest > {
21+ async createModel (
22+ actor : DbUser ,
23+ aiTemplateId : string ,
24+ input : string ,
25+ onResponse ?: ( aiRequest : DbAiRequest ) => void
26+ ) : Promise < DbAiRequest > {
2227 const template = await prisma . aiTemplate . findUniqueOrThrow ( {
2328 where : { id : aiTemplateId }
2429 } ) ;
@@ -65,36 +70,61 @@ function AiRequest(db: PrismaClient['aiRequest']) {
6570 ]
6671 } ) ;
6772
68- const response = await client . responses . create ( {
69- model : template . model ,
70- input : requestInput ,
71- text : {
72- format : template . jsonSchema
73- ? {
74- type : 'json_schema' ,
75- name : 'tdev_ai_response' ,
76- schema : { } ,
77- ...( template . jsonSchema ! as unknown as Partial < OpenAI . ResponseFormatJSONSchema > )
78- }
79- : ( { type : 'text' } as OpenAI . ResponseFormatText )
80- } ,
81- reasoning : { } ,
82- tools : [ ] ,
83- temperature : template . temperature ,
84- max_output_tokens : template . maxTokens ,
85- top_p : template . topP ,
86- store : false
87- } ) ;
88-
8973 const aiRequest = await db . create ( {
9074 data : {
9175 userId : actor . id ,
9276 aiTemplateId : aiTemplateId ,
9377 request : input ,
94- response : JSON . parse ( response . output_text ) ,
95- status : 'success'
78+ status : 'pending' ,
79+ response : { }
9680 }
9781 } ) ;
82+
83+ client . responses
84+ . create ( {
85+ model : template . model ,
86+ input : requestInput ,
87+ text : {
88+ format : template . jsonSchema
89+ ? {
90+ type : 'json_schema' ,
91+ name : template . 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+ } )
104+ . then ( ( response ) => {
105+ db . update ( {
106+ where : { id : aiRequest . id } ,
107+ data : {
108+ status : response . error ? 'error' : 'completed' ,
109+ response : response . error ? response . error : JSON . parse ( response . output_text )
110+ }
111+ } ) . then ( ( updatedRequest ) => {
112+ onResponse ?.( updatedRequest ) ;
113+ } ) ;
114+ } )
115+ . catch ( ( error ) => {
116+ db . update ( {
117+ where : { id : aiRequest . id } ,
118+ data : {
119+ status : 'error' ,
120+ response : {
121+ error : error . message || 'Unknown error occurred'
122+ }
123+ }
124+ } ) . then ( ( updatedRequest ) => {
125+ onResponse ?.( updatedRequest ) ;
126+ } ) ;
127+ } ) ;
98128 return aiRequest ;
99129 }
100130 } ) ;
0 commit comments