Skip to content

Commit 09e65d5

Browse files
committed
fix: separate user and admin cache, and allow taskproc without userId
Signed-off-by: Anupam Kumar <kyteinsky@gmail.com>
1 parent cb8560b commit 09e65d5

File tree

1 file changed

+19
-9
lines changed

1 file changed

+19
-9
lines changed

lib/Service/OpenAiAPIService.php

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,11 @@ private function isModelListValid($models): bool {
9595
}
9696

9797
/**
98-
* @param string $userId
98+
* @param ?string $userId
9999
* @return array|string[]
100100
* @throws Exception
101101
*/
102-
public function getModels(string $userId): array {
102+
public function getModels(?string $userId): array {
103103
// caching against 'getModelEnumValues' calls from all the providers
104104
if ($this->areCredsValid === false) {
105105
$this->logger->info('Cannot get OpenAI models without an API key');
@@ -118,11 +118,24 @@ public function getModels(string $userId): array {
118118
return $this->modelsMemoryCache;
119119
}
120120

121-
$cacheKey = Application::MODELS_CACHE_KEY;
121+
$userCacheKey = Application::MODELS_CACHE_KEY . '_' . ($userId ?? '');
122+
$adminCacheKey = Application::MODELS_CACHE_KEY . '-main';
122123
$cache = $this->cacheFactory->createDistributed(Application::APP_ID);
123-
if ($cachedModels = $cache->get($cacheKey)) {
124+
125+
// try to get models from the user cache first
126+
if ($userId !== null) {
127+
$userCachedModels = $cache->get($userCacheKey);
128+
if ($userCachedModels) {
129+
$this->logger->debug('Getting OpenAI models from user cache for user ' . $userId);
130+
return $userCachedModels;
131+
}
132+
}
133+
134+
// if no user cache or userId is null, try to get from the admin cache
135+
$adminCachedModels = $cache->get($adminCacheKey);
136+
if ($adminCachedModels) {
124137
$this->logger->debug('Getting OpenAI models from distributed cache');
125-
return $cachedModels;
138+
return $adminCachedModels;
126139
}
127140

128141
try {
@@ -149,7 +162,7 @@ public function getModels(string $userId): array {
149162
throw new Exception($this->l10n->t('Invalid models response received'), Http::STATUS_INTERNAL_SERVER_ERROR);
150163
}
151164

152-
$cache->set($cacheKey, $modelsResponse, Application::MODELS_CACHE_TTL);
165+
$cache->set($userId !== null ? $userCacheKey : $adminCacheKey, $modelsResponse, Application::MODELS_CACHE_TTL);
153166
$this->modelsMemoryCache = $modelsResponse;
154167
$this->areCredsValid = true;
155168
return $modelsResponse;
@@ -175,9 +188,6 @@ private function hasOwnOpenAiApiKey(string $userId): bool {
175188
* @return array
176189
*/
177190
public function getModelEnumValues(?string $userId): array {
178-
if ($userId === null) {
179-
return [];
180-
}
181191
try {
182192
$modelResponse = $this->getModels($userId);
183193
$modelEnumValues = array_map(function (array $model) {

0 commit comments

Comments
 (0)