Lambdua / openai4j

Java client library for OpenAI API.Full support for all OpenAI API models including Completions, Chat, Edits, Embeddings, Audio, Files, Assistants-v2, Images, Moderations, Batch, and Fine-tuning.
MIT License
331 stars 31 forks source link

ToolCall 没调用 #69

Closed Mr-LiuDC closed 1 month ago

Mr-LiuDC commented 1 month ago

项目里面的单元测试有如下代码,是不是使用不对?它没有没有执行函数调用的 executor 逻辑 返回 WeatherResponse,即使设置 ToolChoice.REQUIRED 也是一样的效果。

static void toolChat() {
        OpenAiService service = new OpenAiService();
        final ChatTool tool = new ChatTool(ToolUtil.weatherFunction());
        final List<ChatMessage> messages = new ArrayList<>();
        final ChatMessage systemMessage = new SystemMessage("You are a helpful assistant.");
        final ChatMessage userMessage = new UserMessage("What is the weather in BeiJin?");
        messages.add(systemMessage);
        messages.add(userMessage);

        ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest.builder()
                .model("gpt-4o-mini")
                .messages(messages)
                //Tools is a list; multiple tools can be included
                .tools(Collections.singletonList(tool))
                .toolChoice(ToolChoice.AUTO)
                .n(1)
                .maxTokens(100)
                .build();
        //Request is sent
        ChatCompletionChoice choice = service.createChatCompletion(chatCompletionRequest).getChoices().get(0);
        AssistantMessage toolCallMsg = choice.getMessage();
        ChatToolCall toolCall = toolCallMsg.getToolCalls().get(0);
        System.out.println(toolCall.getFunction());

        messages.add(toolCallMsg);
        messages.add(new ToolMessage("the weather is fine today.", toolCall.getId()));

        //submit tool call
        ChatCompletionRequest toolCallRequest = ChatCompletionRequest.builder()
                .model("gpt-4o-mini")
                .messages(messages)
                .n(1)
                .maxTokens(100)
                .build();
        ChatCompletionChoice toolCallChoice = service.createChatCompletion(toolCallRequest).getChoices().get(0);
        System.out.println(toolCallChoice.getMessage().getContent());
    }
Mr-LiuDC commented 1 month ago

还是要进行如下操作才行

FunctionExecutorManager functionExecutor = new FunctionExecutorManager(Collections.singletonList(functionDefinition)); ToolMessage toolMessage = functionExecutor.executeAndConvertToChatMessage(chatFunctionCall.getName(), chatFunctionCall.getArguments(), toolCall.getId());

Lambdua commented 1 month ago

这里只是调用演示,具体函数调用需要主动调用的