1+ package com .phantoms .phantomsbackend .common .LLM ;
2+
3+ import com .fasterxml .jackson .databind .ObjectMapper ;
4+ import com .phantoms .phantomsbackend .common .config .LLMProperties ;
5+ import lombok .extern .slf4j .Slf4j ;
6+ import okhttp3 .*;
7+ import org .springframework .stereotype .Component ;
8+ import javax .annotation .PostConstruct ;
9+ import java .util .Map ;
10+
11+ @ Slf4j
12+ @ Component
13+ public class LLMClient {
14+ private final LLMProperties llmProperties ;
15+ private static final OkHttpClient HTTP_CLIENT = new OkHttpClient .Builder ()
16+ .connectTimeout (30 , java .util .concurrent .TimeUnit .SECONDS )
17+ .readTimeout (60 , java .util .concurrent .TimeUnit .SECONDS )
18+ .writeTimeout (30 , java .util .concurrent .TimeUnit .SECONDS )
19+ .build ();
20+ private static final ObjectMapper MAPPER = new ObjectMapper ();
21+
22+ public LLMClient (LLMProperties llmProperties ) {
23+ this .llmProperties = llmProperties ;
24+ }
25+
26+ @ PostConstruct
27+ public void init () {
28+ log .info ("=== LLM配置 ===" );
29+ log .info ("API URL: {}" , llmProperties .getApiUrl ());
30+ log .info ("API Key: {}" , llmProperties .getApiKey () != null ? llmProperties .getApiKey ().substring (0 , Math .min (10 , llmProperties .getApiKey ().length ())) + "***" : "null" );
31+ log .info ("Model Name: {}" , llmProperties .getModelName ());
32+ log .info ("Temperature: {}" , llmProperties .getTemperature ());
33+ log .info ("===============" );
34+ }
35+
36+ public String chat (String systemPrompt , String userInput ) throws Exception {
37+ Object [] messages = {
38+ Map .of ("role" , "system" , "content" , systemPrompt ),
39+ Map .of ("role" , "user" , "content" , userInput )
40+ };
41+
42+ var body = Map .of (
43+ "model" , llmProperties .getModelName (),
44+ "messages" , messages ,
45+ "temperature" , llmProperties .getTemperature ()
46+ );
47+
48+ String json = MAPPER .writeValueAsString (body );
49+ RequestBody requestBody = RequestBody .create (json , MediaType .parse ("application/json; charset=utf-8" ));
50+
51+ Request request = new Request .Builder ()
52+ .url (llmProperties .getApiUrl ())
53+ .header ("Authorization" , "Bearer " + llmProperties .getApiKey ())
54+ .post (requestBody )
55+ .build ();
56+
57+ try (Response response = HTTP_CLIENT .newCall (request ).execute ()) {
58+ if (!response .isSuccessful ()) {
59+ throw new RuntimeException ("LLM请求失败:" + response .code ());
60+ }
61+ Map <String , Object > resMap = MAPPER .readValue (response .body ().string (), Map .class );
62+ var choices = (Map <?, ?>) ((java .util .List <?>) resMap .get ("choices" )).get (0 );
63+ var msg = (Map <?, ?>) choices .get ("message" );
64+ return (String ) msg .get ("content" );
65+ }
66+ }
67+ }
0 commit comments