-
Notifications
You must be signed in to change notification settings - Fork 24
feat: Add Raw Response Metadata Handling - GPT Token Usage Example #270
New issue
Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? # to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
<?php | ||
|
||
use PhpLlm\LlmChain\Bridge\OpenAI\GPT; | ||
use PhpLlm\LlmChain\Bridge\OpenAI\PlatformFactory; | ||
use PhpLlm\LlmChain\Bridge\OpenAI\TokenOutputProcessor; | ||
use PhpLlm\LlmChain\Chain; | ||
use PhpLlm\LlmChain\Model\Message\Message; | ||
use PhpLlm\LlmChain\Model\Message\MessageBag; | ||
use Symfony\Component\Dotenv\Dotenv; | ||
|
||
require_once dirname(__DIR__).'/vendor/autoload.php'; | ||
(new Dotenv())->loadEnv(dirname(__DIR__).'/.env'); | ||
|
||
if (empty($_ENV['OPENAI_API_KEY'])) { | ||
echo 'Please set the OPENAI_API_KEY environment variable.'.PHP_EOL; | ||
exit(1); | ||
} | ||
|
||
$platform = PlatformFactory::create($_ENV['OPENAI_API_KEY']); | ||
$llm = new GPT(GPT::GPT_4O_MINI, [ | ||
'temperature' => 0.5, // default options for the model | ||
]); | ||
|
||
$chain = new Chain($platform, $llm, outputProcessors: [new TokenOutputProcessor()]); | ||
$messages = new MessageBag( | ||
Message::forSystem('You are a pirate and you write funny.'), | ||
Message::ofUser('What is the Symfony framework?'), | ||
); | ||
$response = $chain->call($messages, [ | ||
'max_tokens' => 500, // specific options just for this call | ||
]); | ||
|
||
$metadata = $response->getMetadata(); | ||
|
||
echo 'Utilized Tokens: '.$metadata['total_tokens'].PHP_EOL; | ||
echo '-- Prompt Tokens: '.$metadata['prompt_tokens'].PHP_EOL; | ||
echo '-- Completion Tokens: '.$metadata['completion_tokens'].PHP_EOL; | ||
echo 'Remaining Tokens: '.$metadata['remaining_tokens'].PHP_EOL; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace PhpLlm\LlmChain\Bridge\OpenAI; | ||
|
||
use PhpLlm\LlmChain\Chain\Output; | ||
use PhpLlm\LlmChain\Chain\OutputProcessor; | ||
use PhpLlm\LlmChain\Model\Response\StreamResponse; | ||
|
||
final class TokenOutputProcessor implements OutputProcessor | ||
{ | ||
public function processOutput(Output $output): void | ||
{ | ||
if ($output->response instanceof StreamResponse) { | ||
// Streams have to be handled manually as the tokens are part of the streamed chunks | ||
return; | ||
} | ||
|
||
$rawResponse = $output->response->getRawResponse(); | ||
if (null === $rawResponse) { | ||
return; | ||
} | ||
|
||
$metadata = $output->response->getMetadata(); | ||
|
||
$metadata->add( | ||
'remaining_tokens', | ||
(int) $rawResponse->getHeaders(false)['x-ratelimit-remaining-tokens'][0], | ||
); | ||
|
||
$content = $rawResponse->toArray(false); | ||
|
||
if (!\array_key_exists('usage', $content)) { | ||
return; | ||
} | ||
|
||
$metadata->add('prompt_tokens', $content['usage']['prompt_tokens'] ?? null); | ||
$metadata->add('completion_tokens', $content['usage']['completion_tokens'] ?? null); | ||
$metadata->add('total_tokens', $content['usage']['total_tokens'] ?? null); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace PhpLlm\LlmChain\Model\Response; | ||
|
||
use PhpLlm\LlmChain\Model\Response\Metadata\MetadataAwareTrait; | ||
|
||
abstract class BaseResponse implements ResponseInterface | ||
{ | ||
use MetadataAwareTrait; | ||
use RawResponseAwareTrait; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace PhpLlm\LlmChain\Model\Response\Exception; | ||
|
||
final class RawResponseAlreadySet extends \RuntimeException | ||
{ | ||
public function __construct() | ||
{ | ||
parent::__construct('The raw response was already set.'); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace PhpLlm\LlmChain\Model\Response\Metadata; | ||
|
||
/** | ||
* @implements \IteratorAggregate<string, mixed> | ||
* @implements \ArrayAccess<string, mixed> | ||
*/ | ||
class Metadata implements \JsonSerializable, \Countable, \IteratorAggregate, \ArrayAccess | ||
{ | ||
/** | ||
* @var array<string, mixed> | ||
*/ | ||
private array $metadata = []; | ||
|
||
/** | ||
* @param array<string, mixed> $metadata | ||
*/ | ||
public function __construct(array $metadata = []) | ||
{ | ||
$this->set($metadata); | ||
} | ||
|
||
/** | ||
* @return array<string, mixed> | ||
*/ | ||
public function all(): array | ||
{ | ||
return $this->metadata; | ||
} | ||
|
||
/** | ||
* @param array<string, mixed> $metadata | ||
*/ | ||
public function set(array $metadata): void | ||
{ | ||
$this->metadata = $metadata; | ||
} | ||
|
||
public function add(string $key, mixed $value): void | ||
{ | ||
$this->metadata[$key] = $value; | ||
} | ||
|
||
public function has(string $key): bool | ||
{ | ||
return \array_key_exists($key, $this->metadata); | ||
} | ||
|
||
public function get(string $key, mixed $default = null): mixed | ||
{ | ||
return $this->metadata[$key] ?? $default; | ||
} | ||
|
||
public function remove(string $key): void | ||
{ | ||
unset($this->metadata[$key]); | ||
} | ||
|
||
/** | ||
* @return array<string, mixed> | ||
*/ | ||
public function jsonSerialize(): array | ||
{ | ||
return $this->all(); | ||
} | ||
|
||
public function count(): int | ||
{ | ||
return \count($this->metadata); | ||
} | ||
|
||
public function getIterator(): \Traversable | ||
{ | ||
return new \ArrayIterator($this->metadata); | ||
} | ||
|
||
public function offsetExists(mixed $offset): bool | ||
{ | ||
return $this->has((string) $offset); | ||
} | ||
|
||
public function offsetGet(mixed $offset): mixed | ||
{ | ||
return $this->get((string) $offset); | ||
} | ||
|
||
public function offsetSet(mixed $offset, mixed $value): void | ||
{ | ||
$this->add((string) $offset, $value); | ||
} | ||
|
||
public function offsetUnset(mixed $offset): void | ||
{ | ||
$this->remove((string) $offset); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace PhpLlm\LlmChain\Model\Response\Metadata; | ||
|
||
trait MetadataAwareTrait | ||
{ | ||
private ?Metadata $metadata = null; | ||
|
||
public function getMetadata(): Metadata | ||
{ | ||
return $this->metadata ??= new Metadata(); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
<?php | ||
|
||
declare(strict_types=1); | ||
|
||
namespace PhpLlm\LlmChain\Model\Response; | ||
|
||
use PhpLlm\LlmChain\Model\Response\Exception\RawResponseAlreadySet; | ||
use Symfony\Contracts\HttpClient\ResponseInterface as SymfonyHttpResponse; | ||
|
||
trait RawResponseAwareTrait | ||
{ | ||
protected ?SymfonyHttpResponse $rawResponse = null; | ||
|
||
public function setRawResponse(SymfonyHttpResponse $rawResponse): void | ||
{ | ||
if (null !== $this->rawResponse) { | ||
throw new RawResponseAlreadySet(); | ||
} | ||
|
||
$this->rawResponse = $rawResponse; | ||
} | ||
|
||
public function getRawResponse(): ?SymfonyHttpResponse | ||
{ | ||
return $this->rawResponse; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.