惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
N
Netflix TechBlog - Medium
博客园 - 叶小钗
大猫的无限游戏
大猫的无限游戏
S
SegmentFault 最新的问题
V
V2EX
IT之家
IT之家
J
Java Code Geeks
Hacker News - Newest:
Hacker News - Newest: "LLM"
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
GbyAI
GbyAI
D
Docker
S
Secure Thoughts
Recent Announcements
Recent Announcements
Webroot Blog
Webroot Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
云风的 BLOG
云风的 BLOG
博客园_首页
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Security Archives - TechRepublic
Security Archives - TechRepublic
酷 壳 – CoolShell
酷 壳 – CoolShell
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
N
News | PayPal Newsroom
S
Security @ Cisco Blogs
I
InfoQ
Last Week in AI
Last Week in AI
SecWiki News
SecWiki News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
W
WeLiveSecurity
T
Troy Hunt's Blog
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Attack and Defense Labs
Attack and Defense Labs
美团技术团队
T
The Blog of Author Tim Ferriss
Google DeepMind News
Google DeepMind News
Martin Fowler
Martin Fowler
B
Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Scott Helme
Scott Helme
T
Tor Project blog
Know Your Adversary
Know Your Adversary
有赞技术团队
有赞技术团队
Hugging Face - Blog
Hugging Face - Blog
Recorded Future
Recorded Future
C
Cyber Attacks, Cyber Crime and Cyber Security
AI
AI
G
Google Developers Blog

LangChain Forum - Topics tagged python-help

Null-drift: A bare-metal O(1) Memory Store for continuous LangGraph agents Clarification needed: Assistant config vs context and graph initialization Proposal: a small local helper for readable run traces via PR Proxy Authentication Required 407 What is the right way to dynamically create and run a graph? Re-Implement claude code's dynamic workflow using langchian & deepagents How to define a correct state for multi-agent system Response Format Groq Model Pydantic I hope to get some recommendations for practical skills Interrupt does not work correctly in LangGraph The Qwen3.6b model in fireworks through initchatmodel reporting hugely inflated tokens For parallel execution in Node, should i use the functional API? Potential Enhancement: Django-Managed PostgresSaver Pre-interrupt() code re-runs on resume — anti-pattern, or is there a sanctioned way to detect resume? Interrupt parallel branch execution Best practices for self-hosting LangGraph Server OSS without LangGraph keys Dynamically Enabling/Disabling Graphs in a LangGraph Server at Runtime LangGraph thread copy can take 12+ minutes: recommended production pattern? Will DeltaChannel be the default for AgentState.messages, or expected to stay opt-in? Proposal: additional docs for implementing custom DB checkpointers or a guide on generic base checkpointer Prompt_cache_retention: '24h' supported in langchain agents and where to provide it, inside invoke or while creating client? Could RAG pipelines realistically cause deployment timeouts, is Render suitable for first-time RAG deployments? How do I use langchain_postgres' init_vectorstore_table correctly? Proposal: Graph-wide default error handler for StateGraph (fallback for nodes without error_handler) Support timedelta for CachePolicy.ttl, consistent with TimeoutPolicy Anyone confirms this issue that deepagent ui streaming is disturb by update in deepagent or bug issue Best Stack for Building AI Applications Seeking help regarding the connection between Websocket and tool calls Tool invocation error with empty error message when using `InjectedState` + `Command` return in async tool How to use @langchain/react Built llmsessioncontract on AgentMiddleware: runtime enforcement of tool-call protocols — feedback wanted Improving citation accuracy and reducing hallucinations in custom Parent-Child RAG pipeline (Gemma3:4B + FAISS+BM25 + Cross-encoder reranker) Built a live autonomous AI agent network using LangGraph-style economics — looking for feedback How to use tool calling using ChatLlamaCpp and Gemma 4 E4B with create_agent? The Docs says open router can be used with init_chat_model but throws an error Interested to contribute to langgraph postgre checkpointer for multiple adapter support SSL certificate error from httpx with LangGraph server [Feature Request] Wire allowed_msgpack_modules in langgraph.json Serving an agent with the LangGraph CLI dev command Proposal: implement delete_for_runs for SQLite checkpoint savers WikipediaLoader endup in JSONDecodeError Human-in-the-loop approval dashboard for LangGraph agents — open source, free to deploy Should interrupt() be split into two primitives — one for human input, one for s2s data fetching? Feature Request: Driver abstraction for checkpoint-postgres: to build support for asyncpg and other adapters .Interested to contribute to langgraph (python) Feature Request: @task metadata How should I provide an agent to a LangGraph server? Parallel astream() on the same compiled graph leaks messages between streams Where should I define the name and description for subagents? Add Qdrant-backed checkpoint saver and memory store (langgraph-checkpoint-qdrant) The output content has been corrupted Feature Request: Simple cryptographic provenance for who authorized what in LangGraph multi-agent graphs LangGraph + PostgreSQL: Chat history and summarization best practice Using SQLRecordManager multi-agent systems debugging agent-to-agent Proposal: Add save_local and load_local to USearch VectorStore (Feature Parity with FAISS) Tiny LangGraph -> Assay evidence sample from tasks v2 Help with local RAG pipeline – poor retrieval quality, wrong page numbers LOGIC.md — declarative reasoning contracts that compile to LangGraph StateGraph Distinguishing internal vs final streamed chunks in Supervisor multi-agent architecture Are people hitting race conditions in multi-agent LangChain setups? How do ContextEditingMiddleware and SummarizationMiddleware interact when used together?Combining ContextEditingMiddleware + SummarizationMiddleware — execution order and behavior when both trigger? How to register type in langgraph Are there any frontends for interacting with a LangGraph agent? Langchain.schema is not available while using in python code In-place model update on a compiled create_agent and per-subagent model update for deep agents - is this possible? Feature Request: Native Support for A2A Protocol (Remote Agents as Sub-Graphs) Feature Request: Image Input support for ChatMistralAI Multiple response formats when creating agents? Unable to parse docstring from OpenAI schema Hosting an agent server on Heroku No cost displayed in LangSmith when using LiteLLM + LangGraph How should I deploy a self-hosted multi-agent system? New integration: langchain-w2a — LangChain tools for W2A-enabled websites LiteLLM Router in LangChain: Missing Model Name and Cost in LangSmith Traces Bogus warning messages after upgrading dependencies which could have security impact if not addressed `anyio.CancelScope(shield=True)` not working inside langgraph node Handling Non-PDF File Attachments in LangChain HumanMessage How are teams handling evals when agent pipelines span multiple LangSmith projects? Feature request: Configurable PostgreSQL schema for langgraph-checkpoint-postgres (parity with LangGraphJS) Using the useStream frontend API with custom FastAPI backend Qwen 3.5 tool calling How to propagate cancellation across multi-level LangGraph agents When to use config['configurable'] vs. context in graph nodes? Tool.func typing [DashScope] reasoning parameter on ChatOpenAI breaks subagent tool calling — use separate models as workaround Structured data fields (1000+): Dedicated LLM channel vs vectorized field names? PollerCompletionQueue._handle_events BlockingIOError spam in LangGraph Cloud logs Parallel Nodes: how to manage failures or exceptions [LangSmith Studio Issue] when resuming from an interrupt inside a subgraph. it doesn't properly resume, instead restarts Guarding tool calls against prompt injection / exfiltration Feature Discussion: Opt-In Recursive Long-Context Executor for LangGraph Persisting HITL payloads Multi-Agent Architecture Are dynamic tool lists allowed when using create_agent? Langgraph RemoteGraph How to make an image tool?
With too many fields, how should deepagents handle this properly?
2026-03-19 · via LangChain Forum - Topics tagged python-help

Hello @yech
Great question, and your instincts are mostly right. Let me break this down clearly for you.


The Core Mental Shift: Tools Are Your Interface

When you were using the raw OpenAI SDK, you were assembling context manually, you controlled what went into the message list. With DeepAgents (which sits on top of LangGraph/LangChain), that control moves into tools. The agent calls your tools, and whatever you return from a tool becomes part of the context automatically. So instead of thinking “how do I arrange the context?”, think “how do I design my tools to return exactly the right data?”.


Designing Your Two Tools

You’ve correctly identified that you need two separate tools. Here’s how to think about them:

Tool 1 — General/Fuzzy Company Info

This takes a free-form query and returns narrative information. No strict field validation needed.

from langchain_core.tools import tool

@tool
def get_company_overview(query: str) -> str:
    """Return general background information about Huawei Technologies Co., Ltd.

    Use this when the user asks broad, open-ended questions about the company
    (history, products, size, culture, etc.).

    Args:
        query: The user's free-form question about the company.
    """
    # Call your data source / RAG pipeline / API here
    return fetch_narrative_info(query)

Tool 2 — Precise Structured Fields (with validation)

This is where your design question lives. The parameter is a list[str] and the tool itself handles validation before doing anything expensive.

from langchain_core.tools import tool
from pydantic import BaseModel, field_validator

# These are your canonical field names — the source of truth
KNOWN_FIELDS: dict[str, str] = {
    "website":        "Official website URL",
    "headquarters":   "Headquarters location",
    "founded":        "Year founded",
    "ceo":            "Current CEO name",
    "employees":      "Approximate number of employees",
    "revenue":        "Latest annual revenue",
    "stock_ticker":   "Stock exchange and ticker symbol",
    "phone":          "Main contact phone number",
}

class CompanyFieldsInput(BaseModel):
    fields: list[str]

    @field_validator("fields")
    @classmethod
    def normalize_fields(cls, raw_fields: list[str]) -> list[str]:
        resolved = []
        for f in raw_fields:
            match = resolve_field(f)   # your semantic matching function
            if match:
                resolved.append(match)
        return resolved

@tool(args_schema=CompanyFieldsInput)
def get_company_fields(fields: list[str]) -> dict[str, str]:
    """Fetch specific, structured data fields for Huawei Technologies Co., Ltd.

    Use this when the user asks for one or more specific pieces of data
    (e.g., website, CEO, revenue). Returns only the fields that exist.

    Args:
        fields: List of field names the user wants (e.g., ["website", "ceo"]).
    """
    results = {}
    for field in fields:
        results[field] = fetch_field_from_source(field)
    return results

The Semantic Field Validation — Your Key Concern

This is the part where you prevent the model from hallucinating field names and passing garbage into your data layer. Here’s a clean pattern using LangChain embeddings:

from langchain_openai import OpenAIEmbeddings
from langchain_core.vectorstores import InMemoryVectorStore
from langchain_core.documents import Document

# Build a small in-memory vector store of your known fields at startup
_embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
_field_store = InMemoryVectorStore.from_documents(
    documents=[
        Document(page_content=f"{name}: {desc}", metadata={"field": name})
        for name, desc in KNOWN_FIELDS.items()
    ],
    embedding=_embeddings,
)

def resolve_field(user_field: str, threshold: float = 0.75) -> str | None:
    """Map a user-supplied field name to a canonical field name.

    Returns the canonical name if a confident match is found, else None.

    Args:
        user_field: Raw field name as provided by the user or LLM.
        threshold: Minimum cosine similarity score to accept a match.
    """
    results = _field_store.similarity_search_with_score(user_field, k=1)
    if not results:
        return None
    doc, score = results[0]
    if score >= threshold:
        return doc.metadata["field"]
    return None

If you don’t want to use embeddings (e.g., for lower latency), a lightweight alternative is rapidfuzz:

from rapidfuzz import process, fuzz

def resolve_field(user_field: str, threshold: int = 70) -> str | None:
    match, score, _ = process.extractOne(
        user_field,
        KNOWN_FIELDS.keys(),
        scorer=fuzz.WRatio
    )
    return match if score >= threshold else None

Putting It All Together With DeepAgents

from deepagents import create_deep_agent

agent = create_deep_agent(
    model="openai:gpt-4o",
    tools=[get_company_overview, get_company_fields],
    system_prompt=(
        "You are a Huawei Technologies research assistant. "
        "For broad questions use get_company_overview. "
        "For specific data points (website, CEO, revenue, etc.) use get_company_fields. "
        "You may call both in the same response if the user wants both."
    ),
)

result = agent.invoke({
    "messages": [{
        "role": "user",
        "content": "Tell me about Huawei, and also give me their website and CEO."
    }]
})

The agent will naturally decide to call both tools when the user asks for both general info and specific fields, because that’s exactly what the tool descriptions guide it to do.


Addressing Your “Context Assembly” Concern Directly

You mentioned you used to arrange results yourself with the raw OpenAI SDK. In DeepAgents, you get equivalent control through two mechanisms:

  1. Tool return values — Whatever your tool returns (string, dict, list) is serialized into a ToolMessage and injected into the conversation context. You control the shape of that data entirely inside the tool function.

  2. response_format for structured final output — If you need the agent’s final answer to follow a strict schema (not just intermediate tool results), use the response_format parameter:

from pydantic import BaseModel
from langchain.agents.structured_output import ResponseFormat

class HuaweiReport(BaseModel):
    summary: str
    fields: dict[str, str]
    missing_fields: list[str]

agent = create_deep_agent(
    model="openai:gpt-4o",
    tools=[get_company_overview, get_company_fields],
    response_format=ResponseFormat(schema=HuaweiReport),
)

Summary

Concern Solution in DeepAgents
Two separate interfaces Two @tool functions with clear descriptions
List of fields as input args_schema=CompanyFieldsInput with Pydantic
Validate fields before querying resolve_field() inside the tool (embeddings or fuzzy match)
Control what goes into context Control what the tool returns
Structured final output response_format=ResponseFormat(schema=YourModel)
User asks for both Agent calls both tools naturally based on tool descriptions

Your original thinking was sound, the key realization is that the tool function is the right place to put your validation and normalization logic, not in a separate pre-processing step outside the agent. This keeps the agent’s interface clean while protecting your data layer from bad inputs.