PHP项目文本摘要如何调用接口生成内容

wen PHP项目 32

本文目录导读:

PHP项目文本摘要如何调用接口生成内容

  1. 使用cURL调用API接口
  2. 使用Guzzle HTTP客户端
  3. 常用API示例
  4. 完整的调用示例类
  5. 注意事项

我来介绍PHP项目中调用文本摘要接口的几种常见方法:

使用cURL调用API接口

百度AI接口示例

<?php
function textSummary($text, $apiKey, $secretKey) {
    $url = "https://aip.baidubce.com/rpc/2.0/nlp/v1/news_summary";
    // 获取access_token
    $tokenUrl = "https://aip.baidubce.com/oauth/2.0/token";
    $postData = [
        'grant_type' => 'client_credentials',
        'client_id' => $apiKey,
        'client_secret' => $secretKey
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $tokenUrl);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    $tokenInfo = json_decode($response, true);
    $accessToken = $tokenInfo['access_token'];
    // 调用文本摘要接口
    $data = [
        'content' => $text,
        'max_summary_len' => 200
    ];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url . "?access_token=" . $accessToken);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return json_decode($result, true);
}
// 使用示例
$text = "这里是需要生成摘要的长文本内容...";
$apiKey = "your_api_key";
$secretKey = "your_secret_key";
$summary = textSummary($text, $apiKey, $secretKey);
print_r($summary);
?>

通用API调用封装函数

<?php
function callSummaryAPI($text, $apiUrl, $apiKey, $maxLength = 200) {
    $data = [
        'text' => $text,
        'max_length' => $maxLength,
        'min_length' => 50
    ];
    $headers = [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json'
    ];
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $apiUrl,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_SSL_VERIFYPEER => false
    ]);
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($httpCode == 200) {
        return json_decode($response, true);
    } else {
        return ['error' => 'API调用失败', 'code' => $httpCode];
    }
}
?>

使用Guzzle HTTP客户端

<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
class TextSummarizer {
    private $client;
    private $apiKey;
    private $apiUrl;
    public function __construct($apiKey, $apiUrl) {
        $this->client = new Client();
        $this->apiKey = $apiKey;
        $this->apiUrl = $apiUrl;
    }
    public function summarize($text, $options = []) {
        try {
            $response = $this->client->post($this->apiUrl, [
                'headers' => [
                    'Authorization' => 'Bearer ' . $this->apiKey,
                    'Content-Type' => 'application/json',
                ],
                'json' => array_merge([
                    'text' => $text,
                    'max_length' => 200,
                    'min_length' => 50,
                ], $options),
                'timeout' => 30,
            ]);
            return json_decode($response->getBody(), true);
        } catch (RequestException $e) {
            return [
                'error' => true,
                'message' => $e->getMessage()
            ];
        }
    }
}
// 使用示例
$summarizer = new TextSummarizer(
    'your_api_key',
    'https://api.example.com/summarize'
);
$result = $summarizer->summarize('这里是需要摘要的文本内容...');
echo $result['summary'];
?>

常用API示例

阿里云NLP接口

<?php
function aliyunTextSummary($text, $accessKeyId, $accessKeySecret) {
    require_once 'aliyun-php-sdk-core/Config.php';
    $client = new DefaultAcsClient(
        'cn-hangzhou',
        $accessKeyId,
        $accessKeySecret
    );
    $request = new Aliyun\Api\Nlp\Request\V20180408\TextSummaryRequest();
    $request->setAcceptFormat('JSON');
    $request->setTitle("文章标题");
    $request->setContent($text);
    $request->setSummaryLength(200);
    try {
        $response = $client->getAcsResponse($request);
        return json_decode(json_encode($response), true);
    } catch (Exception $e) {
        return ['error' => $e->getMessage()];
    }
}
?>

OpenAI GPT API

<?php
function openAISummary($text, $apiKey) {
    $url = "https://api.openai.com/v1/chat/completions";
    $data = [
        'model' => 'gpt-3.5-turbo',
        'messages' => [
            [
                'role' => 'system',
                'content' => '请对以下文本生成简洁的摘要,不超过100字:'
            ],
            [
                'role' => 'user',
                'content' => $text
            ]
        ],
        'max_tokens' => 200,
        'temperature' => 0.5
    ];
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => [
            'Authorization: Bearer ' . $apiKey,
            'Content-Type: application/json'
        ],
        CURLOPT_RETURNTRANSFER => true
    ]);
    $response = curl_exec($ch);
    curl_close($ch);
    return json_decode($response, true);
}
?>

完整的调用示例类

<?php
class TextSummaryService {
    private $provider;
    private $config;
    public function __construct($provider = 'baidu', $config = []) {
        $this->provider = $provider;
        $this->config = $config;
    }
    public function generate($text, $options = []) {
        switch ($this->provider) {
            case 'baidu':
                return $this->baiduSummary($text, $options);
            case 'aliyun':
                return $this->aliyunSummary($text, $options);
            case 'openai':
                return $this->openAISummary($text, $options);
            default:
                throw new Exception("不支持的API提供商");
        }
    }
    private function baiduSummary($text, $options) {
        // 百度API实现
        $apiKey = $this->config['api_key'] ?? '';
        $secretKey = $this->config['secret_key'] ?? '';
        return textSummary($text, $apiKey, $secretKey);
    }
    private function aliyunSummary($text, $options) {
        // 阿里云API实现
        $accessKeyId = $this->config['access_key_id'] ?? '';
        $accessKeySecret = $this->config['access_key_secret'] ?? '';
        return aliyunTextSummary($text, $accessKeyId, $accessKeySecret);
    }
    private function openAISummary($text, $options) {
        // OpenAI API实现
        $apiKey = $this->config['api_key'] ?? '';
        return openAISummary($text, $apiKey);
    }
}
// 使用示例
$config = [
    'api_key' => 'your_api_key',
    'secret_key' => 'your_secret_key'
];
$summaryService = new TextSummaryService('baidu', $config);
$result = $summaryService->generate('需要摘要的文本内容...');
?>

注意事项

  1. API密钥保护:密钥不要直接写在代码中,建议使用环境变量或配置文件
  2. 错误处理:添加完善的异常捕获和错误处理机制
  3. 文本长度限制:注意API的文本长度限制,超长文本需要分段处理
  4. 频率限制:了解API的调用频率限制,避免被限流
  5. 缓存机制:对相同内容的摘要可以缓存,减少API调用

需要我详细解释某个特定API的调用方法吗?

抱歉,评论功能暂时关闭!