HamaWhiteGG / langchain-java

Java version of LangChain, while empowering LLM for Big Data.
Apache License 2.0
551 stars 107 forks source link

是否有function call的案例? #109

Open mumengmeng opened 1 year ago

mumengmeng commented 1 year ago

是否有chatGPT的function call的案例

HamaWhiteGG commented 11 months ago

Yes, see doc OpenAI Function Call Example.md

or see ChatFunctionTest directly.

class ChatFunctionTest extends OpenAiClientTest {

    private static final Logger LOG = LoggerFactory.getLogger(ChatFunctionTest.class);

    private final String functionName = "get_current_weather";

    @BeforeEach
    void setUp() {
        // register function
        FunctionExecutor.register(functionName, this::getCurrentWeather);
    }

    WeatherResponse getCurrentWeather(Weather weather) {
        // mock function
        return WeatherResponse.builder()
                .location(weather.location())
                .unit(weather.unit())
                .temperature(new Random().nextInt(50))
                .description("sunny")
                .build();
    }

    @Test
    void testChatFunction() {
        ChatFunction chatFunction = ChatFunction.builder()
                .name(functionName)
                .description("Get the current weather in a given location")
                .parameters(ChatParameterUtils.generate(Weather.class))
                .build();

        Message message = Message.of("What is the weather like in Boston?");

        ChatCompletion chatCompletion = ChatCompletion.builder()
                .model("gpt-4")
                .temperature(0)
                .messages(List.of(message))
                .tools(List.of(new Tool(chatFunction)))
                .toolChoice("auto")
                .build();

        ChatCompletionResp response = client.createChatCompletion(chatCompletion);
        ChatChoice chatChoice = response.getChoices().get(0);
        LOG.info("result: {}", chatChoice);
        assertThat(chatChoice).isNotNull();
        assertEquals("tool_calls", chatChoice.getFinishReason());

        Function function = chatChoice.getMessage().getToolCalls().get(0).getFunction();
        // name=get_current_weather, arguments={ "location": "Boston" }
        assertEquals(functionName, function.getName());

        String expectedArguments = """
                {
                  "location": "Boston, MA"
                }""";
        assertEquals(expectedArguments, function.getArguments());

        // execute function
        WeatherResponse weatherResponse =
                FunctionExecutor.execute(function.getName(), Weather.class, function.getArguments());
        LOG.info("result: {}", weatherResponse);
        assertThat(weatherResponse).isNotNull();
    }
}