api.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php declare(strict_types = 1);
  2. require_once __DIR__ . '/../vendor/autoload.php';
  3. ini_set('display_errors', 1);
  4. ini_set('error_reporting', E_ALL);
  5. #ini_set('variables_order', 'E');
  6. #ini_set('request_order', 'CGP');
  7. const PROJECT_PATH = __DIR__ . '/../';
  8. use Formstack\FormAutoScaffold\Framework\Main;
  9. use Formstack\FormAutoScaffold\FormstackAPI;
  10. $main = new Main(PROJECT_PATH);
  11. $main->run();
  12. #[Route('/api.php', 'POST')]
  13. function ok(array $args): void
  14. {
  15. $args = array_filter($args);
  16. global $json_cache;
  17. global $main;
  18. $dept = $args['dept'] ?? '';
  19. $industry = $args['industry'] ?? '';
  20. $name = $args['name'] ?? '';
  21. $fields = $args['fields'] ?? '';
  22. $prompt_file = $main->getConf('settings', 'prompt_file');
  23. $prompt = file_get_contents(PROJECT_PATH . $prompt_file);
  24. $prompt = str_replace('${DEPT}', $dept, $prompt);
  25. $prompt = str_replace('${INDUSTRY}', $industry, $prompt);
  26. $prompt = str_replace('${NAME}', $name, $prompt);
  27. $prompt = str_replace('${FIELDS}', $fields, $prompt);
  28. // Connect to Open AI and pass code
  29. $aiKey = $args['ai_tok'] ?? $main->getConf('settings', 'gpt_key');
  30. $openai = OpenAI::client($aiKey);
  31. $result = $openai->completions()->create([
  32. 'model' => 'gpt-3.5-turbo-instruct',
  33. 'prompt' => $prompt,
  34. 'max_tokens' => 4097 - strlen($prompt),
  35. 'temperature' => 0.3,
  36. ]);
  37. $json = $result['choices'][0]['text'];
  38. $main->log($json);
  39. $form_desc = json_decode($json, true, 512, \JSON_THROW_ON_ERROR & \JSON_INVALID_UTF8_IGNORE & \JSON_OBJECT_AS_ARRAY);
  40. $main->log(json_encode($form_desc));
  41. $fsApi = new FormstackAPI($main);
  42. $form = $fsApi->createForm($form_desc);
  43. header('Location: ' . $form['url'] ?? '');
  44. }