php调用讯飞星火ai人工智能问答api示例代码

代码语言:php

所属分类:通讯

代码描述:php调用讯飞星火ai人工智能问答api示例代码

代码标签: php 调用 讯飞 星火 ai 人工 智能 问答 api 示例 代码

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<?php
require('/data/wwwroot/default/lib/php/vendor/autoload.php');

//应用了三方的websocket 库,链接地址:https://github.com/Textalk/websocket-php
use WebSocket\Client;
class test{
	function xfyun(){
	    
		    $addr = "wss://spark-api.xf-yun.com/v3.1/chat";
			//密钥信息,在开放平台-控制台中获取:https://console.xfyun.cn/services/cbm
		    $Appid = "××××××";
		    $Apikey = "××××××";
		    // $XCurTime =time();
		    $ApiSecret ="××××××";
		    // $XCheckSum ="";
		    
		    // $data = $this->getBody("你是谁?");
			$authUrl = $this->assembleAuthUrl("GET",$addr,$Apikey,$ApiSecret);
			//创建ws连接对象
			$client = new Client($authUrl);

			// 连接到 WebSocket 服务器
			if ($client) {
			  
				// 发送数据到 WebSocket 服务器
				$data = $this->getBody($Appid,"你是谁?");
				$client->send($data);

				// 从 WebSocket 服务器接收数据
				$answer = "";
				while(true){
					$response = $client->receive();
					$resp = json_decode($response,true);
					$code = $resp["header"]["code"];
					echo "从服务器接收到的数据: " . $response;
					if(0 == $code){
						$status = $resp["header"]["status"];
						if($status != 2){
							$content = $resp['payload']['choices']['text'][0]['content'];
							$answer .= $content;
						}else{
							$content = $resp['payload']['choices']['text'][0]['content'];
							$answer .= $content;
							$total_tokens = $resp['payload']['usage']['text']['total_tokens'];
							print("\n本次消耗token用量:\n");
							print($total_tokens);
							break;
						}
					}else{
						echo "服务返回报错".$response;
						break;
					}
				}

				print("\n返回结果为:\n");
				print($answer);
			} else {
				echo "无法连接到 WebSocket 服务器";
			}



		}

		/**
		 * 发送post请求
		 * @param string $url 请求地址
		 * @param array $post_data post键值对数据
		 * @return string
		 */
		function http_request($url, $post_data, $headers) {		 
		  $postdata = http_build_query($post_data);
		  $options = array(
		    'http' => array(
		      'method' => 'POST',
		      'header' => $headers,
		      'content' => $postdata,
		      'timeout' => 15 * 60 // 超时时间(单位:s)
		    )
		  );
		  $context = stream_context_create($options);
		  $result = file_get_contents($url, false, $context);
 
		  echo $result; 
			
		  return "success";
		}

		//构造参数体
		function getBody($appid,$question){
			$header = array(
				"app_id" => $appid,
				"uid" => "12345"
			);
			
			$parameter = array(
				"chat" => array(
					"domain" => "generalv3",
					"temperature" => 0.5,
					"max_tokens" => 1024
			.........完整代码请登录后点击上方下载按钮下载查看

网友评论0