-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTokenLimitService.php
More file actions
88 lines (77 loc) · 2.3 KB
/
Copy pathTokenLimitService.php
File metadata and controls
88 lines (77 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
namespace Cloudstudio\TokenUsage\Services;
use Illuminate\Support\Facades\Config;
class TokenLimitService
{
/**
* Check if the model has tokens available for the given period.
*
* @param mixed $model
* @param string $period
* @return bool
*/
public function hasTokensAvailable($model, string $period): bool
{
$modelName = $this->getModelName($model);
$plan = $this->getUserPlan();
$config = $this->getModelConfig($modelName, $plan);
if (!$config) {
return true; // No specific limit defined for this model under the plan
}
return $this->checkTokenLimit($model, $config, $period);
}
/**
* Get the model name from the model instance.
*
* @param mixed $model
* @return string|null
*/
protected function getModelName($model): ?string
{
return array_search(get_class($model), Config::get('token-usage.model_mappings', []));
}
/**
* Get the plan of the authenticated user or the default plan.
*
* @return string
*/
protected function getUserPlan(): string
{
return auth()->user()->plan ?? Config::get('token-usage.default_plan', 'basic');
}
/**
* Get the configuration for a model under a specific plan.
*
* @param string|null $modelName
* @param string $plan
* @return array|null
*/
protected function getModelConfig(?string $modelName, string $plan): ?array
{
return Config::get("token-usage.plans.$plan.model_limits.$modelName");
}
/**
* Check if the tokens used are within the limit for a specific period.
*
* @param mixed $model
* @param array $config
* @param string $period
* @return bool
*/
protected function checkTokenLimit($model, array $config, string $period): bool
{
$limit = $config[$period] ?? 0;
$tokensUsed = $model->{'get' . ucfirst($period) . 'Tokens'}()->sum('tokens_used');
return $tokensUsed < $limit;
}
/**
* Convert model name to its corresponding class.
*
* @param string $modelName
* @return string|null
*/
public function getModelClass(string $modelName): ?string
{
return Config::get('token-usage.model_mappings')[$modelName] ?? null;
}
}