跳到正文
DEV Community· Shubham Vernekar·· 2 小時前AI 評分38

為消除 API 整合中的 AI 幻覺:為 Cognee 建立 Hoppscotch 連接器

Eliminating AI Hallucinations in API Integration: Building a Hoppscotch Connector for Cognee

AI 導讀

Hoppscotch 的 Cognee 連接器可匯入 API 集合,將端點、標頭、參數及請求內容整理成可搜尋的知識圖譜與向量索引,讓 AI 編碼智能體按需檢索 API 規格,減少憑空生成錯誤整合程式碼。連接器支援穩定識別端點、同步刪除的端點,並避免將實際生產憑證和存取權杖上傳至記憶系統。

正文

Autonomous AI coding agents such as Claude Code, Cursor, GitHub Copilot, and other AI-powered development tools are rapidly changing how we build software. Yet, developers who ask an agent to "write a client to call our internal billing and user service" often encounter the same problem: API hallucination.

An agent might invent nonexistent query parameters, omit required headers like X-Workspace-ID, choose the wrong authentication method, or generate requests for outdated endpoints.

Why does this happen?

Large language models (LLMs) generate responses based on learned patterns and the context provided to them. Without reliable, up-to-date API specifications, they may produce plausible-looking but incorrect integrations.

What if AI coding agents could retrieve structured API knowledge instead of guessing?

As part of Mergetober, I worked on a dedicated Hoppscotch data-source connector for Cognee to address this problem.

In this article, I'll explain why API schema memory matters, how the connector fits into the architecture, and how API collections can be ingested into Cognee to provide reliable context for AI-generated integration code.


1. Why Hoppscotch?

Hoppscotch is an open-source API development platform that helps developers create, organize, and test API requests.

Hoppscotch collections contain critical information about how an API should be used:

  • Endpoints: HTTP methods, paths, path parameters, and query parameters.
  • Headers: Required and optional HTTP headers.
  • Authentication: Bearer tokens, Basic authentication, OAuth 2.0, and API keys.
  • Request bodies: JSON payloads, nested objects, and sample data.
  • Environment variables: Dynamic values such as <<baseUrl>> and <<apiToken>>.
  • Organization: Collections, folders, and request names.

When API collections remain isolated in exported JSON files or desktop tools, an AI agent cannot reference them. Pasting an entire 10,000-line JSON export into a prompt floods the context window, burns tokens, and degrades attention.

A better approach is to ingest, structure, index, and retrieve API knowledge on demand.


2. Introducing Cognee: Knowledge Graphs and AI Memory

Cognee is an open-source framework for building AI memory systems using structured knowledge and retrieval.

Instead of relying exclusively on raw text chunks in a vector database, Cognee organizes API information into a hybrid knowledge graph + vector index:

  • Structured endpoint knowledge: Represents API requests with methods, URLs, headers, parameters, and payloads.
  • Relationship preservation: Maintains parent-child relationships between collections, folders, and individual requests.
  • Semantic retrieval: Allows AI agents to search for relevant API information using natural language questions.
  • Zero guesswork: Provides ground-truth API context before an agent generates integration code.

3. Architectural Overview: The Hoppscotch Connector

The connector bridges exported API collections and Cognee's memory pipeline:

Hoppscotch API Collection (.json)
           │
           ▼
Hoppscotch Connector (cognee-community)
           │
           ▼
Parse, Normalize & Resolve Variables
           │
           ▼
Cognee Ingestion Pipeline (dlt resource)
           │
           ▼
Knowledge Graph + Vector Store
           │
           ▼
AI Coding Agent (Claude, Cursor, Devin)
           │
           ▼
Schema-Grounded, Hallucination-Free Code

Key Design Considerations

3.1. Stable Endpoint Identifiers

The connector assigns a deterministic composite identifier to each API request:

hoppscotch:{collection_slug}:{folder_path}:{request_name}

Stable IDs ensure idempotent syncs. When you re-export your collection, existing graph nodes are cleanly updated rather than duplicated.

3.2. Synchronization and Deleted Endpoints

APIs evolve continuously. The connector sets write_disposition="replace" so that when an obsolete endpoint is deleted upstream, Cognee's automatic orphan cleanup purges it from both the vector index and the knowledge graph.

3.3. Environment Variables and Secret Handling

Hoppscotch environments use <<variable>> syntax. The connector resolves non-sensitive base URLs (e.g., <<baseUrl>>/v1/orders ➔ https://api.example.com/v1/orders) while ensuring real production credentials and access tokens are not uploaded to memory.

3.4. Structured, Agent-Friendly API Context

Each endpoint is formatted into a clean, markdown representation:

### POST /v1/orders
Collection: E-Commerce / Orders
Headers:
  - Content-Type: application/json
  - Idempotency-Key: <uuid>
Request Body:
{
  "customer_id": "string",
  "items": [
    { "sku": "string", "qty": 1 }
  ],
  "currency": "USD"
}

4. Step-by-Step: Ingesting a Hoppscotch Collection

Step 1: Install Dependencies

pip install cognee cognee-community-connector-hoppscotch

Step 2: Export Your Hoppscotch Workspace

  1. In Hoppscotch, open Collections ➔ click Export ➔ save as collection.json.
  2. (Optional) Export your active environment as environment.json.
api-memory-project/
├── collection.json
├── environment.json
└── main.py

Step 3: Ingest and Query the Collection

import asyncio
import cognee
from cognee_community_connector_hoppscotch import hoppscotch_source

async def main():
    # 1. Load the exported API collection
    print("Loading Hoppscotch collection...")
    source = hoppscotch_source(
        collection_path="./collection.json",
        environment_path="./environment.json",  # optional
    )

    # 2. Ingest into Cognee memory
    await cognee.remember(
        source,
        dataset_name="api_documentation",
    )

    # 3. Cognify: Build the semantic knowledge graph
    print("Processing API knowledge graph...")
    await cognee.cognify(
        dataset_name="api_documentation",
    )

    # 4. Search API memory with natural language
    print("Searching API memory...")
    results = await cognee.search(
        "Which endpoint creates a customer order, and what headers and request fields are required?",
        dataset_name="api_documentation",
    )

    for result in results:
        print(result)

if __name__ == "__main__":
    asyncio.run(main())

5. What Does Better API Grounding Look Like?

With a searchable API memory system, the agent retrieves the exact endpoint contract before writing code:

{
  "customer_id": "string",
  "items": [{ "sku": "string", "qty": 1 }],
  "currency": "USD"
}

Instead of guessing query params or inventing auth headers, the coding agent writes correct, production-ready integration clients on the very first try.


6. Open-Source Pull Request & Links


7. What's Next?

API documentation is only the first piece of the puzzle. Next in this Mergetober series, we will tackle database schema hallucinations by connecting Prisma ORM (schema.prisma) to Cognee!

What is the biggest source of hallucinations in your AI coding workflows: API contracts, database schemas, or infrastructure configs? Let me know in the comments!

來源:DEV Community · dev.to