# 1. Define a list of callable tools for the model # (Note that `parameters` are defined in JSON Schema) tools = [ { "type": "function", "name": "get_weather", "description": "Retrieves current weather for the given location.", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "City e.g. Beijng, Chegndu" } }, "required": ["location"], "additionalProperties": False }, "strict": True }, ]
defget_weather(location: str) -> str: # Here you would normally make an API call to a weather service return'{"temperature": 14}'
# Create a running input list we will add to over time input_list = [ {"role": "user", "content": "What is the weather like in Chengdu?"}, ]
# 2. Prompt the model with tools defined response = client.responses.create( model="gpt-5", tools=tools, input=input_list, )
# Save function call outputs for subsequent requests input_list += response.output
for item in response.output: if item.type == "function_call": if item.name == "get_weather": # 3. Execute the function logic for `get_weather` location = json.loads(item.arguments)["location"] output = get_weather(location) # 4. Provide function call results to the model input_list.append({ "type": "function_call_output", "call_id": item.call_id, "output": output, })
response = client.responses.create( model="gpt-5", instructions="You are a helpful assistant.", tools=tools, input=input_list, )
# 5. The model should be able to give a response! print(response.output_text)
# Output: # The current temperature in Chengdu is about 14°C.
from langchain.chat_models import init_chat_model from langchain.tools import tool
model = init_chat_model("gpt-5")
@tool defget_weather(location: str) -> str: """Retrieves current weather for the given location.""" returnf"It's sunny in {location}."
# 1. Bind (potentially multiple) tools to the model model_with_tools = model.bind_tools([get_weather])
# 2. Model generates tool calls messages = [{"role": "user", "content": "What's the weather like in Chengdu?"}] ai_msg = model_with_tools.invoke(messages) messages.append(ai_msg)
for tool_call in ai_msg.tool_calls: # 3. Execute the tool with the generated arguments tool_result = get_weather.invoke(tool_call) # 4. Pass results back to model messages.append(tool_result)
# 5. Model generates the final response final_response = model_with_tools.invoke(messages) print(final_response.text)
from langchain.agents import create_agent from langchain.chat_models import init_chat_model from langchain.tools import tool
model = init_chat_model("gpt-5")
@tool defget_weather(location: str) -> str: """Retrieves current weather for the given location.""" returnf"It's sunny in {location}."
agent = create_agent(model, tools=[get_weather]) result = agent.invoke( {"messages": [{"role": "user", "content": "What's the weather like in Chengdu?"}]} ) print(result["messages"][-1].content)
System: You are a helpful weather assistant. User: What is the weather like in Chengdu? Assistant: ToolCall(name="get_weather", args={"location": "Chengdu"}) User: ToolOutput(result={"weather": "Sunny", "temperature": "22°C"}) Assistant: The weather in Chengdu is Sunny with a temperature of 22°C.
System: You are Claude Code, Anthropic's official CLI for Claude. User: What files are there? Assistant: ToolCall(name="Bash", args={"command": "ls"}) User: ToolOutput(result="[README.md]") Assistant: There is only one file named README.md. User: Create a hello world function in Python. Assistant: ToolCall(name="Write", args={"file_path": "hello_world.py", "content": "def hello_world():\n print('Hello, World!')\n\nif __name__ == '__main__':\n hello_world()"}) User: ToolOutput(result="Created `hello_world.py` with a simple hello world function.") Assistant: I've created a simple Python file with a "Hello, World!" function.
上下文过载导致性能下降:即使最先进的LLM支持长上下文(如百万token),但如果上下文内容过多,其性能也会显著下降。除了经典的Lost in the Middle,还会出现上下文污染(Context Poisoning)、上下文混淆(Context Confusion)等各种问题。感兴趣的读者可以进一步参考How Long Contexts Fail。
System: You are Claude Code...\n\nYou have access to the following resources:\n- `resources/frontend-design.md`: Guidelines for designing the frontend UI. User: Generate a blog frontend UI. Assistant: ToolCall(name="Read", args={"file_path": "resources/fontend-design.md"}) User: ToolOutput(result="Choose fonts that are beautiful, unique, and interesting...") Assistant: ToolCall(name="Write", args={"file_path": "app/index.html", "content": "<html><head><style>...</style></head><body>...</body></html>"}) User: ToolOutput(result="Created file `app/index.html`.") Assistant: ToolCall(name="Write", args={"file_path": "app/styles.css", "content": "..."}) User: ToolOutput(result="Created file `app/styles.css`.") Assistant: I've generated a simple blog frontend UI based on the guidelines.
📤 REQUEST: ---------------------------------------- System: System[0]: type: text text: You are Claude Code, Anthropic's official CLI for Claude. System[1]: type: text text: You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
...
Messages: Message[0]: role: user content: Content[0]: type: text text: <system-reminder> This is a reminder that your todo list is currently empty. DO NOT mention this to the user explicitly because they are already aware. If you are working on tasks that would benefit from a todo list please use the TodoWrite tool to create one. If not, please feel free to ignore. Again do not mention this message to the user. </system-reminder> Content[1]: type: text text: <system-reminder> As you answer the user's questions, you can use the following context: # important-instruction-reminders Do what has been asked; nothing more, nothing less. NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one. NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User. IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task. </system-reminder> Content[2]: type: text text: create a hello world function in python Tools: ...
Tool[8]: Name: Write Description: Writes a file to the local filesystem.
Usage: - This tool will overwrite the existing file if there is one at the provided path. - If this is an existing file, you MUST use the Read tool first to read the file's contents. This tool will fail if you did not read the file first. - ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required. - NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User. - Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked. Input Schema: Type: object Required: file_path, content Properties: file_path, content
Messages: Message[0]: role: user content: Content[0]: type: text text: <system-reminder> This is a reminder that your todo list is currently empty. DO NOT mention this to the user explicitly because they are already aware. If you are working on tasks that would benefit from a todo list please use the TodoWrite tool to create one. If not, please feel free to ignore. Again do not mention this message to the user. </system-reminder> Content[1]: type: text text: <system-reminder> As you answer the user's questions, you can use the following context: # important-instruction-reminders Do what has been asked; nothing more, nothing less. NEVER create files unless they're absolutely necessary for achieving your goal. ALWAYS prefer editing an existing file to creating a new one. NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User. IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task. </system-reminder> Content[2]: type: text text: create a hello world function in python Message[1]: role: assistant content: Content[0]: type: text text: (no content) Content[1]: type: tool_use id: toolu_bdrk_01Tv5P8iPpKfvXkD7jGmjLFr name: Write input: {'file_path': '/Users/russellluo/Projects/demo/hello_world.py', 'content': 'def hello_world():\n print("Hello, World!")\n\nif __name__ == "__main__":\n hello_world()'} Message[2]: role: user content: Content[0]: tool_use_id: toolu_bdrk_01Tv5P8iPpKfvXkD7jGmjLFr type: tool_result content: File created successfully at: /Users/russellluo/Projects/demo/hello_world.py Tools: ...
📥 RESPONSE: ---------------------------------------- 📡 Parsed SSE Response: Created `hello_world.py` with a simple hello world function.
思考与行动(FLOW #1):这是循环的起点。LLM接收系统上下文和用户指令(create a hello world function in python)后,经过内部推理,决定采取行动——使用Write工具,它生成了完整的代码内容并指定了文件路径。
观察与完成(FLOW #2):这是循环的下一步。经用户确认后,Write工具被执行,系统于是接收到了执行结果(File created successfully at...)。LLM观察到这个反馈后,判定任务已成功完成,于是决定结束循环,并生成最终响应给用户(Created 'hello_world.py' with a simple hello world function.)。
# System prompt for Claude Code SYSTEM = [ { "type": "text", "text": "You are Claude Code, Anthropic's official CLI for Claude.", }, { "type": "text", "text": f""" You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user. Here is useful information about the environment you are running in: <env> Working directory: {CWD} </env> """, }, ]
# Write tool definition WRITE_TOOL = { "name": "Write", "description": "Writes a file to the local filesystem.", "input_schema": { "type": "object", "properties": { "file_path": { "type": "string", "description": "The absolute path to the file to write (must be absolute, not relative)", }, "content": { "type": "string", "description": "The content to write to the file", }, }, "required": ["file_path", "content"], "additionalProperties": False, }, }
defexecute_tool(tool_name: str, tool_input: dict[str, Any]) -> str: """Execute tool function with user confirmation""" if tool_name.lower() != "write": returnf"Error: Unknown tool `{tool_name}`"
# User confirmation whileTrue: file_name = os.path.basename(tool_input["file_path"]) confirmation = ( input(f""" ``` {tool_input["content"]} ``` Do you want to create `{file_name}`? (Y/N) > """) .strip() .lower() ) if confirmation == "y": return write_file(tool_input["file_path"], tool_input["content"]) else: returnf"User rejected write to `{file_name}`"
defwrite_file(file_path: str, content: str) -> str: """Write content to a file at the specified path""" try: os.makedirs(os.path.dirname(file_path), exist_ok=True) withopen(file_path, "w", encoding="utf-8") as f: f.write(content) returnf"File created successfully at: {file_path}" except Exception as e: returnf"Error writing file: {str(e)}"
defrun_agent_in_loop(messages: list[dict], max_turns: int = 5) -> None: """Run the coding agent in a loop""" for turn inrange(max_turns): # Call Claude response = client.messages.create( model=MODEL, max_tokens=1024, system=SYSTEM, tools=[WRITE_TOOL], messages=messages, )
response_content = response.content[0]
# Text response - task completed if response_content.type == "text": print(f"\n⏺ {response_content.text}") break
$ python lite_claude_code_v1.py ================================================== 🤖 Lite Claude Code (^C to exit) ==================================================
> create a hello world functionin python
``` def hello_world(): print("Hello, World!")
if __name__ == "__main__": hello_world() ``` Do you want to create `hello_world.py`? (Y/N) > y
⏺ I've created a simple Python file with a "Hello, World!" function. ... >