處理請求的邏輯

在請求處理過程中,我們需要遵循以下步驟:

信息校驗

  1. 判斷是否使用付費模型:確保用戶有相應的權限使用高級模型。
  2. 校驗提問額度:確保用戶在使用模型時沒有超過提問限額。
  3. 檢查敏感詞:自建敏感詞系統,通過 SSE 通知用戶檢查到敏感內容,并在稍后進行調查。

獲取模型 API Key

根據用戶選擇的模型獲取相應的 API Key 列表,以確保請求可以正確發送到目標模型。

獲取聊天記錄

在處理新請求時,查看用戶的歷史聊天記錄,以提供更準確的上下文信息。

構建對象并發送給策略工廠處理

策略工廠負責根據前期處理的信息,使用對應模型的 SDK 處理請求,并發送請求和響應。

策略工廠的實現

策略工廠的設計主要包括以下幾個包:

@Slf4j
public abstract class AiModelStrategy {

   /**
    * SSE 流式對話
    */
   public abstract void contextStreamChat(AiModeChatParams aiModeChatParams);
}

AiModeChatParams 的實現如下:

@Data
@NoArgsConstructor
public class AiModeChatParams {

   @ApiModelProperty("用戶發送消息")
   private String prompt;

   @ApiModelProperty("會話 ID")
   private String chatDialogueId;

   @ApiModelProperty("模型選擇")
   private String chatModel;

   @ApiModelProperty(value = "對話機器人ID")
   private String robotModelId;

   @ApiModelProperty("最大 token 數量")
   private int maxTokens = 2048;

   @ApiModelProperty("密鑰集合")
   private List apiKeys = new ArrayList();

   @ApiModelProperty("上下文消息")
   private List chatMessageList;

   @ApiModelProperty("請求路徑")
   private String apiHost;

   @ApiModelProperty("SSE")
   private EventSourceListener eventSourceListener;

   @ApiModelProperty("上傳圖片")
   private List imageList;
}

工廠實現

@Service
@Slf4j
public class AiModelFactory {

   @Autowired
   private Map map = new ConcurrentHashMap();

   public AiModelStrategy getStrategy(String componentName) {

      LogPrintUtils.info(log, "進入外部產品工廠方法 : {}", componentName);

      AiModelStrategy strategy = map.get(componentName);

      if (strategy == null) {
         strategy = map.get("stdNullStrategy");
      }

      LogPrintUtils.info(log, "帶走了:{}", strategy);

      return strategy;
   }
}

策略實現

@Service
public class AmXfxhStrategy extends AiModelStrategy {

   @Override
   public void contextStreamChat(AiModeChatParams aiModeChatParams) {

      // 構建參數

      // 發送請求

   }
}

通過這種設計,我們可以將各個大模型的請求構建和發送邏輯放入策略工廠中,減少代碼重復,提高系統的可擴展性。

通過 HTTP 封裝實現網絡模型 API

在對接大模型時,接口文檔是非常重要的參考資料。它描述了軟件組件或系統中的接口,包括接口名稱、方法、參數、返回值和異常等信息。通過接口文檔,我們可以了解如何調用大模型的 API。

規范實現接口文檔

以智譜 AI 的 GLM-4 模型為例,以下是通過 HTTP 調用該模型的示例代碼:

private static final String API_URL = "https://example.com/api"; // 替換為實際的 API URL
private static final String API_KEY = "your_api_key"; // 填寫您的 API Key

public static void main(String[] args) throws IOException {

    OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .build();

    JSONObject requestBodyJson = new JSONObject();
    requestBodyJson.put("model", "glm-4-plus");

    JSONArray messages = new JSONArray();
    messages.put(new JSONObject().put("role", "system")
            .put("content", "你是一個樂于解答各種問題的助手,你的任務是為用戶提供專業、準確、有見地的建議。"));
    messages.put(new JSONObject().put("role", "user")
            .put("content", "如何實現重定向"));

    requestBodyJson.put("messages", messages);

    RequestBody body = RequestBody.create(
            requestBodyJson.toString(),
            MediaType.parse("application/json")
    );

    Request request = new Request.Builder()
            .url(API_URL)
            .addHeader("Authorization", "Bearer " + API_KEY)
            .post(body)
            .build();

    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        }

        String responseBody = response.body().string();
        JSONObject jsonResponse = new JSONObject(responseBody);
        String assistantReply = jsonResponse.getJSONArray("choices")
                .getJSONObject(0)
                .getJSONObject("message")
                .getString("content");

        System.out.println(assistantReply);
    }
}

通過以上代碼,我們可以看到如何創建 HTTP 請求,發送請求并解析響應。

結論

通過工廠策略模式,我們能夠高效地對接多家國內已備案的大模型,減少代碼重復,提升系統的可擴展性。同時,通過規范的接口文檔和 HTTP 調用,我們能夠更好地實現大模型的功能應用。這種方法不僅適用于 AI 大模型,也可以應用于其他需要多策略、多接口對接的場景。

FAQ

  1. 問:什么是工廠策略模式?

  2. 問:為什么需要對接多個大模型?

  3. 問:如何確保接口調用的安全性?

  4. 問:什么是 SSE 連接?

  5. 問:如何處理接口文檔中的敏感詞?

上一篇:

URL 重定向:深入解析與應用

下一篇:

Transformer論文原文深度解讀與應用
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費