Explorar o código

feat:使用ChatClient进行API调用,将LLM的输出转换为Java对象;

yangyi hai 7 meses
pai
achega
063fe1dcb0

+ 12 - 0
src/main/java/space/anyi/springAiAlibabaLearn/controller/ChatClientController.java

@@ -14,6 +14,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestParam;
 import org.springframework.web.bind.annotation.RestController;
 import reactor.core.publisher.Flux;
+import space.anyi.springAiAlibabaLearn.model.Person;
 
 @RestController
 @RequestMapping("/chatClient")
@@ -78,4 +79,15 @@ public class ChatClientController {
                 })
                 .map(chatClientResponse -> chatClientResponse.chatResponse().getResult().getOutput().getText());
     }
+    @GetMapping("/entity")
+    public Person entity(){
+        //将LLM的输出转换为Java对象
+        /**
+         * 内部会在prompt中追加Person类的结构消息,并要求LLM输出符合格式的JSON字符串
+         */
+        return chatClient
+                .prompt("生成一个人的消息.")
+                .call()
+                .entity(Person.class);
+    }
 }

+ 53 - 0
src/main/java/space/anyi/springAiAlibabaLearn/model/Person.java

@@ -0,0 +1,53 @@
+package space.anyi.springAiAlibabaLearn.model;
+
+/**
+ * This is a test object used to convert LLM output into entity classes
+ */
+public class Person {
+    private String name;
+    private int age;
+    private String sex;
+    private float height;
+
+    public String getName() {
+        return name;
+    }
+
+    public void setName(String name) {
+        this.name = name;
+    }
+
+    public int getAge() {
+        return age;
+    }
+
+    public void setAge(int age) {
+        this.age = age;
+    }
+
+    public String getSex() {
+        return sex;
+    }
+
+    public void setSex(String sex) {
+        this.sex = sex;
+    }
+
+    public float getHeight() {
+        return height;
+    }
+
+    public void setHeight(float height) {
+        this.height = height;
+    }
+
+    @Override
+    public String toString() {
+        return "Person{" +
+                "name='" + name + '\'' +
+                ", age=" + age +
+                ", sex=" + sex +
+                ", height=" + height +
+                '}';
+    }
+}