unconv / php-gpt-funcs

GPT-4 Function Calling Example in PHP
34 stars 20 forks source link

Using php attributes instead of docblocks #2

Closed ohnotnow closed 1 year ago

ohnotnow commented 1 year ago

Not really an 'issue' - but after watching some of the youtube videos (and enjoying them!) I wondered if using the new-fangled 'attributes' would make life easier compared to parsing the docblocks?

Eg (off the top of my head) :

<?php

use Attribute;

#[Attribute]
class AiFunction
{
    public function __construct(public string $description) { }
}

#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_FUNCTION)]
class AiParam
{
    public function __construct(
        public string $name, 
        public string $description, 
        public string $type
    ) { }
}

/* ----- */

#[AiFunction('Get the weather for a specific location')]
#[AiParam('location', 'The location to get the weather for', 'string')]
#[AiParam('units', 'The units to return the weather in', 'enum|metric,imperial')]
function get_weather(string $location, string $units = 'metric')
{
    // do stuff
}

function dumpAttributeData($reflection)
{
    $attributes = $reflection->getAttributes();

    // also get the function name etc etc

    foreach ($attributes as $attribute) {
        var_dump($attribute->getName());
        var_dump($attribute->getArguments());
    }
}

dumpAttributeData(new ReflectionFunction('get_weather'));

$ php test.php
string(13) "AiFunction"
array(1) {
  [0]=>
  string(39) "Get the weather for a specific location"
}
string(7) "AiParam"
array(3) {
  [0]=>
  string(8) "location"
  [1]=>
  string(35) "The location to get the weather for"
  [2]=>
  string(6) "string"
}
string(7) "AiParam"
array(3) {
  [0]=>
  string(5) "units"
  [1]=>
  string(34) "The units to return the weather in"
  [2]=>
  string(20) "enum|metric,imperial"
}```

Anyway - an idle thought.  And thanks again for the videos!
unconv commented 1 year ago

Yes, you could do it this way too, but with docblocks you don't have to learn a new syntax since you should know docblock anyway ;)

I did in fact try to find a way to label the functions with attributes, like #[AiFunction] in order to get a list of available functions automatically but I wasn't able to find a (good) way of listing all functions that have that attribute. I haven't used PHP attributes before.

ohnotnow commented 1 year ago

Ah - no worries. Just a thought while I was watching one of the videos. I've not really used the attributes myself so can't really offer much in the way of help about them.