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

推荐订阅源

博客园_首页
B
Blog RSS Feed
Microsoft Azure Blog
Microsoft Azure Blog
J
Java Code Geeks
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Google DeepMind News
Google DeepMind News
F
Fortinet All Blogs
V
V2EX
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Engineering at Meta
Engineering at Meta
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
M
MIT News - Artificial intelligence
IT之家
IT之家
博客园 - 【当耐特】
U
Unit 42
云风的 BLOG
云风的 BLOG
L
LangChain Blog
小众软件
小众软件
Microsoft Security Blog
Microsoft Security Blog
B
Blog
H
Hackread – Cybersecurity News, Data Breaches, AI and More
宝玉的分享
宝玉的分享
N
Netflix TechBlog - Medium

LangChain Forum - Topics tagged python-help

Llama-server process has terminated: invalid argument --load-mode with Ollama client 0.32.6 and langchain-ollama 1.1.0 Langchain Certified Agent Engineer Exam - Exam link not received and no response 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
With too many fields, how should deepagents handle this p...
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.