[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75KYATKWS15PR40ERBGP5JF":3,"skill-same:01M75KYATKWS15PR40ERBGP5JF":45},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":23,"commitSha":24,"skillDirectory":25,"forksCount":26,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":29,"updatedAt":30,"install":31,"resources":44},"01M75KYATKWS15PR40ERBGP5JF","langchain-fundamentals",null,"Create LangChain agents with create_agent, define tools, and use middleware for human-in-the-loop and error handling.","ydf0509\u002Flc-agent","ydf0509","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F26890690?v=4","01M75KX7AQYS5FN6KPSDJAVM43","01M75KX7C61TGAM4RM0M3K4XG6",8,"MIT","https:\u002F\u002Fgithub.com\u002Fydf0509\u002Flc-agent\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Flangchain_skills\u002Flangchain-fundamentals\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: langchain-fundamentals\ndescription: Create LangChain agents with create_agent, define tools, and use middleware for human-in-the-loop and error handling.\n---\n\n\u003Coneliner>\nBuild production agents using `create_agent()`, middleware patterns, and the `@tool` decorator \u002F `tool()` function. When creating LangChain agents, you MUST use create_agent(), with middleware for custom flows. All other alternatives are outdated.\n\u003C\u002Foneliner>\n\n\u003Ccreate_agent>\n## Creating Agents with create_agent\n\n`create_agent()` is the recommended way to build agents. It handles the agent loop, tool execution, and state management.\n\n### Agent Configuration Options\n\n| Parameter | Purpose | Example |\n|-----------|---------|---------|\n| `model` | LLM to use | `\"anthropic:claude-sonnet-4-5\"` or model instance |\n| `tools` | List of tools | `[search, calculator]` |\n| `system_prompt` \u002F `systemPrompt` | Agent instructions | `\"You are a helpful assistant\"` |\n| `checkpointer` | State persistence | `MemorySaver()` |\n| `middleware` | Processing hooks | `[HumanInTheLoopMiddleware]` (Python) \u002F `[humanInTheLoopMiddleware({...})]` (TypeScript) |\n\u003C\u002Fcreate_agent>\n\n\u003Cex-basic-agent>\n\u003Cpython>\n\n```python\nfrom langchain.agents import create_agent\nfrom langchain_core.tools import tool\n\n@tool\ndef get_weather(location: str) -> str:\n    \"\"\"Get current weather for a location.\n\n    Args:\n        location: City name\n    \"\"\"\n    return f\"Weather in {location}: Sunny, 72F\"\n\nagent = create_agent(\n    model=\"anthropic:claude-sonnet-4-5\",\n    tools=[get_weather],\n    system_prompt=\"You are a helpful assistant.\"\n)\n\nresult = agent.invoke({\n    \"messages\": [{\"role\": \"user\", \"content\": \"What's the weather in Paris?\"}]\n})\nprint(result[\"messages\"][-1].content)\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\n\n```typescript\nimport { createAgent } from \"langchain\";\nimport { tool } from \"@langchain\u002Fcore\u002Ftools\";\nimport { z } from \"zod\";\n\nconst getWeather = tool(\n  async ({ location }) => `Weather in ${location}: Sunny, 72F`,\n  {\n    name: \"get_weather\",\n    description: \"Get current weather for a location.\",\n    schema: z.object({ location: z.string().describe(\"City name\") }),\n  }\n);\n\nconst agent = createAgent({\n  model: \"anthropic:claude-sonnet-4-5\",\n  tools: [getWeather],\n  systemPrompt: \"You are a helpful assistant.\",\n});\n\nconst result = await agent.invoke({\n  messages: [{ role: \"user\", content: \"What's the weather in Paris?\" }],\n});\nconsole.log(result.messages[result.messages.length - 1].content);\n```\n\u003C\u002Ftypescript>\n\u003C\u002Fex-basic-agent>\n\n\u003Cex-agent-with-persistence>\n\u003Cpython>\nAdd MemorySaver checkpointer to maintain conversation state across invocations.\n\n```python\nfrom langchain.agents import create_agent\nfrom langgraph.checkpoint.memory import MemorySaver\n\ncheckpointer = MemorySaver()\n\nagent = create_agent(\n    model=\"anthropic:claude-sonnet-4-5\",\n    tools=[search],\n    checkpointer=checkpointer,\n)\n\nconfig = {\"configurable\": {\"thread_id\": \"user-123\"}}\nagent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"My name is Alice\"}]}, config=config)\nresult = agent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"What's my name?\"}]}, config=config)\n# Agent remembers: \"Your name is Alice\"\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\nAdd MemorySaver checkpointer to maintain conversation state across invocations.\n\n```typescript\nimport { createAgent } from \"langchain\";\nimport { MemorySaver } from \"@langchain\u002Flanggraph\";\n\nconst checkpointer = new MemorySaver();\n\nconst agent = createAgent({\n  model: \"anthropic:claude-sonnet-4-5\",\n  tools: [search],\n  checkpointer,\n});\n\nconst config = { configurable: { thread_id: \"user-123\" } };\nawait agent.invoke({ messages: [{ role: \"user\", content: \"My name is Alice\" }] }, config);\nconst result = await agent.invoke({ messages: [{ role: \"user\", content: \"What's my name?\" }] }, config);\n\u002F\u002F Agent remembers: \"Your name is Alice\"\n```\n\u003C\u002Ftypescript>\n\u003C\u002Fex-agent-with-persistence>\n\n\u003Ctools>\n## Defining Tools\n\nTools are functions that agents can call. Use the `@tool` decorator (Python) or `tool()` function (TypeScript).\n\u003C\u002Ftools>\n\n\u003Cex-basic-tool>\n\u003Cpython>\n\n```python\nfrom langchain_core.tools import tool\n\n@tool\ndef add(a: float, b: float) -> float:\n    \"\"\"Add two numbers.\n\n    Args:\n        a: First number\n        b: Second number\n    \"\"\"\n    return a + b\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\n\n```typescript\nimport { tool } from \"@langchain\u002Fcore\u002Ftools\";\nimport { z } from \"zod\";\n\nconst add = tool(\n  async ({ a, b }) => a + b,\n  {\n    name: \"add\",\n    description: \"Add two numbers.\",\n    schema: z.object({\n      a: z.number().describe(\"First number\"),\n      b: z.number().describe(\"Second number\"),\n    }),\n  }\n);\n```\n\u003C\u002Ftypescript>\n\u003C\u002Fex-basic-tool>\n\n\u003Cmiddleware>\n## Middleware for Agent Control\n\nMiddleware intercepts the agent loop to add human approval, error handling, logging, and more. A deep understanding of middleware is essential for production agents — use `HumanInTheLoopMiddleware` (Python) \u002F `humanInTheLoopMiddleware` (TypeScript) for approval workflows, and `@wrap_tool_call` (Python) \u002F `createMiddleware` (TypeScript) for custom hooks.\n\nKey imports:\n\n```python\nfrom langchain.agents.middleware import HumanInTheLoopMiddleware, wrap_tool_call\n```\n\n```typescript\nimport { humanInTheLoopMiddleware, createMiddleware } from \"langchain\";\n```\n\nKey patterns:\n- **HITL**: `middleware=[HumanInTheLoopMiddleware(interrupt_on={\"dangerous_tool\": True})]` — requires `checkpointer` + `thread_id`\n- **Resume after interrupt**: `agent.invoke(Command(resume={\"decisions\": [{\"type\": \"approve\"}]}), config=config)`\n- **Custom middleware**: `@wrap_tool_call` decorator (Python) or `createMiddleware({ wrapToolCall: ... })` (TypeScript)\n\u003C\u002Fmiddleware>\n\n\u003Cstructured_output>\n## Structured Output\n\nGet typed, validated responses from agents using `response_format` or `with_structured_output()`.\n\n\u003Cpython>\n\n```python\nfrom langchain.agents import create_agent\nfrom pydantic import BaseModel, Field\n\nclass ContactInfo(BaseModel):\n    name: str\n    email: str\n    phone: str = Field(description=\"Phone number with area code\")\n\n# Option 1: Agent with structured output\nagent = create_agent(model=\"gpt-4.1\", tools=[search], response_format=ContactInfo)\nresult = agent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"Find contact for John\"}]})\nprint(result[\"structured_response\"])  # ContactInfo(name='John', ...)\n\n# Option 2: Model-level structured output (no agent needed)\nfrom langchain_openai import ChatOpenAI\nmodel = ChatOpenAI(model=\"gpt-4.1\")\nstructured_model = model.with_structured_output(ContactInfo)\nresponse = structured_model.invoke(\"Extract: John, john@example.com, 555-1234\")\n# ContactInfo(name='John', email='john@example.com', phone='555-1234')\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\n\n```typescript\nimport { ChatOpenAI } from \"@langchain\u002Fopenai\";\nimport { z } from \"zod\";\n\nconst ContactInfo = z.object({\n  name: z.string(),\n  email: z.string().email(),\n  phone: z.string().describe(\"Phone number with area code\"),\n});\n\n\u002F\u002F Model-level structured output\nconst model = new ChatOpenAI({ model: \"gpt-4.1\" });\nconst structuredModel = model.withStructuredOutput(ContactInfo);\nconst response = await structuredModel.invoke(\"Extract: John, john@example.com, 555-1234\");\n\u002F\u002F { name: 'John', email: 'john@example.com', phone: '555-1234' }\n```\n\u003C\u002Ftypescript>\n\u003C\u002Fstructured_output>\n\n\u003Cmodel_config>\n## Model Configuration\n\n`create_agent` accepts model strings (`\"anthropic:claude-sonnet-4-5\"`, `\"openai:gpt-4.1\"`) or model instances for custom settings:\n\n```python\nfrom langchain_anthropic import ChatAnthropic\nagent = create_agent(model=ChatAnthropic(model=\"claude-sonnet-4-5\", temperature=0), tools=[...])\n```\n\u003C\u002Fmodel_config>\n\n\n\u003Cfix-missing-tool-description>\n\u003Cpython>\nClear descriptions help the agent know when to use each tool.\n\n```python\n# WRONG: Vague or missing description\n@tool\ndef bad_tool(input: str) -> str:\n    \"\"\"Does stuff.\"\"\"\n    return \"result\"\n\n# CORRECT: Clear, specific description with Args\n@tool\ndef search(query: str) -> str:\n    \"\"\"Search the web for current information about a topic.\n\n    Use this when you need recent data or facts.\n\n    Args:\n        query: The search query (2-10 words recommended)\n    \"\"\"\n    return web_search(query)\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\nClear descriptions help the agent know when to use each tool.\n\n```typescript\n\u002F\u002F WRONG: Vague description\nconst badTool = tool(async ({ input }) => \"result\", {\n  name: \"bad_tool\",\n  description: \"Does stuff.\", \u002F\u002F Too vague!\n  schema: z.object({ input: z.string() }),\n});\n\n\u002F\u002F CORRECT: Clear, specific description\nconst search = tool(async ({ query }) => webSearch(query), {\n  name: \"search\",\n  description: \"Search the web for current information about a topic. Use this when you need recent data or facts.\",\n  schema: z.object({\n    query: z.string().describe(\"The search query (2-10 words recommended)\"),\n  }),\n});\n```\n\u003C\u002Ftypescript>\n\u003C\u002Ffix-missing-tool-description>\n\n\u003Cfix-no-checkpointer>\n\u003Cpython>\nAdd checkpointer and thread_id for conversation memory across invocations.\n\n```python\n# WRONG: No persistence - agent forgets between calls\nagent = create_agent(model=\"anthropic:claude-sonnet-4-5\", tools=[search])\nagent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"I'm Bob\"}]})\nagent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"What's my name?\"}]})\n# Agent doesn't remember!\n\n# CORRECT: Add checkpointer and thread_id\nfrom langgraph.checkpoint.memory import MemorySaver\n\nagent = create_agent(\n    model=\"anthropic:claude-sonnet-4-5\",\n    tools=[search],\n    checkpointer=MemorySaver(),\n)\nconfig = {\"configurable\": {\"thread_id\": \"session-1\"}}\nagent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"I'm Bob\"}]}, config=config)\nagent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"What's my name?\"}]}, config=config)\n# Agent remembers: \"Your name is Bob\"\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\nAdd checkpointer and thread_id for conversation memory across invocations.\n\n```typescript\n\u002F\u002F WRONG: No persistence\nconst agent = createAgent({ model: \"anthropic:claude-sonnet-4-5\", tools: [search] });\nawait agent.invoke({ messages: [{ role: \"user\", content: \"I'm Bob\" }] });\nawait agent.invoke({ messages: [{ role: \"user\", content: \"What's my name?\" }] });\n\u002F\u002F Agent doesn't remember!\n\n\u002F\u002F CORRECT: Add checkpointer and thread_id\nimport { MemorySaver } from \"@langchain\u002Flanggraph\";\n\nconst agent = createAgent({\n  model: \"anthropic:claude-sonnet-4-5\",\n  tools: [search],\n  checkpointer: new MemorySaver(),\n});\nconst config = { configurable: { thread_id: \"session-1\" } };\nawait agent.invoke({ messages: [{ role: \"user\", content: \"I'm Bob\" }] }, config);\nawait agent.invoke({ messages: [{ role: \"user\", content: \"What's my name?\" }] }, config);\n\u002F\u002F Agent remembers: \"Your name is Bob\"\n```\n\u003C\u002Ftypescript>\n\u003C\u002Ffix-no-checkpointer>\n\n\u003Cfix-infinite-loop>\n\u003Cpython>\nSet recursion_limit in the invoke config to prevent runaway agent loops.\n\n```python\n# WRONG: No iteration limit - could loop forever\nresult = agent.invoke({\"messages\": [(\"user\", \"Do research\")]})\n\n# CORRECT: Set recursion_limit in config\nresult = agent.invoke(\n    {\"messages\": [(\"user\", \"Do research\")]},\n    config={\"recursion_limit\": 10},  # Stop after 10 steps\n)\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\nSet recursionLimit in the invoke config to prevent runaway agent loops.\n\n```typescript\n\u002F\u002F WRONG: No iteration limit\nconst result = await agent.invoke({ messages: [[\"user\", \"Do research\"]] });\n\n\u002F\u002F CORRECT: Set recursionLimit in config\nconst result = await agent.invoke(\n  { messages: [[\"user\", \"Do research\"]] },\n  { recursionLimit: 10 }, \u002F\u002F Stop after 10 steps\n);\n```\n\u003C\u002Ftypescript>\n\u003C\u002Ffix-infinite-loop>\n\n\u003Cfix-accessing-result-wrong>\n\u003Cpython>\nAccess the messages array from the result, not result.content directly.\n\n```python\n# WRONG: Trying to access result.content directly\nresult = agent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"Hello\"}]})\nprint(result.content)  # AttributeError!\n\n# CORRECT: Access messages from result dict\nresult = agent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"Hello\"}]})\nprint(result[\"messages\"][-1].content)  # Last message content\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\nAccess the messages array from the result, not result.content directly.\n\n```typescript\n\u002F\u002F WRONG: Trying to access result.content directly\nconst result = await agent.invoke({ messages: [{ role: \"user\", content: \"Hello\" }] });\nconsole.log(result.content); \u002F\u002F undefined!\n\n\u002F\u002F CORRECT: Access messages from result object\nconst result = await agent.invoke({ messages: [{ role: \"user\", content: \"Hello\" }] });\nconsole.log(result.messages[result.messages.length - 1].content); \u002F\u002F Last message content\n```\n\u003C\u002Ftypescript>\n\u003C\u002Ffix-accessing-result-wrong>\n","\u003Coneliner>\nBuild production agents using `create_agent()`, middleware patterns, and the `@tool` decorator \u002F `tool()` function. When creating LangChain agents, you MUST use create_agent(), with middleware for custom flows. All other alternatives are outdated.\n\u003C\u002Foneliner>\n\n\u003Ccreate_agent>\n## Creating Agents with create_agent\n\n`create_agent()` is the recommended way to build agents. It handles the agent loop, tool execution, and state management.\n\n### Agent Configuration Options\n\n| Parameter | Purpose | Example |\n|-----------|---------|---------|\n| `model` | LLM to use | `\"anthropic:claude-sonnet-4-5\"` or model instance |\n| `tools` | List of tools | `[search, calculator]` |\n| `system_prompt` \u002F `systemPrompt` | Agent instructions | `\"You are a helpful assistant\"` |\n| `checkpointer` | State persistence | `MemorySaver()` |\n| `middleware` | Processing hooks | `[HumanInTheLoopMiddleware]` (Python) \u002F `[humanInTheLoopMiddleware({...})]` (TypeScript) |\n\u003C\u002Fcreate_agent>\n\n\u003Cex-basic-agent>\n\u003Cpython>\n\n```python\nfrom langchain.agents import create_agent\nfrom langchain_core.tools import tool\n\n@tool\ndef get_weather(location: str) -> str:\n    \"\"\"Get current weather for a location.\n\n    Args:\n        location: City name\n    \"\"\"\n    return f\"Weather in {location}: Sunny, 72F\"\n\nagent = create_agent(\n    model=\"anthropic:claude-sonnet-4-5\",\n    tools=[get_weather],\n    system_prompt=\"You are a helpful assistant.\"\n)\n\nresult = agent.invoke({\n    \"messages\": [{\"role\": \"user\", \"content\": \"What's the weather in Paris?\"}]\n})\nprint(result[\"messages\"][-1].content)\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\n\n```typescript\nimport { createAgent } from \"langchain\";\nimport { tool } from \"@langchain\u002Fcore\u002Ftools\";\nimport { z } from \"zod\";\n\nconst getWeather = tool(\n  async ({ location }) => `Weather in ${location}: Sunny, 72F`,\n  {\n    name: \"get_weather\",\n    description: \"Get current weather for a location.\",\n    schema: z.object({ location: z.string().describe(\"City name\") }),\n  }\n);\n\nconst agent = createAgent({\n  model: \"anthropic:claude-sonnet-4-5\",\n  tools: [getWeather],\n  systemPrompt: \"You are a helpful assistant.\",\n});\n\nconst result = await agent.invoke({\n  messages: [{ role: \"user\", content: \"What's the weather in Paris?\" }],\n});\nconsole.log(result.messages[result.messages.length - 1].content);\n```\n\u003C\u002Ftypescript>\n\u003C\u002Fex-basic-agent>\n\n\u003Cex-agent-with-persistence>\n\u003Cpython>\nAdd MemorySaver checkpointer to maintain conversation state across invocations.\n\n```python\nfrom langchain.agents import create_agent\nfrom langgraph.checkpoint.memory import MemorySaver\n\ncheckpointer = MemorySaver()\n\nagent = create_agent(\n    model=\"anthropic:claude-sonnet-4-5\",\n    tools=[search],\n    checkpointer=checkpointer,\n)\n\nconfig = {\"configurable\": {\"thread_id\": \"user-123\"}}\nagent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"My name is Alice\"}]}, config=config)\nresult = agent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"What's my name?\"}]}, config=config)\n# Agent remembers: \"Your name is Alice\"\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\nAdd MemorySaver checkpointer to maintain conversation state across invocations.\n\n```typescript\nimport { createAgent } from \"langchain\";\nimport { MemorySaver } from \"@langchain\u002Flanggraph\";\n\nconst checkpointer = new MemorySaver();\n\nconst agent = createAgent({\n  model: \"anthropic:claude-sonnet-4-5\",\n  tools: [search],\n  checkpointer,\n});\n\nconst config = { configurable: { thread_id: \"user-123\" } };\nawait agent.invoke({ messages: [{ role: \"user\", content: \"My name is Alice\" }] }, config);\nconst result = await agent.invoke({ messages: [{ role: \"user\", content: \"What's my name?\" }] }, config);\n\u002F\u002F Agent remembers: \"Your name is Alice\"\n```\n\u003C\u002Ftypescript>\n\u003C\u002Fex-agent-with-persistence>\n\n\u003Ctools>\n## Defining Tools\n\nTools are functions that agents can call. Use the `@tool` decorator (Python) or `tool()` function (TypeScript).\n\u003C\u002Ftools>\n\n\u003Cex-basic-tool>\n\u003Cpython>\n\n```python\nfrom langchain_core.tools import tool\n\n@tool\ndef add(a: float, b: float) -> float:\n    \"\"\"Add two numbers.\n\n    Args:\n        a: First number\n        b: Second number\n    \"\"\"\n    return a + b\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\n\n```typescript\nimport { tool } from \"@langchain\u002Fcore\u002Ftools\";\nimport { z } from \"zod\";\n\nconst add = tool(\n  async ({ a, b }) => a + b,\n  {\n    name: \"add\",\n    description: \"Add two numbers.\",\n    schema: z.object({\n      a: z.number().describe(\"First number\"),\n      b: z.number().describe(\"Second number\"),\n    }),\n  }\n);\n```\n\u003C\u002Ftypescript>\n\u003C\u002Fex-basic-tool>\n\n\u003Cmiddleware>\n## Middleware for Agent Control\n\nMiddleware intercepts the agent loop to add human approval, error handling, logging, and more. A deep understanding of middleware is essential for production agents — use `HumanInTheLoopMiddleware` (Python) \u002F `humanInTheLoopMiddleware` (TypeScript) for approval workflows, and `@wrap_tool_call` (Python) \u002F `createMiddleware` (TypeScript) for custom hooks.\n\nKey imports:\n\n```python\nfrom langchain.agents.middleware import HumanInTheLoopMiddleware, wrap_tool_call\n```\n\n```typescript\nimport { humanInTheLoopMiddleware, createMiddleware } from \"langchain\";\n```\n\nKey patterns:\n- **HITL**: `middleware=[HumanInTheLoopMiddleware(interrupt_on={\"dangerous_tool\": True})]` — requires `checkpointer` + `thread_id`\n- **Resume after interrupt**: `agent.invoke(Command(resume={\"decisions\": [{\"type\": \"approve\"}]}), config=config)`\n- **Custom middleware**: `@wrap_tool_call` decorator (Python) or `createMiddleware({ wrapToolCall: ... })` (TypeScript)\n\u003C\u002Fmiddleware>\n\n\u003Cstructured_output>\n## Structured Output\n\nGet typed, validated responses from agents using `response_format` or `with_structured_output()`.\n\n\u003Cpython>\n\n```python\nfrom langchain.agents import create_agent\nfrom pydantic import BaseModel, Field\n\nclass ContactInfo(BaseModel):\n    name: str\n    email: str\n    phone: str = Field(description=\"Phone number with area code\")\n\n# Option 1: Agent with structured output\nagent = create_agent(model=\"gpt-4.1\", tools=[search], response_format=ContactInfo)\nresult = agent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"Find contact for John\"}]})\nprint(result[\"structured_response\"])  # ContactInfo(name='John', ...)\n\n# Option 2: Model-level structured output (no agent needed)\nfrom langchain_openai import ChatOpenAI\nmodel = ChatOpenAI(model=\"gpt-4.1\")\nstructured_model = model.with_structured_output(ContactInfo)\nresponse = structured_model.invoke(\"Extract: John, john@example.com, 555-1234\")\n# ContactInfo(name='John', email='john@example.com', phone='555-1234')\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\n\n```typescript\nimport { ChatOpenAI } from \"@langchain\u002Fopenai\";\nimport { z } from \"zod\";\n\nconst ContactInfo = z.object({\n  name: z.string(),\n  email: z.string().email(),\n  phone: z.string().describe(\"Phone number with area code\"),\n});\n\n\u002F\u002F Model-level structured output\nconst model = new ChatOpenAI({ model: \"gpt-4.1\" });\nconst structuredModel = model.withStructuredOutput(ContactInfo);\nconst response = await structuredModel.invoke(\"Extract: John, john@example.com, 555-1234\");\n\u002F\u002F { name: 'John', email: 'john@example.com', phone: '555-1234' }\n```\n\u003C\u002Ftypescript>\n\u003C\u002Fstructured_output>\n\n\u003Cmodel_config>\n## Model Configuration\n\n`create_agent` accepts model strings (`\"anthropic:claude-sonnet-4-5\"`, `\"openai:gpt-4.1\"`) or model instances for custom settings:\n\n```python\nfrom langchain_anthropic import ChatAnthropic\nagent = create_agent(model=ChatAnthropic(model=\"claude-sonnet-4-5\", temperature=0), tools=[...])\n```\n\u003C\u002Fmodel_config>\n\n\n\u003Cfix-missing-tool-description>\n\u003Cpython>\nClear descriptions help the agent know when to use each tool.\n\n```python\n# WRONG: Vague or missing description\n@tool\ndef bad_tool(input: str) -> str:\n    \"\"\"Does stuff.\"\"\"\n    return \"result\"\n\n# CORRECT: Clear, specific description with Args\n@tool\ndef search(query: str) -> str:\n    \"\"\"Search the web for current information about a topic.\n\n    Use this when you need recent data or facts.\n\n    Args:\n        query: The search query (2-10 words recommended)\n    \"\"\"\n    return web_search(query)\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\nClear descriptions help the agent know when to use each tool.\n\n```typescript\n\u002F\u002F WRONG: Vague description\nconst badTool = tool(async ({ input }) => \"result\", {\n  name: \"bad_tool\",\n  description: \"Does stuff.\", \u002F\u002F Too vague!\n  schema: z.object({ input: z.string() }),\n});\n\n\u002F\u002F CORRECT: Clear, specific description\nconst search = tool(async ({ query }) => webSearch(query), {\n  name: \"search\",\n  description: \"Search the web for current information about a topic. Use this when you need recent data or facts.\",\n  schema: z.object({\n    query: z.string().describe(\"The search query (2-10 words recommended)\"),\n  }),\n});\n```\n\u003C\u002Ftypescript>\n\u003C\u002Ffix-missing-tool-description>\n\n\u003Cfix-no-checkpointer>\n\u003Cpython>\nAdd checkpointer and thread_id for conversation memory across invocations.\n\n```python\n# WRONG: No persistence - agent forgets between calls\nagent = create_agent(model=\"anthropic:claude-sonnet-4-5\", tools=[search])\nagent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"I'm Bob\"}]})\nagent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"What's my name?\"}]})\n# Agent doesn't remember!\n\n# CORRECT: Add checkpointer and thread_id\nfrom langgraph.checkpoint.memory import MemorySaver\n\nagent = create_agent(\n    model=\"anthropic:claude-sonnet-4-5\",\n    tools=[search],\n    checkpointer=MemorySaver(),\n)\nconfig = {\"configurable\": {\"thread_id\": \"session-1\"}}\nagent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"I'm Bob\"}]}, config=config)\nagent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"What's my name?\"}]}, config=config)\n# Agent remembers: \"Your name is Bob\"\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\nAdd checkpointer and thread_id for conversation memory across invocations.\n\n```typescript\n\u002F\u002F WRONG: No persistence\nconst agent = createAgent({ model: \"anthropic:claude-sonnet-4-5\", tools: [search] });\nawait agent.invoke({ messages: [{ role: \"user\", content: \"I'm Bob\" }] });\nawait agent.invoke({ messages: [{ role: \"user\", content: \"What's my name?\" }] });\n\u002F\u002F Agent doesn't remember!\n\n\u002F\u002F CORRECT: Add checkpointer and thread_id\nimport { MemorySaver } from \"@langchain\u002Flanggraph\";\n\nconst agent = createAgent({\n  model: \"anthropic:claude-sonnet-4-5\",\n  tools: [search],\n  checkpointer: new MemorySaver(),\n});\nconst config = { configurable: { thread_id: \"session-1\" } };\nawait agent.invoke({ messages: [{ role: \"user\", content: \"I'm Bob\" }] }, config);\nawait agent.invoke({ messages: [{ role: \"user\", content: \"What's my name?\" }] }, config);\n\u002F\u002F Agent remembers: \"Your name is Bob\"\n```\n\u003C\u002Ftypescript>\n\u003C\u002Ffix-no-checkpointer>\n\n\u003Cfix-infinite-loop>\n\u003Cpython>\nSet recursion_limit in the invoke config to prevent runaway agent loops.\n\n```python\n# WRONG: No iteration limit - could loop forever\nresult = agent.invoke({\"messages\": [(\"user\", \"Do research\")]})\n\n# CORRECT: Set recursion_limit in config\nresult = agent.invoke(\n    {\"messages\": [(\"user\", \"Do research\")]},\n    config={\"recursion_limit\": 10},  # Stop after 10 steps\n)\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\nSet recursionLimit in the invoke config to prevent runaway agent loops.\n\n```typescript\n\u002F\u002F WRONG: No iteration limit\nconst result = await agent.invoke({ messages: [[\"user\", \"Do research\"]] });\n\n\u002F\u002F CORRECT: Set recursionLimit in config\nconst result = await agent.invoke(\n  { messages: [[\"user\", \"Do research\"]] },\n  { recursionLimit: 10 }, \u002F\u002F Stop after 10 steps\n);\n```\n\u003C\u002Ftypescript>\n\u003C\u002Ffix-infinite-loop>\n\n\u003Cfix-accessing-result-wrong>\n\u003Cpython>\nAccess the messages array from the result, not result.content directly.\n\n```python\n# WRONG: Trying to access result.content directly\nresult = agent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"Hello\"}]})\nprint(result.content)  # AttributeError!\n\n# CORRECT: Access messages from result dict\nresult = agent.invoke({\"messages\": [{\"role\": \"user\", \"content\": \"Hello\"}]})\nprint(result[\"messages\"][-1].content)  # Last message content\n```\n\u003C\u002Fpython>\n\u003Ctypescript>\nAccess the messages array from the result, not result.content directly.\n\n```typescript\n\u002F\u002F WRONG: Trying to access result.content directly\nconst result = await agent.invoke({ messages: [{ role: \"user\", content: \"Hello\" }] });\nconsole.log(result.content); \u002F\u002F undefined!\n\n\u002F\u002F CORRECT: Access messages from result object\nconst result = await agent.invoke({ messages: [{ role: \"user\", content: \"Hello\" }] });\nconsole.log(result.messages[result.messages.length - 1].content); \u002F\u002F Last message content\n```\n\u003C\u002Ftypescript>\n\u003C\u002Ffix-accessing-result-wrong>\n",{"name":5,"description":7},"main","c9d35c0e379f9b59b3807abb9a04d98437ffbffa",".agents\u002Fskills\u002Flangchain_skills\u002Flangchain-fundamentals",2,"https:\u002F\u002Fgithub.com\u002Fydf0509\u002Flc-agent","https:\u002F\u002Fgithub.com\u002Fydf0509","研究oop编程思想","2026-11-05 17:49:50",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add ydf0509\u002Flc-agent --skill langchain-fundamentals",{"tool":37,"command":38},"bunx","bunx skills add ydf0509\u002Flc-agent --skill langchain-fundamentals",{"tool":40,"command":41},"pnpm","pnpm dlx skills add ydf0509\u002Flc-agent --skill langchain-fundamentals","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fydf0509\u002Flc-agent\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Flangchain_skills\u002Flangchain-fundamentals\u002FSKILL.md",true,[],[46,52,59,66,73,80],{"skillNo":47,"name":48,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":49,"categories":50,"keywords":51,"publishedAt":18},"01M75M719FJ3D75G010QKKGS9P","vision-bridge","https:\u002F\u002Fgithub.com\u002Fydf0509\u002Flc-agent\u002Fblob\u002Fmain\u002Flc_agent\u002Fskills\u002Fthird_party_skills\u002Fvision-bridge\u002FSKILL.md",[],[],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":18},"01M75M6WQ4JP3HHP635A4VA6XE","writing-skills","Use when creating new skills, editing existing skills, or verifying skills work before deployment","https:\u002F\u002Fgithub.com\u002Fydf0509\u002Flc-agent\u002Fblob\u002Fmain\u002Flc_agent\u002Fskills\u002Fthird_party_skills\u002Fsuperpowers\u002Fwriting-skills\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":18},"01M75M6SNFFXN1WM46XAJTZM2B","writing-plans","Use when you have a spec or requirements for a multi-step task, before touching code","https:\u002F\u002Fgithub.com\u002Fydf0509\u002Flc-agent\u002Fblob\u002Fmain\u002Flc_agent\u002Fskills\u002Fthird_party_skills\u002Fsuperpowers\u002Fwriting-plans\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":18},"01M75M6PR8M5KYVWT4XJGMY9Y9","verification-before-completion","Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always","https:\u002F\u002Fgithub.com\u002Fydf0509\u002Flc-agent\u002Fblob\u002Fmain\u002Flc_agent\u002Fskills\u002Fthird_party_skills\u002Fsuperpowers\u002Fverification-before-completion\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M75M6KQX25K40ZP204NFF89K","using-superpowers","Use when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions","https:\u002F\u002Fgithub.com\u002Fydf0509\u002Flc-agent\u002Fblob\u002Fmain\u002Flc_agent\u002Fskills\u002Fthird_party_skills\u002Fsuperpowers\u002Fusing-superpowers\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":18},"01M75M6FYAG0D8EP8WXYNMVKQM","using-git-worktrees","Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback","https:\u002F\u002Fgithub.com\u002Fydf0509\u002Flc-agent\u002Fblob\u002Fmain\u002Flc_agent\u002Fskills\u002Fthird_party_skills\u002Fsuperpowers\u002Fusing-git-worktrees\u002FSKILL.md",[],[]]