( request: FastifyRequestTypebox<typeof GenerateResponseSchema>, reply: FastifyReplyTypebox<typeof GenerateResponseSchema>, )
| 42 | * @returns {Promise<void>} - A promise that resolves when the response is generated |
| 43 | */ |
| 44 | export const generateResponse = async ( |
| 45 | request: FastifyRequestTypebox<typeof GenerateResponseSchema>, |
| 46 | reply: FastifyReplyTypebox<typeof GenerateResponseSchema>, |
| 47 | ) => { |
| 48 | try { |
| 49 | const { data, stream, timeout = DEFAULT_TIMEOUT_IN_MS, maxRetries = DEFAULT_MAX_RETRIES } = request.body; |
| 50 | data.sort((a, b) => a.order - b.order); |
| 51 | const orm = request.server.orm; |
| 52 | for (const params of data) { |
| 53 | let provider; |
| 54 | let model; |
| 55 | if (params.providerId) { |
| 56 | provider = await orm.getRepository(Provider).findOne({ where: { id: params.providerId } }); |
| 57 | } else if (params.providerName) { |
| 58 | provider = await orm.getRepository(Provider).findOne({ where: { name: params.providerName } }); |
| 59 | } else { |
| 60 | throw new ApiError(400, `Neither provider ID nor name was provided`); |
| 61 | } |
| 62 | if (!!!provider) { |
| 63 | throw new ApiError( |
| 64 | 400, |
| 65 | `Provider with ${ |
| 66 | params.providerId ? `id ${params.providerId}` : `name ${params.providerName}` |
| 67 | } does not exist`, |
| 68 | ); |
| 69 | } |
| 70 | |
| 71 | if (params.modelId) { |
| 72 | model = await orm.getRepository(Model).findOne({ where: { id: params.modelId }, relations: ["cost"] }); |
| 73 | } else if (params.modelName) { |
| 74 | model = await orm.getRepository(Model).findOne({ where: { name: params.modelName }, relations: ["cost"] }); |
| 75 | } else { |
| 76 | throw new ApiError(400, `Neither model ID nor name was provided`); |
| 77 | } |
| 78 | if (!!!model) { |
| 79 | throw new ApiError( |
| 80 | 400, |
| 81 | `Model with ${params.modelId ? `id ${params.modelId}` : `name ${params.modelName}`} does not exist`, |
| 82 | ); |
| 83 | } |
| 84 | |
| 85 | const obj = await orm |
| 86 | .getRepository(ModelHealthCheck) |
| 87 | .findOne({ where: { modelId: model.id, providerId: provider.id }, order: { lastChecked: "DESC" } }); |
| 88 | |
| 89 | if (!obj || obj.isAvailable === false || obj.latency > MODEL_LATENCY_LIMIT_FOR_GENERATION) { |
| 90 | continue; |
| 91 | } |
| 92 | |
| 93 | if (stream) { |
| 94 | const response = streamHandler({ |
| 95 | modelName: model.name, |
| 96 | providerName: provider.name, |
| 97 | promptParams: params?.promptParams, |
| 98 | timeout, |
| 99 | maxRetries, |
| 100 | }); |
| 101 | reply.sse( |
nothing calls this directly
no test coverage detected