package com.example.springbootxunfeiai.service;import com.example.springbootxunfeiai.util.HttpUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@Service
public class SparkApiService {public String callSparkApi(String userMessage) {String url = "https://spark-api-open.xf-yun.com/v1/chat/completions";String apiPassword = "123"; // 替换为你的 API 密码Map<String, Object> requestBody = new HashMap<>();requestBody.put("model", "4.0Ultra");// 构建消息列表List<Map<String, String>> messages = new ArrayList<>();Map<String, String> userMessageMap = new HashMap<>();userMessageMap.put("role", "user");userMessageMap.put("content", userMessage);messages.add(userMessageMap);requestBody.put("messages", messages);// 构建工具列表List<Map<String, Object>> tools = new ArrayList<>();Map<String, Object> functionTool = new HashMap<>();functionTool.put("type", "function");Map<String, Object> functionDetails = new HashMap<>();functionDetails.put("name", "get_current_weather");functionDetails.put("description", "");Map<String, Object> parameters = new HashMap<>();parameters.put("type", "object");Map<String, Object> properties = new HashMap<>();Map<String, Object> location = new HashMap<>();location.put("type", "string");location.put("description", "");properties.put("location", location);Map<String, Object> format = new HashMap<>();format.put("type", "string");format.put("enum", new String[]{"celsius", "fahrenheit"});format.put("description", "");properties.put("format", format);parameters.put("properties", properties);parameters.put("required", new String[]{"location", "format"});functionDetails.put("parameters", parameters);functionTool.put("function", functionDetails);tools.add(functionTool);requestBody.put("tools", tools);// 设置请求头HttpHeaders headers = new HttpHeaders();headers.set("Authorization", "Bearer " + apiPassword);headers.set("Content-Type", "application/json");// 发送请求RestTemplate restTemplate = new RestTemplate();HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);HttpHeaders responseHeaders = response.getHeaders();String contentType = responseHeaders.getContentType().toString();String responseBody = response.getBody();if (contentType.contains("charset=UTF-8")) {try {responseBody = new String(response.getBody().getBytes("ISO-8859-1"), "UTF-8");} catch (Exception e) {e.printStackTrace();}}return responseBody;}}
注意这里apiPassword去讯飞星火控制台自己的应用查找
具体传参可以查看文档
星火认知大模型Web API文档 | 讯飞开放平台文档中心