大学网 > php中文网 > 每日编程SharpAPI Laravel 集成指南正文

SharpAPI Laravel 集成指南

中国大学网 2024-10-17

欢迎来到sharpapi Laravel 集成指南!该存储库提供了有关如何将 sharpapi 集成到下一个 laravel ai 应用程序中的全面的分步教程。无论您是希望通过**人工智能支持的功能**还是自动化工作流程来增强您的应用程序,本指南都将引导您完成从身份验证到进行 api 调用和处理响应的整个过程。

文章也作为 github 存储库发布在 https://github.com/sharpapi/laravel-ai-integration-guide。


目录

  1. 先决条件
  2. 设置 laravel 项目
  3. 安装 sharpapi php 客户端
  4. 配置
    • 环境变量
  5. 使用 sharpapi 进行身份验证
  6. 进行 api 调用
    • 示例:生成职位描述
  7. 处理响应
  8. 错误处理
  9. 测试集成
  10. 高级用法
    • 异步请求
    • 缓存响应
  11. 结论
  12. 支持
  13. 许可证

先决条件

开始之前,请确保您已满足以下要求:

  • php: >= 8.1
  • composer:php 的依赖管理器
  • laravel:版本 9 或更高版本
  • sharpapi 帐户:从 sharpapi.com 获取 api 密钥
  • laravel基础知识:熟悉laravel框架和mvc架构

设置 laravel 项目

如果你已经有 laravel 项目,可以跳过此步骤。否则,请按照以下说明创建一个新的 laravel 项目。

  1. 通过 composer 安装 laravel

   composer create-project --prefer-dist laravel/laravel laravel-ai-integration-guide


  1. 导航到项目目录

   cd laravel-ai-integration-guide


  1. 送达申请

   php artisan serve


可以通过 http://localhost:8000 访问该应用程序。


安装 sharpapi php 客户端

要与 sharpapi 交互,您需要安装 sharpapi php 客户端库。

需要通过 composer 安装 sharpapi 包


composer require sharpapi/sharpapi-laravel-client
php artisan vendor:publish --tag=sharpapi-laravel-client



配置

环境变量

在环境变量中存储 api 密钥等敏感信息是最佳实践。 laravel 使用 .env 文件进行特定于环境的配置。

  1. 打开 .env 文件

位于 laravel 项目的根目录中。

  1. 添加您的 sharpapi api 密钥

   sharp_api_key=your_actual_sharpapi_api_key_here


注意:将此处的 your_actual_sharpapi_api_key_key_替换为您实际的 sharpapi api 密钥。

  1. 在代码中访问环境变量

laravel 提供了 env 辅助函数来访问环境变量。


   $apikey = env('sharp_api_key');



使用 sharpapi 进行身份验证

需要进行身份验证才能安全地与 sharpapi 端点交互。

  1. 初始化 sharpapi 客户端

创建服务或直接在控制器中使用它。


   client = new sharpapiservice(env('sharp_api_key'));
       }

       public function getclient()
       {
           return $this->client;
       }
   }


  1. 将服务绑定到服务提供者中(可选)

这允许您在需要的地方注入服务。


   app->singleton(sharpapiclient::class, function ($app) {
               return new sharpapiclient();
           });
       }

       public function boot()
       {
           //
       }
   }


  1. 在控制器中使用服务

   sharpapi = $sharpapi->getclient();
       }

       public function ping()
       {
           $response = $this->sharpapi->ping();
           return response()->json($response);
       }
   }


  1. 定义路线

将路由添加到routes/web.php或routes/api.php:


   use app\http\controllers\sharpapicontroller;

   route::get('/sharpapi/ping', [sharpapicontroller::class, 'ping']);



进行 api 调用

经过身份验证后,您可以开始对各种 sharpapi 端点进行 api 调用。以下是如何与不同端点交互的示例。

示例:生成职位描述

  1. 创建作业描述参数 dto

   sharpapi = $sharpapi->getclient();
       }

       public function generatejobdescription()
       {
           $jobdescriptionparams = new jobdescriptionparameters(
               "software engineer",
               "tech corp",
               "5 years",
               "bachelor's degree in computer science",
               "full-time",
               [
                   "develop software applications",
                   "collaborate with cross-functional teams",
                   "participate in agile development processes"
               ],
               [
                   "proficiency in php and laravel",
                   "experience with restful apis",
                   "strong problem-solving skills"
               ],
               "usa",
               true,   // isremote
               true,   // hasbenefits
               "enthusiastic",
               "category c driving license",
               "english"
           );

           $statusurl = $this->sharpapi->generatejobdescription($jobdescriptionparams);
           $resultjob = $this->sharpapi->fetchresults($statusurl);

           return response()->json($resultjob->getresultjson());
       }
   }


  1. 定义路线

   route::get('/sharpapi/generate-job-description', [sharpapicontroller::class, 'generatejobdescription']);


  1. 访问端点

访问 http://localhost:8000/sharpapi/generate-job-description 查看生成的职位描述。


处理响应

sharpapi 响应通常封装在作业对象中。要有效处理这些响应:

  1. 理解响应结构

   {
       "id": "uuid",
       "type": "jobtype",
       "status": "completed",
       "result": {
           // result data
       }
   }


  1. 访问结果

使用提供的方法访问结果数据。


   $resultjob = $this->sharpapi->fetchresults($statusurl);
   $resultdata = $resultjob->getresultobject(); // as a php object
   // or
   $resultjson = $resultjob->getresultjson(); // as a json string


  1. 控制器中的用法示例

   public function generatejobdescription()
   {
       // ... (initialize and make api call)

       if ($resultjob->getstatus() === 'completed') {
           $resultdata = $resultjob->getresultobject();
           // process the result data as needed
           return response()->json($resultdata);
       } else {
           return response()->json(['message' => 'job not completed yet.'], 202);
       }
   }



错误处理

正确的错误处理可确保您的应用程序能够妥善处理 api 交互期间出现的问题。

  1. 捕获异常

将 api 调用包装在 try-catch 块中以处理异常。


   public function generatejobdescription()
   {
       try {
           // ... (initialize and make api call)

           $resultjob = $this->sharpapi->fetchresults($statusurl);
           return response()->json($resultjob->getresultjson());
       } catch (\exception $e) {
           return response()->json([
               'error' => 'an error occurred while generating the job description.',
               'message' => $e->getmessage()
           ], 500);
       }
   }


  1. 处理 api 错误

检查作业的状态,并针对不同的状态进行相应的处理。


   if ($resultjob->getstatus() === 'completed') {
       // handle success
   } elseif ($resultjob->getstatus() === 'failed') {
       // handle failure
       $error = $resultjob->getresultobject()->error;
       return response()->json(['error' => $error], 400);
   } else {
       // handle other statuses (e.g., pending, in progress)
       return response()->json(['message' => 'job is still in progress.'], 202);
   }



测试集成

测试对于确保您与 sharpapi 的集成按预期工作至关重要。

  1. 编写单元测试

使用 laravel 的内置测试工具为 sharpapi 集成编写单元测试。


   sharpapi = new sharpapiclient();
       }

       public function testping()
       {
           $response = $this->sharpapi->ping();
           $this->assertequals('ok', $response['status']);
       }

       public function testgeneratejobdescription()
       {
           $jobdescriptionparams = new jobdescriptionparameters(
               "backend developer",
               "innovatetech",
               "3 years",
               "bachelor's degree in computer science",
               "full-time",
               ["develop apis", "optimize database queries"],
               ["proficiency in php and laravel", "experience with restful apis"],
               "usa",
               true,
               true,
               "professional",
               "category b driving license",
               "english"
           );

           $statusurl = $this->sharpapi->generatejobdescription($jobdescriptionparams);
           $resultjob = $this->sharpapi->fetchresults($statusurl);

           $this->assertequals('completed', $resultjob->getstatus());
           $this->assertnotempty($resultjob->getresultobject());
       }

       // add more tests for other methods...
   }


  1. 运行测试

使用 phpunit 执行测试。


   ./vendor/bin/phpunit



高级用法

异步请求

要同时处理多个 api 请求,请考虑使用 laravel 队列实现异步处理。

  1. 设置队列

在 .env 文件中配置队列驱动程序。


   queue_connection=database


运行必要的迁移。


   php artisan queue:table
   php artisan migrate


  1. 创建工作

   php artisan make:job processsharpapirequest



   params = $params;
       }

       public function handle(sharpapiclient $sharpapi)
       {
           $statusurl = $sharpapi->generatejobdescription($this->params);
           $resultjob = $sharpapi->fetchresults($statusurl);
           // handle the result...
       }
   }


  1. 派遣工作

   use app\jobs\processsharpapirequest;

   public function generatejobdescriptionasync()
   {
       $jobdescriptionparams = new jobdescriptionparameters(
           // ... parameters
       );

       processsharpapirequest::dispatch($jobdescriptionparams);
       return response()->json(['message' => 'job dispatched successfully.']);
   }


  1. 运行队列工作线程

   php artisan queue:work


缓存响应

为了优化性能并减少冗余 api 调用,请实施缓存。

  1. 使用 laravel 的缓存外观

   use illuminate\support\facades\cache;

   public function generatejobdescription()
   {
       $cachekey = 'job_description_' . md5(json_encode($jobdescriptionparams));
       $result = cache::remember($cachekey, 3600, function () use ($jobdescriptionparams) {
           $statusurl = $this->sharpapi->generatejobdescription($jobdescriptionparams);
           $resultjob = $this->sharpapi->fetchresults($statusurl);
           return $resultjob->getresultjson();
       });

       return response()->json(json_decode($result, true));
   }


  1. 使缓存失效

底层数据发生变化时,确保相关缓存失效。


   Cache::forget('job_description_' . md5(json_encode($jobDescriptionParams)));



结论

将 sharpapi 集成到您的 laravel 应用程序中可以解锁大量人工智能驱动的功能,增强您的应用程序的功能并提供无缝的工作流程自动化。本指南引导您完成从设置身份验证到进行 api 调用和处理响应的基本步骤。通过提供的示例和最佳实践,您已经准备好在 laravel 项目中利用 sharpapi 的强大功能。


支持

如果您遇到任何问题或对集成过程有疑问,请随时在 github 存储库上提出问题,或通过 contact@sharpapi.com 联系我们的支持团队。


执照

该项目已获得 mit 许可。


以上就是SharpAPI Laravel 集成指南的详细内容,更多请关注中国大学网其它相关文章!