001/* 002 * Copyright (c) 2023-2026, Agents-Flex (fuhai999@gmail.com). 003 * <p> 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * <p> 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * <p> 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package com.agentsflex.core.model.chat.tool; 017 018import com.agentsflex.core.message.ToolCall; 019 020public final class ToolContextHolder { 021 022 private static final ThreadLocal<ToolContext> CONTEXT_HOLDER = new ThreadLocal<>(); 023 024 private ToolContextHolder() { 025 // 工具类,禁止实例化 026 } 027 028 029 public static ToolContextScope beginExecute(Tool tool, ToolCall toolCall) { 030 ToolContext ctx = new ToolContext(tool, toolCall); 031 CONTEXT_HOLDER.set(ctx); 032 return new ToolContextScope(ctx); 033 } 034 035 public static ToolContext currentContext() { 036 return CONTEXT_HOLDER.get(); 037 } 038 039 public static void clear() { 040 CONTEXT_HOLDER.remove(); 041 } 042 043 044 /** 045 * 用于 try-with-resources 的作用域对象,确保上下文自动清理。 046 */ 047 public static class ToolContextScope implements AutoCloseable { 048 049 ToolContext context; 050 051 public ToolContextScope(ToolContext context) { 052 this.context = context; 053 } 054 055 @Override 056 public void close() { 057 clear(); 058 } 059 } 060}