OcrApiClient.java 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package com.qmth.ops.biz.ai.client;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import com.qmth.boot.core.rateLimit.service.RateLimiter;
  4. import com.qmth.boot.core.rateLimit.service.impl.MemoryRateLimiter;
  5. import com.qmth.ops.biz.ai.exception.OcrRateLimitExceeded;
  6. import okhttp3.*;
  7. import java.io.IOException;
  8. /**
  9. * 大模型chat类接口基础实现
  10. */
  11. public abstract class OcrApiClient {
  12. private OkHttpClient client;
  13. private OcrApiConfig config;
  14. private ObjectMapper mapper;
  15. private RateLimiter queryRateLimiter;
  16. public OcrApiClient(OcrApiConfig config) {
  17. this.client = new OkHttpClient.Builder().connectionPool(new ConnectionPool()).build();
  18. this.mapper = new ObjectMapper();
  19. this.config = config;
  20. if (config.getQps() > 0) {
  21. this.queryRateLimiter = new MemoryRateLimiter(config.getQps(), 1000);
  22. }
  23. }
  24. protected OcrApiConfig getConfig() {
  25. return config;
  26. }
  27. protected abstract String buildUrl() throws Exception;
  28. protected abstract String buildResult(byte[] data, ObjectMapper mapper) throws IOException;
  29. protected abstract String handleError(byte[] data, int statusCode, ObjectMapper mapper);
  30. public String call(byte[] image) throws Exception {
  31. if (queryRateLimiter != null && !queryRateLimiter.acquire()) {
  32. throw new OcrRateLimitExceeded(config.getQps());
  33. }
  34. RequestBody body = RequestBody.create(MediaType.parse("application/octet-stream"), image);
  35. Request httpRequest = new Request.Builder().url(buildUrl()).post(body).build();
  36. Response response = client.newCall(httpRequest).execute();
  37. byte[] data = response.body() != null ? response.body().bytes() : null;
  38. if (response.isSuccessful()) {
  39. return buildResult(data, mapper);
  40. } else {
  41. return handleError(data, response.code(), mapper);
  42. }
  43. }
  44. }