Skip to content

Conversation

@dm1tryG
Copy link
Contributor

@dm1tryG dm1tryG commented Apr 26, 2025

Description

/api/v1/responses
In this PR manages function calls

  • search
  • cognify
  • prune

Next steps

  • codify

DCO Affirmation

I affirm that all code in every commit of this pull request conforms to the terms of the Topoteretes Developer Certificate of Origin.

<!-- .github/pull_request_template.md -->

## Description
<!-- Provide a clear description of the changes in this PR -->

## DCO Affirmation
I affirm that all code in every commit of this pull request conforms to
the terms of the Topoteretes Developer Certificate of Origin.

---------

Co-authored-by: Vasilije <[email protected]>
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 26, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This update introduces a new "responses" API endpoint under /api/v1/responses in the FastAPI application. It adds a modular router that handles OpenAI-compatible function-calling requests and responses. The implementation includes new modules for tool definitions, function dispatch logic, and comprehensive Pydantic models for request and response structures. The router processes incoming requests, manages function calls (such as search, cognify, and prune), and returns structured outputs. Default tool specifications and schemas are provided to support validation and integration. The code is organized to facilitate extensibility and maintainability within the API framework.

Changes

File(s) Change Summary
cognee/api/client.py Added import and integration of get_responses_router from cognee.api.v1.responses.routers, mounting the new responses router at /api/v1/responses with the tag "responses".
cognee/api/v1/responses/init.py
cognee/api/v1/responses/routers/init.py
New __init__.py modules exposing get_responses_router as the public API for their respective packages.
cognee/api/v1/responses/default_tools.py
cognee/api/v1/responses/routers/default_tools.py
Added modules defining the DEFAULT_TOOLS constant as a list of tool specifications, each with JSON schema for parameters. Tools include search, cognify_text, and (in routers) prune.
cognee/api/v1/responses/dispatch_function.py New module implementing async dispatch logic for function calls based on tool name and arguments, with handlers for search, cognify, and prune. Includes logging and error handling.
cognee/api/v1/responses/models.py New module defining Pydantic models for function definitions, tool calls, requests, responses, and usage statistics, compatible with OpenAI's function calling format.
cognee/api/v1/responses/routers/get_responses_router.py New module providing a FastAPI router for the /api/v1/responses endpoint, handling POST requests, invoking the OpenAI API, dispatching function calls, and returning structured responses. Includes error handling and usage statistics extraction.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant FastAPI_Server
    participant ResponsesRouter
    participant OpenAIClient
    participant DispatchFunction

    Client->>FastAPI_Server: POST /api/v1/responses (ResponseRequest)
    FastAPI_Server->>ResponsesRouter: Handle request
    ResponsesRouter->>OpenAIClient: Call OpenAI responses API
    OpenAIClient-->>ResponsesRouter: Return API response
    alt Function call(s) present in response
        ResponsesRouter->>DispatchFunction: dispatch_function(tool_call)
        DispatchFunction-->>ResponsesRouter: Function result or error
    end
    ResponsesRouter-->>Client: Return ResponseResponse (with tool call outputs and usage)
Loading

Poem

🐇
A router hops in, swift and spry,
Bringing tools and models nigh.
Search and cognify, prune with care,
Structured responses everywhere!
With schemas neat and endpoints new,
The API garden grows and grew—
Springtime for code, with features bright,
The rabbits cheer this update’s light!


🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@dm1tryG dm1tryG force-pushed the feat/openai_chat_completion_response branch from c8e79e5 to f713511 Compare April 28, 2025 19:51
@dm1tryG dm1tryG force-pushed the feat/openai_chat_completion_response branch from f713511 to 2018850 Compare April 28, 2025 19:53
@dm1tryG dm1tryG requested a review from borisarzentar April 28, 2025 19:53
@dm1tryG dm1tryG marked this pull request as ready for review April 28, 2025 19:53
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 9

🧹 Nitpick comments (6)
cognee/api/v1/responses/default_tools.py (1)

24-28: Validate top_k bounds

top_k is declared with a default of 10 but no numerical guardrails. Supplying an excessively large or negative value could exhaust resources or raise errors deeper in the stack.

-                "top_k": {
-                    "type": "integer",
-                    "description": "Maximum number of results to return",
-                    "default": 10,
-                },
+                "top_k": {
+                    "type": "integer",
+                    "description": "Maximum number of results to return",
+                    "default": 10,
+                    "minimum": 1,
+                    "maximum": 100,
+                },
cognee/api/client.py (1)

17-18: Import order nitpick

To keep alphabetical grouping (present in nearby imports) place the new import after get_search_router.

-from cognee.api.v1.responses.routers import get_responses_router

This is purely stylistic – feel free to ignore if the team does not enforce ordering.

cognee/api/v1/responses/routers/default_tools.py (1)

1-86: Consider adding examples for each tool parameter

The tool definitions are well-structured, but adding examples would significantly improve developer experience when integrating with this API.

For example, you could enhance the search_query parameter like this:

                "search_query": {
                    "type": "string",
                    "description": "The query to search for in the knowledge graph",
+                   "example": "How does neural network training work?"
                },

Similar examples could be added for other parameters across all tools to provide clear guidance on expected inputs.

cognee/api/v1/responses/models.py (2)

11-16: Consider adding more model options to the CogneeModel enum

Currently, only one model is defined in the CogneeModel enum. As you expand your API offerings, you might want to support multiple model types.

class CogneeModel(str, Enum):
    """Enum for supported model types"""

    COGNEEV1 = "cognee-v1"
+   # Future model versions can be added here
+   # COGNEEV2 = "cognee-v2"

102-103: Initialize metadata with an empty dictionary

The metadata field in ResponseResponse is defined without a default value, which could lead to None reference errors if not explicitly set.

-   metadata: Dict[str, Any] = None
+   metadata: Dict[str, Any] = Field(default_factory=dict)

This ensures that metadata is always a dictionary, consistent with the pattern used for other fields in the model.

cognee/api/v1/responses/dispatch_function.py (1)

58-68: Use SearchType enum for validating search types

The code manually validates search types against a hardcoded list, but you already import SearchType which could be used for validation.

+from cognee.modules.search.types import SearchType

# Later in the handle_search function:
    search_type_str = arguments.get("search_type", "GRAPH_COMPLETION")
-    valid_search_types = (
-        search_tool["parameters"]["properties"]["search_type"]["enum"]
-        if search_tool
-        else ["INSIGHTS", "CODE", "GRAPH_COMPLETION", "SEMANTIC", "NATURAL_LANGUAGE"]
-    )
+    valid_search_types = [t.value for t in SearchType]

    if search_type_str not in valid_search_types:
        logger.warning(f"Invalid search_type: {search_type_str}, defaulting to GRAPH_COMPLETION")
        search_type_str = "GRAPH_COMPLETION"

This approach is more maintainable as it will automatically stay in sync with the SearchType enum.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7d7df18 and 2018850.

📒 Files selected for processing (8)
  • cognee/api/client.py (2 hunks)
  • cognee/api/v1/responses/__init__.py (1 hunks)
  • cognee/api/v1/responses/default_tools.py (1 hunks)
  • cognee/api/v1/responses/dispatch_function.py (1 hunks)
  • cognee/api/v1/responses/models.py (1 hunks)
  • cognee/api/v1/responses/routers/__init__.py (1 hunks)
  • cognee/api/v1/responses/routers/default_tools.py (1 hunks)
  • cognee/api/v1/responses/routers/get_responses_router.py (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
cognee/api/client.py (1)
cognee/api/v1/responses/routers/get_responses_router.py (1)
  • get_responses_router (23-146)
cognee/api/v1/responses/routers/get_responses_router.py (2)
cognee/api/v1/responses/models.py (6)
  • ResponseRequest (64-73)
  • ResponseResponse (92-102)
  • ResponseToolCall (83-89)
  • ChatUsage (56-61)
  • FunctionCall (41-45)
  • ToolCallOutput (76-80)
cognee/api/v1/responses/dispatch_function.py (1)
  • dispatch_function (19-44)
cognee/api/v1/responses/__init__.py (1)
cognee/api/v1/responses/routers/get_responses_router.py (1)
  • get_responses_router (23-146)
cognee/api/v1/responses/dispatch_function.py (5)
cognee/api/v1/responses/models.py (1)
  • ToolCall (48-53)
cognee/modules/search/types/SearchType.py (1)
  • SearchType (4-13)
cognee/modules/users/methods/get_default_user.py (1)
  • get_default_user (12-37)
cognee/shared/logging_utils.py (2)
  • info (121-122)
  • warning (124-125)
cognee/api/v1/datasets/datasets.py (1)
  • datasets (7-40)
🪛 Ruff (0.8.2)
cognee/api/v1/responses/dispatch_function.py

6-6: cognee.modules.search.types.SearchType imported but unused

Remove unused import: cognee.modules.search.types.SearchType

(F401)

🔇 Additional comments (5)
cognee/api/v1/responses/default_tools.py (1)

60-65: Keep tool list in sync with dispatcher

prune is commented out here but still handled inside dispatch_function.py.
If a request explicitly chooses the prune tool, OpenAI will return a tool call the router cannot validate against tools, resulting in a 400 error from the OpenAI API.

Either:

  1. Restore the prune entry (preferably with an "danger": true flag you check server-side), or
  2. Remove its handling branch from dispatch_function.py.
cognee/api/v1/responses/routers/__init__.py (1)

1-3: Re-export looks good

Simple barrel import correctly exposes get_responses_router.
No issues spotted.

cognee/api/v1/responses/__init__.py (1)

1-3: LGTM

The package-level re-export aligns with neighbouring packages and improves DX.

cognee/api/client.py (1)

171-172: Verify router prefix collision & OpenAPI tag

/api/v1/responses is new. Ensure no other router (e.g., legacy /responses) exists to avoid ambiguous routes, and that "responses" is added to tags_metadata if you generate custom OpenAPI docs.

cognee/api/v1/responses/routers/get_responses_router.py (1)

92-102: Confirm output key matches OpenAI Responses spec

The current implementation assumes the API payload resembles:

{ "output": [ { "type": "function_call", ... } ] }

OpenAI’s public examples instead nest tool calls inside choices[].message.tool_calls.
If the key path is wrong, no function will ever be dispatched.

Please verify with the latest SDK docs or live response and adjust traversal logic accordingly.

@dm1tryG
Copy link
Contributor Author

dm1tryG commented Apr 28, 2025

Hey, @borisarzentar @Vasilije1990 I have made base version of handle now it has tools with cognify+add, search and prune. Could you take a look pls?

@borisarzentar sorry, it was raw/draft version

@dm1tryG dm1tryG changed the title Add OpenAI-compatible chat and responses API endpoints with functions OpenAI compatible route /api/v1/responses Apr 28, 2025
@Vasilije1990 Vasilije1990 changed the title OpenAI compatible route /api/v1/responses feat: OpenAI compatible route /api/v1/responses Apr 29, 2025
diegoabt and others added 2 commits April 30, 2025 11:26
<!-- .github/pull_request_template.md -->

## Description 

This branch contains the Portuguese translation of the README
(`README.pt.md`).

Happy to work on any suggestions you may have.

## DCO Affirmation
I affirm that all code in every commit of this pull request conforms to
the terms of the Topoteretes Developer Certificate of Origin.

---------

Signed-off-by: Diego B Theuerkauf <[email protected]>
Co-authored-by: Hande <[email protected]>
Co-authored-by: Boris <[email protected]>
Co-authored-by: Boris <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@pull-checklist
Copy link

Please make sure all the checkboxes are checked:

  • I have tested these changes locally.
  • I have reviewed the code changes.
  • I have added end-to-end and unit tests (if applicable).
  • I have updated the documentation and README.md file (if necessary).
  • I have removed unnecessary code and debug statements.
  • PR title is clear and follows the convention.
  • I have tagged reviewers or team members for feedback.

@borisarzentar borisarzentar changed the base branch from main to dev April 30, 2025 11:00
@borisarzentar
Copy link
Member

Hey, @borisarzentar @Vasilije1990 I have made base version of handle now it has tools with cognify+add, search and prune. Could you take a look pls?

@borisarzentar sorry, it was raw/draft version

Hey @dm1tryG, thanks! I will take a look today.

@dm1tryG dm1tryG force-pushed the feat/openai_chat_completion_response branch from cf28ebf to 683af24 Compare May 3, 2025 09:54
if text:
await add(data=text, user=user)

await cognify(user=user, ontology_file_path=graph_model_file if graph_model_file else None)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see mixed ontology_file_path and graph_model usage.
If you want to set a custom graph model, you can do it with graph_model argument. But that one expects a pydantic model, so not suitable for this case. If you want to set a custom ontology, then ontology_file_path is the right property, but then the argument name is wrong.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ohh, yes, I missed that

@dm1tryG
Copy link
Contributor Author

dm1tryG commented May 15, 2025

@borisarzentar @Vasilije1990 have made fixes, please take a look again

@Vasilije1990 Vasilije1990 self-requested a review May 16, 2025 07:15
@Vasilije1990 Vasilije1990 merged commit 1dd179b into topoteretes:dev May 16, 2025
13 of 27 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants