-
|
Hi, I’m currently working with streaming responses using OpenAI via Prism PHP, and I’d like to ask about tracking token usage (specifically prompt tokens and completion tokens) when using the asStream() method. Here’s a simplified version of the code I’m using: // if agent has tools, add them to the system prompt
$prismTools = [];
if ($this->agent->tools->count() > 0) {
$tools = $this->agent->tools->where('status', Tool::STATUS_ACTIVE);
foreach ($tools as $tool) {
$prismTools[] = new GenericVectorSearchTool(
$tool->code,
$tool->description,
$this->agent
);
}
}
// streaming the response
$stream = Prism::text()
->using(Provider::OpenAI, $this->agent->chat_model)
->withMaxSteps(5) // Increased to allow for multiple tool calls
->withTools($prismTools)
->withMessages($messages)
->asStream();
foreach ($stream as $chunk) {
$onChunk($chunk->text);
}My question is: Any suggestions or best practices for tracking token usage in this case would be really helpful. Thanks in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
I finally found the answer. Since there's no built-in function to get the token count, we need to calculate it manually. Fortunately, I came across a package called I’m not sure about its performance yet, but for now, it solves my problem. Here’s a helper function I created to get the token count: public static function countTokens(string $model, string $text): int
{
// Inisialisasi provider dan encoder sesuai model
$provider = new EncoderProvider();
$encoder = $provider->getForModel($model);
// Hitung token prompt
$totalToken = count($encoder->encode($text));
return $totalToken;
} |
Beta Was this translation helpful? Give feedback.
I finally found the answer. Since there's no built-in function to get the token count, we need to calculate it manually. Fortunately, I came across a package called
yethee/tiktoken-phpthat helps with the token calculation.I’m not sure about its performance yet, but for now, it solves my problem.
Here’s a helper function I created to get the token count: