第 4 章 Agent 背后的模型:能力与优化
Supervisor Agent 团队
关于本 notebook
这个 notebook 用 LangGraph 和 LangChain 构建了一个分层、基于团队的 agent 系统,它可以在网上做研究、抓取网页、搜索专利、运行代码,并协作把报告写入磁盘。它演示了如何在顶层 supervisor 之下组合多个子图,同时让工具、角色和 state 保持清晰明确。
它展示了什么
两个专职团队,由 supervisor 协调
- 研究团队(Research team),负责搜索、抓取、Exa 语义搜索和 Google Patents 专利检索
- 文档写作团队(Document writing team),负责创建大纲、读写文档、编辑,以及用 Python REPL 绘制简单图表
顶层编排器(orchestrator),负责在两个团队之间路由任务并汇总结果
工具组合:Tavily、SerpAPI、Exa、WebBaseLoader 抓取和 Python REPL
文件持久化:在工作目录中保存大纲和最终报告
流式运行,逐步打印更新,并为每个团队和 supervisor 图生成 Mermaid PNG 图预览
你将运行什么
定义研究工具
tavily_tool用于搜索结果scrape_webpages用于抓取并拼接页面内容patent_search通过 SerpAPI Google Patents 搜索专利exa_search_tool用于带高亮片段的神经搜索
定义文档工具
create_outline、read_document、write_document、edit_document,运行在沙箱工作目录中python_repl_tool用于快速计算或输出到 stdout 的图表
使用
create_react_agent构建 worker 节点,以及带有结构化路由的 LLM supervisor,后者会选择下一个 worker 或结束任务。编译三个图
research_graph用于网络研究和专利检索paper_writing_graph用于写大纲和写文档,可选用图表生成super_graph端到端地编排两个团队
执行一个示例
- 向研究团队询问 AI agents 和专利
- 让写作团队把一首诗写入磁盘
- 运行一个完整任务,生成 800 字的半导体白皮书,包含专利链接和来源,并保存到
semiconductor_whitepaper.txt
工作原理
- Supervisor:使用结构化输出的小型 LLM 路由器,从固定的集合中选择下一个 worker,或返回 FINISH。
- Worker:绑定特定工具集和 prompt 的 ReAct 风格 agent。每个 worker 返回一条简洁的消息,反馈给 supervisor。
- State:使用
MessagesState加上一个简单的next字段。消息在团队之间流动,这样顶层 supervisor 就能进行协调。 - 路由:通过
Command(goto=..., update=...)实现,在节点之间移动的同时把结果追加到 state。 - 持久化:文件工具在
WORKING_DIRECTORY下读写。最终任务把完整报告写入磁盘。
为什么用这个模式
- 清晰的关注点分离让行为可预测、可测试。
- Supervisor 让控制流保持明确、可审计。
- 每个 worker 的 tool 使用范围是受限的,这减少了 prompt 膨胀并提高了可靠性。
- 顶层图在组合团队时不会耦合它们内部的实现细节。
扩展与适配
- 在研究环节和写作环节之间加入一个引用校验器。
- 替换或添加搜索服务提供商。
- 用沙箱化的执行器替换 Python REPL。
- 使用 LangSmith 持久化 checkpoints 和 traces,用于调试和评估。
要求与注意事项
- 必需的密钥:
OPENAI_API_KEY、TAVILY_API_KEY、SERPAPI_API_KEY、EXA_API_KEY。 - 网页结果和专利列表会随时间变化,每次运行的输出可能不同。
- 文件系统工具会写入工作目录。对不可信的内容请使用沙箱,或在 Docker 环境中使用。
- 流式输出会打印中间更新,帮助你追踪决策过程和 tool calls。
%%capture --no-stderr
%pip install -U langgraph langchain_community langchain_openai langchain-tavily langchain_experimental python-dotenv exa_py==1.16.1# Imports for API
from dotenv import load_dotenv
import os
load_dotenv()
NEBIUS_API_KEY = os.getenv('NEBIUS_API_KEY')
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY")
serp_api_key = os.getenv("SERPAPI_API_KEY")
SERPER_API_KEY = os.getenv("SERPER_API_KEY")
exa_api_key = os.getenv("EXA_API_KEY")!pip install tavily-python为 LangGraph 开发设置 LangSmith
注册 LangSmith,可以快速发现问题并改进 LangGraph 项目的性能。LangSmith 让你使用 trace 数据来调试、测试和监控用 LangGraph 构建的 LLM 应用——点击这里了解更多入门信息。
创建工具
每个团队由一个或多个 agent 组成,每个 agent 有一个或多个工具。下面定义你的各个团队将要使用的所有工具。
我们先从研究团队开始。
ResearchTeam 工具
研究团队可以使用搜索引擎和 URL 抓取器在网上查找信息。欢迎在下面添加额外功能来提升团队性能!
from typing import Annotated, List
from langchain_community.document_loaders import WebBaseLoader
from langchain_tavily import TavilySearch
from langchain_core.tools import toolWARNING:langchain_community.utils.user_agent:USER_AGENT environment variable not set, consider setting it to identify your requests.import os
import datetime
from typing import Dict, Any
from langchain_openai import ChatOpenAI
from langchain_tavily import TavilySearch, TavilyExtract
from langgraph.graph import StateGraph, START, END
from langgraph.graph.message import add_messages
from langgraph.types import StreamWriter
from langgraph.prebuilt import ToolNode
from langchain_core.messages import HumanMessage, AIMessage文档写作团队工具
接下来,我们给文档写作团队一些工具。 下面定义了一些最基本的文件访问工具。
注意,这会让 agent 访问你的文件系统,可能不安全。我们也没有针对性能优化工具描述。
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Dict, Optional
from typing_extensions import TypedDict
from langchain_community.tools.tavily_search import TavilySearchResults
from typing import Annotated, List
from langchain_community.document_loaders import WebBaseLoader
from langchain_tavily import TavilySearch
from langchain_core.tools import tool
# Define a persistent working directory
WORKING_DIRECTORY = Path("/content/working_directory")
# Ensure the working directory exists
if not WORKING_DIRECTORY.exists():
WORKING_DIRECTORY.mkdir(parents=True)
print(f"Created working directory: {WORKING_DIRECTORY}")
else:
print(f"Working directory already exists: {WORKING_DIRECTORY}")
from langchain_community.utilities import SerpAPIWrapper
from exa_py import Exa
import json
from typing import List
import re
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel
from langchain_core.tools import tool
from typing import List
# --- Load the Encoder Model (The Analyst's "Brain") ---
# This is done once at the start.
try:
print("Loading Analyst (ModernBERT) model...")
device = "cuda" if torch.cuda.is_available() else "cpu"
# Using the exact model you provided
tok = AutoTokenizer.from_pretrained("answerdotai/ModernBERT-base", use_fast=True)
enc = AutoModel.from_pretrained("answerdotai/ModernBERT-base", trust_remote_code=True).eval().to(device)
print(f"Analyst (ModernBERT) loaded successfully on {device}.")
except Exception as e:
print(f"Warning: Could not load ModernBERT. Analyst will not work. Error: {e}")
# Define dummy objects so the rest of the code doesn't crash
tok, enc, device = None, None, "cpu"
def _sent_split(text):
"""A simple, fast sentence splitter"""
return [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if len(s.strip()) > 0]
@tool("semantic_filter_tool")
def semantic_filter_tool(query: str, documents: List[str], k: int = 10) -> str:
"""
The Analyst's tool. Uses ModernBERT (an encoder model) to perform
extractive summarization. It finds the top 'k' most relevant sentences
from a list of documents that match a specific query.
"""
if not enc:
return "Error: ModernBERT model is not loaded."
print(f"--- 🕵️ Analyst (ModernBERT) processing {len(documents)} docs... ---")
# 1. Create a bank of sentences with provenance
bank, provenance = [], []
for i, doc_text in enumerate(documents):
for s in _sent_split(doc_text):
bank.append(s)
provenance.append(f"Source Doc [{i}]") # Keep track of where it came from
if not bank:
return "No text found in documents."
# 2. Encode query + all sentences in the bank
batch = [query] + bank
inputs = tok(batch, padding=True, truncation=True, max_length=512, return_tensors="pt").to(device)
with torch.no_grad():
H = enc(**inputs).last_hidden_state
attn = inputs["attention_mask"].unsqueeze(-1)
# Mean-pool to get sentence embeddings
emb = (H * attn).sum(dim=1) / attn.sum(dim=1)
q = emb[0] # Query embedding
S = emb[1:] # Sentence embeddings
# 3. Score sentences based on query similarity
score = F.cosine_similarity(S, q.unsqueeze(0)).flatten()
# 4. Pick the top k
top_k_indices = torch.topk(score, k=min(k, len(bank))).indices
# 5. Format the output
results = []
for idx in top_k_indices:
i = idx.item()
results.append({
"text": bank[i],
"source": provenance[i],
"score": round(score[i].item(), 4)
})
return json.dumps(results, indent=2)
tavily_search = TavilySearch(
max_results=10,
topic="general",
search_depth="basic",
)
tavily_extract = TavilyExtract(
extract_depth="advanced",
include_images=False,
)
@tool
def scrape_webpages(urls: List[str]) -> str:
"""Use requests and bs4 to scrape the provided web pages for detailed information."""
loader = WebBaseLoader(urls)
docs = loader.load()
return "\n\n".join(
[
f'\n{doc.page_content}\n '
for doc in docs
]
)
from langchain_community.utilities import GoogleSerperAPIWrapper
_serper = GoogleSerperAPIWrapper(type="search", hl="en", gl="us", tbs="qdr:y")
@tool("patent_search")
def patent_search(topic: str, max_items: int = 10) -> str:
"""
Past-year Google Patents hits via Serper. Returns JSON with title, link, date, snippet.
"""
q = f'site:patents.google.com ("{topic}")'
res = _serper.results(q)
organics = res.get("organic", [])
hits = [
{
"title": o.get("title",""),
"link": o.get("link",""),
"date": o.get("date") or o.get("publishedDate") or o.get("publishedTime"),
"snippet": o.get("snippet",""),
}
for o in organics if "patents.google.com" in o.get("link","")
][:max_items]
if not hits:
return "No recent Google Patents results found."
return json.dumps(hits, indent=2)
@tool("exa_search_tool")
def exa_search_tool(question: str) -> str:
"""Tool using Exa's Python SDK to run semantic search and return result highlights."""
exa = Exa(exa_api_key)
response = exa.search_and_contents(
question,
type="neural",
use_autoprompt=True,
num_results=5,
highlights=True
)
results = []
for idx, eachResult in enumerate(response.results):
result = {
"Title": eachResult.title,
"URL": eachResult.url,
"Highlight": "".join(eachResult.highlights)
}
results.append(result)
return json.dumps(results)
@tool
def create_outline(
points: Annotated[List[str], "List of main points or sections."],
file_name: Annotated[str, "File path to save the outline."],
) -> Annotated[str, "Path of the saved outline file."]:
"""Create and save an outline."""
with (WORKING_DIRECTORY / file_name).open("w") as file:
for i, point in enumerate(points):
file.write(f"{i + 1}. {point}\n")
return f"Outline saved to {file_name}"
@tool
def read_document(
file_name: Annotated[str, "File path to read the document from."],
start: Annotated[Optional[int], "The start line. Default is 0"] = None,
end: Annotated[Optional[int], "The end line. Default is None"] = None,
) -> str:
"""Read the specified document."""
with (WORKING_DIRECTORY / file_name).open("r") as file:
lines = file.readlines()
if start is None:
start = 0
return "\n".join(lines[start:end])
@tool
def write_document(
content: Annotated[str, "Text content to be written into the document."],
file_name: Annotated[str, "File path to save the document."],
) -> Annotated[str, "Path of the saved document file."]:
"""Create and save a text document."""
with (WORKING_DIRECTORY / file_name).open("w") as file:
file.write(content)
return f"Document saved to {file_name}"
@tool
def edit_document(
file_name: Annotated[str, "Path of the document to be edited."],
inserts: Annotated[
Dict[int, str],
"Dictionary where key is the line number (1-indexed) and value is the text to be inserted at that line.",
],
) -> Annotated[str, "Path of the edited document file."]:
"""Edit a document by inserting text at specific line numbers."""
with (WORKING_DIRECTORY / file_name).open("r") as file:
lines = file.readlines()
sorted_inserts = sorted(inserts.items())
for line_number, text in sorted_inserts:
if 1 <= line_number <= len(lines) + 1:
lines.insert(line_number - 1, text + "\n")
else:
return f"Error: Line number {line_number} is out of range."
with (WORKING_DIRECTORY / file_name).open("w") as file:
file.writelines(lines)
return f"Document edited and saved to {file_name}"Working directory already exists: /content/working_directory
Loading Analyst (ModernBERT) model...
Analyst (ModernBERT) loaded successfully on cuda.辅助工具函数
我们将创建几个工具函数,以便在需要时让代码更简洁:
- 创建一个 worker agent。
- 为子图创建一个 supervisor。
这些函数会简化最后的图组合代码,让我们更容易看清整体逻辑。
from typing import List, Optional, Literal
from langchain_core.language_models.chat_models import BaseChatModel
import operator
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.types import Command
from langchain_core.messages import HumanMessage, trim_messages
from langchain_core.messages import BaseMessage
class State(MessagesState):
# This tracks the team's conversation internally
messages: Annotated[List[BaseMessage], operator.add]
# This provides each worker with context on the others' skill sets
members: str
# This is how the supervisor tells langgraph who has to work next
next: str
# This tracks the shared directory state
current_files: str
def make_supervisor_node(llm: BaseChatModel, members: list[str]) -> str:
options = ["FINISH"] + members
system_prompt = (
"You are the Thinker, a supervisor.\n"
"you have the following team members: {members}"
"Default order: search -> exa_search -> patent_research -> analyst -> note_taker -> doc_writer -> FINISH.\n"
"Only send the analyst after at least one research worker returned content.\n"
"When finished, write key findings to file via doc_writer. Cite sources."
)
class Router(TypedDict):
"""Worker to route to next. If no workers needed, route to FINISH."""
next: Literal[*options]
def supervisor_node(state: State) -> Command[Literal[*members, "__end__"]]:
"""An LLM-based router."""
messages = [
{"role": "system", "content": system_prompt},
] + state["messages"]
response = llm.with_structured_output(Router).invoke(messages)
goto = response["next"]
if goto == "FINISH":
goto = END
return Command(goto=goto, update={"next": goto})
return supervisor_nodefrom __future__ import annotations
from typing import Any, Dict, Literal, Sequence
from langchain_core.messages import BaseMessage, HumanMessage
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from langgraph.types import Command
def make_react_worker_node(
*,
llm: ChatOpenAI,
name: str,
tools: list,
prompt: str | None = None,
goto: str = "supervisor",
):
agent = create_react_agent(llm, tools=tools, prompt=prompt)
def node(state: State) -> Command[Literal["supervisor"]]:
result: Dict[str, Any] = agent.invoke(state)
msgs: Sequence[BaseMessage] = result.get("messages", [])
content = getattr(msgs[-1], "content", "") if msgs else ""
return Command(
update={"messages": [HumanMessage(content=content, name=name)]},
goto=goto,
)
return node定义 Agent 团队
现在我们可以来定义分层团队了。"选择你的玩家吧!"
研究团队
研究团队将有一个搜索 agent 和一个网页抓取型的 "research_agent" 作为两个 worker 节点。让我们创建它们,以及团队 supervisor。
既然我们已经创建了必要的组件,定义它们的交互就很简单了。把节点添加到团队图中,并定义决定转移条件的边。
fast_llm = ChatOpenAI(
model="Qwen/Qwen3-32B-fast",
temperature=0,
api_key=NEBIUS_API_KEY,
base_url="https://api.studio.nebius.ai/v1/",
extra_body={
"top_k": 20,
"chat_template_kwargs": {"enable_thinking": False},
},
)
thinker_llm = ChatOpenAI(
model="Qwen/Qwen3-235B-A22B-Thinking-2507",
temperature=0,
api_key=NEBIUS_API_KEY,
base_url="https://api.studio.nebius.ai/v1/",
# Keep thoughts internal and bounded
extra_body={
"chat_template_kwargs": {"enable_thinking": True},
# Set budget
"thinking": {"type": "token", "budget": 1536}
},
)
supervisor_llm = ChatOpenAI(
model="gpt-4.1",
temperature=0
)# Prompts help to keep roles sharp
#SEARCH_PROMPT = """Role: Web researcher. Use the search tool and return a
#concise research note with sources. No follow-up questions."""
today = datetime.datetime.now().strftime("%Y-%m-%d")
SEARCH_PROMPT = f"""
You are a precise research agent. The date is {today}.
When the user asks for sources from a specific site or domain, pass that intent to the Tavily search tool using include_domains.
Typical flow:
1 search with TavilySearch to find relevant pages
2 extract with TavilyExtract on the top results
3 write a clear synthesis with short bullet points and inline bracketed citations pointing to the URLs you actually used
Be concise and evidence based.
""".strip()
EXA_PROMPT = """Role: Research assistant. You can search for all recent info
on Exa Search. Your response should clearly articulate the key points you found."""
PATENT_PROMPT = """Role: Market researcher with 20 years of experience.
You are very knowledgeable in patent research and in finding up-to-date info
about patents using the Google Patents API."""
NOTE_PROMPT = """You can read documents and create outlines for the document
writer. Don't ask follow-up questions."""
WRITER_PROMPT = """You can read, write and edit documents based on note-taker's
outlines. Don't ask follow-up questions."""
ANALYST_PROMPT = """
You are the Analyst. You must call the `semantic_filter_tool` exactly once.
Inputs:
- query: the current task topic or question
- documents: a list of raw strings gathered by teammates
Rules:
- Do not answer the user
- Do not do free form writing
- Only return the tool result to the supervisor
""".strip()
specs = [
dict(name="search", tools=[tavily_search, tavily_extract], prompt=SEARCH_PROMPT, llm=fast_llm),
dict(name="exa_search", tools=[exa_search_tool], prompt=EXA_PROMPT, llm=fast_llm),
dict(name="patent_research", tools=[patent_search], prompt=PATENT_PROMPT, llm=fast_llm),
dict(name="analyst", tools=[semantic_filter_tool], prompt=ANALYST_PROMPT, llm=thinker_llm),
dict(name="note_taker", tools=[create_outline, read_document], prompt=NOTE_PROMPT, llm=fast_llm),
dict(name="doc_writer", tools=[write_document, edit_document, read_document], prompt=WRITER_PROMPT, llm=fast_llm),
]
nodes = {
s["name"]: make_react_worker_node(llm=s["llm"], name=s["name"], tools=s["tools"], prompt=s["prompt"])
for s in specs
}
search_node = nodes["search"]
exa_search_node = nodes["exa_search"]
patent_research_node = nodes["patent_research"]
analyst_node = nodes["analyst"]
note_taking_node = nodes["note_taker"]
doc_writing_node = nodes["doc_writer"]
# Supervisor that can coordinate all four
research_supervisor_node = make_supervisor_node(
supervisor_llm, ["exa_search", "patent_research", "analyst", "note_taker", "doc_writer"]
)/tmp/ipython-input-3604616990.py:16: LangGraphDeprecatedSinceV10: create_react_agent has been moved to `langchain.agents`. Please update your import to `from langchain.agents import create_agent`. Deprecated in LangGraph V1.0 to be removed in V2.0.
agent = create_react_agent(llm, tools=tools, prompt=prompt)research_builder = StateGraph(State)
# register nodes
research_builder.add_node("supervisor", research_supervisor_node)
research_builder.add_node("exa_search", exa_search_node)
research_builder.add_node("patent_research", patent_research_node)
research_builder.add_node("analyst", analyst_node)
research_builder.add_node("note_taker", note_taking_node)
research_builder.add_node("doc_writer", doc_writing_node)
# --- Define edges ---
research_builder.add_edge(START, "supervisor")
research_builder.add_edge("exa_search", "supervisor")
research_builder.add_edge("patent_research", "supervisor")
research_builder.add_edge("analyst", "supervisor")
research_builder.add_edge("note_taker", "supervisor")
research_builder.add_edge("doc_writer", "supervisor")
research_graph = research_builder.compile()from IPython.display import Image, display
display(Image(research_graph.get_graph().draw_mermaid_png()))
我们可以直接给这个团队分配任务。在下面试试。
for s in research_graph.stream(
{"messages": [("user", """ Research the latest developments in AI agents,
specifically coding agents. Write at least 500 words about the findings.
Include patents! And include all links to references!
""")]},
{"recursion_limit": 100},
):
print(s)
print("---"){'supervisor': {'next': 'exa_search'}}
---
{'exa_search': {'messages': [HumanMessage(content='### Latest Developments in AI Agents: A Focus on Coding Agents\n\nAI agents, particularly those focused on coding, are rapidly evolving and transforming the landscape of software development. These agents, powered by large language models (LLMs), are capable of autonomously planning, executing, and interacting with various tools such as compilers, debuggers, and version control systems. This paradigm shift is not just about generating code but involves decomposing complex tasks into manageable steps, coordinating multi-step processes, and adapting based on feedback. The implications of these advancements are profound, as they promise to reshape traditional software development practices.\n\n#### AI Agentic Programming\n\nA recent survey titled "AI Agentic Programming: A Survey of Techniques, Challenges, and Opportunities" provides a comprehensive overview of the field. The authors, from the University of Leeds, introduce a taxonomy of agent behaviors and system architectures, examining relevant techniques for planning, context management, tool integration, and execution monitoring. This survey highlights the importance of context-awareness and adaptability in AI agents, which are crucial for handling the dynamic nature of software development tasks. The paper also discusses the challenges associated with these agents, including the need for robust planning mechanisms and the integration of diverse tools.\n\n#### SWE-agent: Agent-Computer Interfaces\n\nAnother significant development is the introduction of SWE-agent, a system that facilitates the use of language model agents in software engineering tasks. As described in the paper "SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering," this system is designed to enable LM agents to autonomously use computers to solve software engineering problems. The authors argue that just as humans benefit from powerful software applications, LM agents can also benefit from specially-built interfaces tailored to their needs. This approach not only enhances the performance of these agents but also opens up new possibilities for automated software engineering.\n\n#### AgentCoder: Multi-Agent-based Code Generation\n\nThe paper "AgentCoder: Multi-Agent-based Code Generation with Iterative Testing and Optimisation" presents a novel approach to code generation using multi-agent systems. This method involves iterative testing and optimization, allowing for the refinement of generated code through continuous feedback. The authors demonstrate how this approach can lead to more robust and efficient code generation, highlighting the potential of multi-agent systems in the realm of AI-driven software development.\n\n#### OpenHands: An Open Platform for AI Software Developers\n\nThe "OpenHands" project, as detailed in the paper "OpenHands: An Open Platform for AI Software Developers as Generalist Agents," introduces an open platform designed to support AI software developers as generalist agents. This platform aims to provide a comprehensive environment for AI agents to perform a wide range of software development tasks. The authors emphasize the importance of an open and collaborative approach in fostering innovation and advancing the capabilities of AI agents in software development.\n\n### Patents on AI Agents\n\nWhile the provided search results do not explicitly mention patents on AI agents, it is worth noting that the field of AI is rapidly evolving, and numerous patents are likely being filed to protect innovations in this area. Companies and research institutions are increasingly recognizing the potential of AI agents and are investing in developing proprietary technologies. These patents may cover various aspects of AI agent development, including novel algorithms, system architectures, and user interfaces.\n\n### Conclusion\n\nThe advancements in AI agents, particularly in the rea/usr/local/lib/python3.12/dist-packages/torch/_inductor/compile_fx.py:282: UserWarning: TensorFloat32 tensor cores for float32 matrix multiplication available but not enabled. Consider setting `torch.set_float32_matmul_precision('high')` for better performance.
warnings.warn(
W1102 12:49:47.802000 1518 torch/_inductor/utils.py:1436] [1/0_1] Not enough SMs to use max_autotune_gemm mode{'analyst': {'messages': [HumanMessage(content='\n\n[\n {\n "text": "### Patents on AI Agents\\n\\nWhile the provided search results do not explicitly mention patents on AI agents, it is worth noting that the field of AI is rapidly evolving, and numerous patents are likely being filed to protect innovations in this area.",\n "source": "Source Doc [1]",\n "score": 0.9658\n },\n {\n "text": "### Patents on AI Agents\\n\\nWhile the provided search results do not explicitly mention patents on AI agents, it is worth noting that the field of AI is rapidly evolving, and numerous patents are likely being filed to protect innovations in this area.",\n "source": "Source Doc [0]",\n "score": 0.9658\n },\n {\n "text": "### Latest Developments in AI Agents: A Focus on Coding Agents\\n\\nAI agents, particularly those focused on coding, are rapidly evolving and transforming the landscape of software development.",\n "source": "Source Doc [0]",\n "score": 0.956\n },\n {\n "text": "### Latest Developments in AI Agents: A Focus on Coding Agents\\n\\nAI agents, particularly those focused on coding, are rapidly evolving and transforming the landscape of software development.",\n "source": "Source Doc [1]",\n "score": 0.956\n },\n {\n "text": "These patents may cover various aspects of AI agent development, including novel algorithms, system architectures, and user interfaces.",\n "source": "Source Doc [1]",\n "score": 0.9516\n },\n {\n "text": "These patents may cover various aspects of AI agent development, including novel algorithms, system architectures, and user interfaces.",\n "source": "Source Doc [0]",\n "score": 0.9516\n },\n {\n "text": "### Conclusion\\n\\nThe advancements in AI agents, particularly in the realm of coding, are reshaping the software development landscape.",\n "source": "Source Doc [0]",\n "score": 0.9485\n },\n {\n "text": "### Conclusion\\n\\nThe advancements in AI agents, particularly in the realm of coding, are reshaping the software development landscape.",\n "source": "Source Doc [1]",\n "score": 0.9485\n },\n {\n "text": "This survey highlights the importance of context-awareness and adaptability in AI agents, which are crucial for handling the dynamic nature of software development tasks.",\n "source": "Source Doc [0]",\n "score": 0.9446\n },\n {\n "text": "This survey highlights the importance of context-awareness and adaptability in AI agents, which are crucial for handling the dynamic nature of software development tasks.",\n "source": "Source Doc [1]",\n "score": 0.9446\n }\n]', additional_kwargs={}, response_metadata={}, name='analyst')]}}
---
{'supervisor': {'next': 'note_taker'}}
---
{'note_taker': {'messages': [HumanMessage(content='The outline has been successfully saved to `ai_agents_coding_outline.md`. Let me know if you need further assistance!', additional_kwargs={}, response_metadata={}, name='note_taker')]}}
---
{'supervisor': {'next': 'doc_writer'}}
---
{'doc_writer': {'messages': [HumanMessage(content='The document has been successfully saved as `ai_agents_coding.md`. Let me know if you need any further assistance!', additional_kwargs={}, response_metadata={}, name='doc_writer')]}}
---
{'supervisor': {'next': '__end__'}}
---AI Agent 的最新进展:聚焦编码 Agent
AI agents,尤其是专注于编码的 agent,正在快速演进并改变软件开发的格局。这些 agent 由大语言模型(LLM)驱动,能够自主规划、执行,并与编译器、调试器、版本控制系统等各种工具交互。这种范式转变不仅仅是生成代码,还涉及把复杂任务分解成可管理的步骤、协调多步骤流程,并根据反馈进行调整。这些进展的影响深远,因为它们有望重塑传统的软件开发实践。
AI Agentic Programming(AI 智能体编程)
一篇题为 "AI Agentic Programming: A Survey of Techniques, Challenges, and Opportunities"(AI 智能体编程:技术、挑战与机遇综述)的最新综述对这一领域做了全面概述。作者来自利兹大学,提出了一个 agent 行为与系统架构的分类体系,考察了规划、上下文管理、工具集成和执行监控等相关技术。这篇综述强调了上下文感知和适应性在 AI agents 中的重要性,它们对处理软件开发任务的动态性至关重要。论文还讨论了这些 agent 面临的挑战,包括需要稳健的规划机制以及多样工具的集成。
SWE-agent:Agent-Computer Interfaces(智能体-计算机接口)
另一个重要进展是 SWE-agent 的推出,这是一个促进语言模型 agent 用于软件工程任务的系统。正如论文 "SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering"(SWE-agent:智能体-计算机接口实现自动化软件工程)所描述的,该系统旨在让 LM agents 能够自主使用计算机解决软件工程问题。作者认为,正如人类受益于强大的软件应用一样,LM agents 也能受益于为其需求量身定制的专门接口。这种方法不仅提升了这些 agent 的性能,也为自动化软件工程开辟了新的可能。
AgentCoder:基于多 Agent 的代码生成
论文 "AgentCoder: Multi-Agent-based Code Generation with Iterative Testing and Optimisation"(AgentCoder:基于迭代测试与优化的多 Agent 代码生成)提出了一种使用多 agent 系统进行代码生成的新方法。该方法涉及迭代测试和优化,通过持续反馈不断完善生成的代码。作者展示了这种方法如何带来更稳健、更高效的代码生成,凸显了多 agent 系统在 AI 驱动软件开发领域的潜力。
OpenHands:面向 AI 软件开发者的开放平台
"OpenHands" 项目(详见论文 "OpenHands: An Open Platform for AI Software Developers as Generalist Agents")推出了一个开放平台,旨在支持 AI 软件开发者作为通用型 agent 工作。该平台力求为 AI agents 提供一个综合环境,使其能够执行广泛的软件开发任务。作者强调了开放、协作的方式在推动创新和提升 AI agents 软件开发能力方面的重要性。
关于 AI Agent 的专利
虽然提供的搜索结果没有明确提及 AI agent 的专利,但值得注意的是,AI 领域正在快速演进,很可能有大量专利正在申请以保护该领域的创新。公司和研究机构正日益认识到 AI agents 的潜力,并投入研发专有技术。这些专利可能涵盖 AI agent 开发的各个方面,包括新颖的算法、系统架构和用户界面。
结论
AI agents 的进展,尤其是编码领域的进展,正在重塑软件开发格局。这些 agent 不仅能生成代码,还能自主规划、执行并适应复杂任务。SWE-agent 这样的系统和 OpenHands 这样的平台的推出,正在为更高效、更有效的软件开发实践铺平道路。随着这一领域的持续演进,保持对 AI agents 最新发展和创新的关注至关重要,这样才能充分发挥它们的潜力。
如需进一步阅读和详细信息,可以参考以下资源:
- AI Agentic Programming: A Survey of Techniques, Challenges, and Opportunities
- SWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering
- AgentCoder: Multi-Agent-based Code Generation with Iterative Testing and Optimisation
- OpenHands: An Open Platform for AI Software Developers as Generalist Agents