override suspend fun subtask()

in agents/agents-core/src/commonMain/kotlin/ai/koog/agents/core/agent/context/AIAgentFunctionalContextImpl.kt [351:416]


    override suspend fun <Input, OutputTransformed> subtask(
        taskDescription: String,
        input: Input,
        tools: List<Tool<*, *>>?,
        finishTool: Tool<*, OutputTransformed>,
        llmModel: LLModel?,
        llmParams: LLMParams?,
        runMode: ToolCalls,
        assistantResponseRepeatMax: Int?,
        responseProcessor: ResponseProcessor?
    ): OutputTransformed {
        val maxAssistantResponses = assistantResponseRepeatMax ?: SubgraphWithTaskUtils.ASSISTANT_RESPONSE_REPEAT_MAX

        val toolsSubset = tools?.map { it.descriptor } ?: llm.readSession { this.tools.toList() }

        val originalTools = llm.readSession { this.tools.toList() }
        val originalModel = llm.readSession { this.model }
        val originalParams = llm.readSession { this.prompt.params }
        val originalResponseProcessor = llm.readSession { this.responseProcessor }

        // setup:
        llm.writeSession {
            if (finishTool.descriptor !in toolsSubset) {
                this.tools = toolsSubset + finishTool.descriptor
            }

            if (llmModel != null) {
                model = llmModel
            }

            if (llmParams != null) {
                prompt = prompt.withParams(llmParams)
            }

            if (responseProcessor != null) {
                this.responseProcessor = responseProcessor
            }

            setToolChoiceRequired()
        }

        val result = when (runMode) {
            ToolCalls.SINGLE_RUN_SEQUENTIAL -> subtaskWithSingleToolMode(
                taskDescription,
                finishTool,
                maxAssistantResponses
            )

            else -> subtaskWithMultiToolMode(
                taskDescription,
                finishTool,
                runMode,
                maxAssistantResponses
            )
        }

        // rollback
        llm.writeSession {
            this.tools = originalTools
            this.model = originalModel
            this.prompt = prompt.withParams(originalParams)
            this.responseProcessor = originalResponseProcessor
        }

        return result
    }