Upgrade to Pro — share decks privately, control downloads, hide ads and more …

PHPで生成AIのAPIをやってみた - PHPカンファレンス関西2024

Arimoto
February 11, 2024

PHPで生成AIのAPIをやってみた - PHPカンファレンス関西2024

Arimoto

February 11, 2024
Tweet

Other Decks in Programming

Transcript

  1. DPNQPTFSKTPO { "name": "ochanoko/ocnk", "description": "Ochanoko-net sysytem", "config": { "vendor-dir":

    "src/vendors", }, "require":{ "openai-php/client":"^0.8.1", "vlucas/phpdotenv":"^5.6.0" } }
  2. <?php require_once 'src/vendors/autoload.php'; $dotenv = Dotenv\Dotenv::createImmutable(__DIR__); $dotenv->load(); $yourApiKey = $_ENV['API_KEY'];

    $client = OpenAI::client($yourApiKey); $message[] = [ "role" => "system", "content" => "ωοτγϣοϓͷ঎඼આ໌จΛ࡞Ε·͢" ]; $message[] = [ "role" => "assistant", "content" => "మಓ໛ܕ ৽ܕ΍͘΋ 273ܥ Nήʔδ 10,000ԁ" ]; $message[] = [ "role" => "user", "content" => "঎඼આ໌จΛৄ͘͠1000จࣈఔ౓Ͱ࡞੒͍ͯͩ͘͠͞" ]; $response = $client->chat()->create([ 'model' => 'gpt-3.5-turbo', 'messages' => $message ]); foreach ($response->choices as $result) { echo $result->message->content; } echo "\n" . (0.000001 * $response->usage->promptTokens + 0.000002 * $response->usage->completionTokens);
  3. $message[] = [ "role" => "system", "content" => "ωοτγϣοϓͷ঎඼આ໌จΛ࡞Ε·͢" ];

    $message[] = [ "role" => "assistant", "content" => "మಓ໛ܕ ৽ܕ΍͘΋ 273ܥ Nήʔδ 10,000ԁ" ]; $message[] = [ "role" => "user", "content" => "঎඼આ໌จΛৄ͘͠1000จࣈఔ౓Ͱ࡞੒͍ͯͩ͘͠͞" ]; $response = $client->chat()->create([ 'model' => 'gpt-3.5-turbo', 'messages' => $message ]); "*Ξγελϯτͷਓ֨Λઃఆ ੜ੒͢ΔͨΊͷ৘ใ ࣭໰಺༰
  4. foreach ($response->choices as $result) { echo $result->message->content; } echo "\n"

    . (0.000001 * $response->usage->promptTokens + 0.000002 * $response->usage- >completionTokens); ͝޷ධ͍͍͍ͨͩͯΔమಓ໛ܕγϦʔζʹɺ৽ͨͳϥΠϯφοϓ͕ొ৔͠·ͨ͠ʂͦͷ໊΋ʮ৽ܕ΍͘΋ɹܥ/ήʔδʯͰ͢ɻ͜ͷૉ੖Β͍͠మಓ໛ܕΛ௨ͯ͡ɺΑΓϦ ΞϧͳమಓମݧΛָ͠Ή͜ͱ͕Ͱ͖·͢ɻ ৽ܕ΍͘΋ܥ͸ɺ೔ຊͷಛٸྻंͱͯ͠׆༂͢ΔϞσϧΛ஧࣮ʹ࠶ݱͨ͠΋ͷͰ͢ɻຊ঎඼͸/ήʔδʢʣͷαΠζͰɺखʹऔΓ΍͍͢ίϯύΫτͳαΠζײͱͳͬ ͍ͯ·͢ɻͦΕʹ΋ؔΘΒͣɺ߽՚ͳσΟςʔϧͱਫ਼޼ͳ଄ΓͰɺຊ෺ͷྻंΛࢥΘͤΔϦΞϦςΟΛ࣮ݱ͍ͯ͠·͢ɻ ͜ͷమಓ໛ܕͷಛ௃ͷͻͱͭ͸ɺૉࡐͷબఆʹ͋Γ·͢ɻߴ඼࣭ͳϓϥενοΫΛ࢖༻͓ͯ͠Γɺ଱ٱੑʹ༏Ε͍ͯ·͢ɻ·ͨɺ৭߹͍΍ృ૷΋ඇৗʹਫ਼៛ʹߦΘΕ͓ͯΓɺ ຊ෺ͷ৭ͱ΄΅มΘΒͳ͍࢓্͕Γͱͳ͍ͬͯ·͢ɻ͜ͷͩ͜ΘΓͷ࢟੎͕ɺΑΓຊ෺ʹ͍ۙమಓ໛ܕମݧΛఏڙ͠·͢ɻ ͞Βʹɺಈ࡞໘ʹ΋஫໨Ͱ͢ɻ৽ܕ΍͘΋ܥ͸ɺύϫϑϧ͔ͭ੩͔ͳϞʔλʔΛ౥ࡌ͍ͯ͠·͢ɻεϜʔζͳ૸ߦੑೳͱ੩ԻੑΛཱ྆ͤ͞Δ͜ͱͰɺϦΞϧͳྻंͷಈ͖ Λ࠶ݱ͍ͯ͠·͢ɻ·ͨɺલর౮ͱඌ౮΋఺౮͢Δ࢓༷Ͱ͋ΓɺϞσϧͷඒ͚ͩ͠͞Ͱͳ͘ɺΑΓྟ৔ײ͋;ΕΔమಓମݧΛָ͠Ή͜ͱ͕Ͱ͖·͢ɻ ΋ͪΖΜɺ͜ͷ৽ܕ΍͘΋ܥ΋ଞͷమಓ໛ܕͱಉ༷ʹɺ૊ΈཱͯෆཁͰ͝࢖༻͍͚ͨͩ·͢ɻ։෧ޙ͙͢ʹऔΓग़ͯ͠ɺઢ࿏ʹηοτ͢Δ͚ͩͰమಓ໛ܕͷָ͠ΈΛຯΘ ͏͜ͱ͕Ͱ͖·͢ɻ·ͨɺࣗ͝୐ͷమಓ໛ܕϨΠΞ΢τʹ΋؆୯ʹ૊ΈࠐΉ͜ͱ͕Ͱ͖ɺΑΓ߽՚ͳγʔϯΛԋग़͢Δ͜ͱ͕Ͱ͖ΔͰ͠ΐ͏ɻ ͜ͷ৽ܕ΍͘΋ܥ͸ɺమಓϑΝϯͷΈͳΒͣɺେਓ͔Βࢠڙ·Ͱ෯޿͍૚ͷํʑʹָ͓͠Έ͍͚ͨͩ·͢ɻ·ͨɺమಓ໛ܕͷίϨΫγϣϯͱͯ͠΋࠷దͳҰ඼Ͱ͢ɻ৽͠ ͍మಓ໛ܕΛ͓୳͠ͷํ΍ɺॳΊͯమಓ໛ܕΛखʹ͞ΕΔํʹ΋ͽͬͨΓͷ঎඼ͱͳ͍ͬͯ·͢ɻ͜ͷػձʹɺͥͻ৽ܕ΍͘΋ܥΛखʹೖΕͯɺຊ෺ͷమಓͷੈքΛָ͠ ΜͰΈ·ͤΜ͔ʁ