1. Ingestion

1.1. Resources

1.2. INCLUDES

  • Imports
  • Environment Variables
  • TavilyCrawl, TavilyMap, TavilyExtract
  • OpenAIEmbeddings(已注释)
  • ZhipuAIEmbeddings
  • PineconeVectorStore / Chroma
  • llms.txt 读取与分批抓取
  • RecursiveCharacterTextSplitter 切分
  • 按 64 条一批写入 Pinecone
  • 多次执行互不影响

1.3. 改用智谱

点 Run 后,Output 在创建 PineconeVectorStore 时失败。文件还没执行到 main()。

pinecone.exceptions.exceptions.NotFoundException: (404)
Reason: Not Found
HTTP response body: {"error":{"code":"NOT_FOUND","message":"Resource langchain-docs not found"},"status":404}

课程代码用的是 OpenAI text-embedding-3-small(1536 维)和索引 langchain-docs。当前账号里没有这个索引,已建好的是智谱索引 langchain-docs-zhipu(embedding-3,1024 维)。.env 里的 OPENAI_API_KEY 仍是占位符。

ingestion.py 注释掉 OpenAI 导入、OpenAIEmbeddings 和原来的 PineconeVectorStore,改为和 create_index.py 一样的智谱配置。ZhipuAIEmbeddings 自动读取 ZHIPUAI_API_KEY,这里把 .env 里的 ZHIPU_API_KEY 传给 api_key。

# from langchain_openai import OpenAIEmbeddings
from langchain_community.embeddings import ZhipuAIEmbeddings

# embeddings = OpenAIEmbeddings(
#     model="text-embedding-3-small",
#     show_progress_bar=False,
#     chunk_size=50,
#     retry_min_seconds=10,
# )
embeddings = ZhipuAIEmbeddings(
    model="embedding-3",
    dimensions=1024,
    api_key=os.environ["ZHIPU_API_KEY"],
)
# vectorstore = PineconeVectorStore(
#     index_name="langchain-docs", embedding=embeddings
# )
vectorstore = PineconeVectorStore(
    index_name="langchain-docs-zhipu", embedding=embeddings
)

改完后再跑,Output 里只剩一条 langchain-community 的 DeprecationWarning,进程退出码是 0,用时 2.55 秒。这时 main() 还是空的,所以没有抓取文档。

1.4. 读取 llms.txt 并用 TavilyExtract 抓取

main() 先读 llms.txt,取出 Python 文档索引里 /oss/python/ 的页面,再按 20 个 URL 一批交给 TavilyExtract。各批并发执行。没有 raw_content 的页面会跳过。这一步只生成 Document。

LLMS_TXT = "https://docs.langchain.com/llms.txt"

def get_documentation_urls() -> List[str]:
    llms_txt = requests.get(LLMS_TXT, timeout=30).text
    python_line = next(line for line in llms_txt.splitlines() if "Build / Python" in line)
    python_index = re.search(r"\((https://\S+?\.txt)\)", python_line).group(1)
    index = requests.get(python_index, timeout=30).text
    urls = re.findall(r"\((https://docs\.langchain\.com/\S+?\.md)\)", index)
    return [url for url in urls if "/oss/python/" in url]

async def main():
    log_header("DOCUMENTATION INGESTION PIPELINE")
    urls = get_documentation_urls()
    log_success(f"llms.txt: Found {len(urls)} documentation pages")
    url_batches = chunk_urls(urls, chunk_size=20)
    all_docs = await async_extract(url_batches)

这次 Output 用时 16.303 秒,退出码 0。194 个 URL 分成 10 批:前 9 批各 20 个,最后一批 14 个。10 批全部成功,得到 194 篇文档。

🚀 DOCUMENTATION INGESTION PIPELINE
ℹ️  📄 llms.txt: Reading the documentation index from https://docs.langchain.com/llms.txt
✅ llms.txt: Found 194 documentation pages

🚀 DOCUMENT EXTRACTION PHASE
ℹ️  🔄 TavilyExtract: Processing batch 1 with 20 URLs
...
ℹ️  🔄 TavilyExtract: Processing batch 10 with 14 URLs
✅ TavilyExtract: Completed batch 6 - 20 pages
✅ TavilyExtract: Completed batch 10 - 14 pages
✅ TavilyExtract: Completed batch 3 - 20 pages
✅ TavilyExtract: Completed batch 1 - 20 pages
✅ TavilyExtract: Completed batch 2 - 20 pages
✅ TavilyExtract: Completed batch 9 - 20 pages
✅ TavilyExtract: Completed batch 4 - 20 pages
✅ TavilyExtract: Completed batch 8 - 20 pages
✅ TavilyExtract: Completed batch 5 - 20 pages
✅ TavilyExtract: Completed batch 7 - 20 pages
✅ TavilyExtract: Extracted 194 documents

批次完成顺序和提交顺序不一样,因为 asyncio.gather 是并发的。导入 ZhipuAIEmbeddings 时仍会打印 langchain-community 的 DeprecationWarning,不影响这次抓取。

1.5. 切分文档

抓取之后用 RecursiveCharacterTextSplitter 把 194 篇文档切成块。chunk_size 是 4000,chunk_overlap 是 200。

log_header("DOCUMENT CHUNKING PHASE")
text_splitter = RecursiveCharacterTextSplitter(chunk_size=4000, chunk_overlap=200)
splitted_docs = text_splitter.split_documents(all_docs)
log_success(
    f"Text Splitter: Created {len(splitted_docs)} chunks from {len(all_docs)} documents"
)

这次 Output 在抓取 194 篇之后继续切分,退出码 0,用时 7.167 秒。194 篇文档变成 1239 个 chunk。

🚀 DOCUMENT CHUNKING PHASE
ℹ️  ✂️  Text Splitter: Processing 194 documents with 4000 chunk size and 200 overlap
✅ Text Splitter: Created 1239 chunks from 194 documents

1.6. 写入智谱索引

切分后的 chunk 通过 vectorstore.add_documents 写入 langchain-docs-zhipu。ZhipuAIEmbeddings.embed_documents 会把整批文本放进一次请求的 input 数组。智谱 embedding-3 规定这个数组最多 64 条,超过就返回 400,错误码 1214,input数组最大不得超过64条。

index_documents_async 按 batch_size 切批,再用 asyncio.gather 并发调用 add_documents。调用处显式传入 64:

# Zhipu embedding-3 rejects an input array longer than 64.
await index_documents_async(splitted_docs, batch_size=64)

先用 500 跑过一次。1239 个 chunk 被分成 3 批,三批都失败,索引仍是空的。

ℹ️  📦 VectorStore Indexing: Split into 3 batches of 500 documents each
❌ VectorStore Indexing: Failed to add batch 3 - Error code: 400, with error text {"error":{"code":"1214","message":"input数组最大不得超过64条"}}
❌ VectorStore Indexing: Failed to add batch 1 - Error code: 400, with error text {"error":{"code":"1214","message":"input数组最大不得超过64条"}}
❌ VectorStore Indexing: Failed to add batch 2 - Error code: 400, with error text {"error":{"code":"1214","message":"input数组最大不得超过64条"}}
⚠️  VectorStore Indexing: Processed 0/3 batches successfully
python -c "from ingestion import vectorstore; print(vectorstore.index.describe_index_stats())"
{'dimension': 1024,
 'index_fullness': 0.0,
 'metric': 'cosine',
 'namespaces': {},
 'total_vector_count': 0,
 'vector_type': 'dense'}

main() 在入库失败后仍会打印 Documentation ingestion pipeline finished successfully!。入库是否成功要看上面的 0/3 和 describe_index_stats()。

把 batch_size 改成 64 后重新执行 python ingestion.py。1239 个 chunk 分成 20 批,前 19 批各 64 条,最后一批 23 条,20 批全部成功。

ℹ️  📦 VectorStore Indexing: Split into 20 batches of 64 documents each
✅ VectorStore Indexing: Successfully added batch 20/20 (23 documents)
✅ VectorStore Indexing: All batches processed successfully! (20/20)

再查一次索引,默认 namespace 里有 1239 条向量:

{'dimension': 1024,
 'index_fullness': 0.0,
 'metric': 'cosine',
 'namespaces': {'': {'vector_count': 1239}},
 'total_vector_count': 1239,
 'vector_type': 'dense'}

用智谱把问题嵌入后做相似度检索,取第一条:

python -c "from ingestion import vectorstore as vs; d = vs.similarity_search('What does the agent loop do?')[0]; print(d.id, d.metadata, d.page_content[:187], sep='\n')"
149362c6-8c09-46bb-bb95-d85b3ec2e7a4
{'source': 'https://docs.langchain.com/oss/python/langchain/multi-agent/subagents.md'}
> ## Documentation Index > Fetch the complete documentation index at: https://docs.langchain.com/llms.txt > Use this file to discover all available pages before exploring further

返回的 source 是入库时写在 metadata 里的文档地址。

1.7. 重复执行互不影响

一次 ingestion 对应一个 Pinecone 索引名,再配同一套 embeddings。当前脚本固定写 langchain-docs-zhipu(智谱 embedding-3,1024 维)。注释掉的 OpenAI 路径用的是另一个索引 langchain-docs(1536 维)。维度不同的结果不能放进同一个索引。换文档来源或换嵌入模型时,新建索引名,例如 other-docs-zhipu,查询也连这个名字。

add_documents 没有传入 ids。PineconeVectorStore 会给每条 chunk 生成新的 uuid4。Pinecone 按 id 做 upsert,id 不同就不会覆盖旧向量。同一份 ingestion.py 再成功跑一遍,langchain-docs-zhipu 的 total_vector_count 会再增加约 1239,检索里同一段文档会出现多条。

要重跑同一套 ingestion 且不保留旧向量,只清这个索引里的数据:

vectorstore.index.delete(delete_all=True)

这只影响当前 index_name,不会动 langchain-docs 或其他索引。索引定义还在,可以直接再执行 python ingestion.py。

要连索引一起删掉,按名字删除,不要用 delete_all 扫全部索引:

from pinecone import Pinecone
import os
from dotenv import load_dotenv

load_dotenv()
pc = Pinecone(api_key=os.environ["PINECONE_API_KEY"])
print([i.name for i in pc.list_indexes()])
pc.delete_index("langchain-docs-zhipu")

create_index.py 也是先 delete_index("langchain-docs-zhipu") 再按 1024 维重建。删掉整个索引后,要先跑 create_index.py,再跑 ingestion.py。

ccq/1-start-here-ingestion-finish

26.12.01

results matching ""

    No results matching ""