llm-agents/json-schema-mapper

LLM Agents 的 JSON Schema 到 PHP 类映射器

1.1.0 2024-09-01 13:46 UTC

This package is auto-updated.

Last update: 2024-09-21 04:23:40 UTC


README

PHP Latest Version on Packagist Total Downloads

此包是 LLM Agents 项目的一个非常方便的 JSON Schema 映射器。

这是关于什么的?

此包为您提供了一个巧妙的 SchemaMapper,可以

  • 将 PHP 类转换为 JSON 模式
  • 将 JSON 数据转换为 PHP 对象

类图

让我们快速了解一下主要组件是如何结合在一起的

入门指南

安装

首先,让我们安装这个包

composer require llm-agents/json-schema-mapper

在 Spiral 中设置

如果您使用的是 Spiral 框架(您当然应该使用!它很棒!),您需要注册引导加载器。

以下是方法

  1. 打开您的 app/src/Application/Kernel.php 文件。
  2. LLM\Agents\JsonSchema\Mapper\Integration\Spiral\SchemaMapperBootloader 添加到 defineBootloaders() 方法中
class Kernel extends \Spiral\Framework\Kernel
{
    // ...

    public function defineBootloaders(): array
    {
        return [
            // ... other bootloaders ...
            \LLM\Agents\JsonSchema\Mapper\Integration\Spiral\SchemaMapperBootloader::class,
        ];
    }
}

就这样!引导加载器将为您注册所有必要的组件。

在 Laravel 中设置

如果您使用的是 Laravel 框架,您需要注册服务提供者。

以下是方法

只需注册 LLM\Agents\JsonSchema\Mapper\Integration\Laravel\SchemaMapperServiceProvider

就这样!服务提供者将为您注册所有必要的组件。

如何使用

将 PHP 类转换为 JSON 模式

假设您有一个 User 类,并且您想获取其 JSON 模式

use LLM\Agents\JsonSchema\Mapper\SchemaMapperInterface;

class UserController
{
    public function __construct(
        private SchemaMapperInterface $schemaMapper
    ) {}

    public function getUserSchema(): array
    {
        return $this->schemaMapper->toJsonSchema(User::class);
    }
}

将 JSON 转换为 PHP 对象

有一些 JSON 数据您想转换成 PHP 对象?没问题

use LLM\Agents\JsonSchema\Mapper\SchemaMapperInterface;

class UserService
{
    public function __construct(
        private SchemaMapperInterface $schemaMapper
    ) {}

    public function createUserFromJson(string $json): User
    {
        return $this->schemaMapper->toObject($json, User::class);
    }
}

贡献

我们非常希望您能帮助我们使这个包变得更好!以下是您如何贡献的方法

  1. 叉取仓库
  2. 编写一些出色的代码
  3. 创建一个新的 Pull Request

请确保您的代码遵循 PSR-12 编码标准,并为任何新功能包含测试。

许可证

此包是开源软件,根据 MIT 许可证授权。请随意使用、修改和分享它!

这就结束了,朋友们!如果您有任何问题或遇到任何问题,请不要犹豫在 GitHub 上提交问题。