Skip to content

API Chat for GraphQL APIs implementation #13098

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 18 commits into
base: master
Choose a base branch
from

Conversation

Nayanatharapmc
Copy link

No description provided.

@CLAassistant
Copy link

CLAassistant commented May 13, 2025

CLA assistant check
All committers have signed the CLA.

Copy link

coderabbitai bot commented May 13, 2025

📝 Walkthrough

Walkthrough

The changes introduce GraphQL support into the API Chat feature by adding new fields and logic to handle GraphQL SDL (Schema Definition Language) alongside existing HTTP/OpenAPI handling. This includes updates to Java interfaces, implementations, models, utility methods, and OpenAPI specifications, enabling API type awareness and dynamic payload construction based on API type.

Changes

File(s) Change Summary
.../org.wso2.carbon.apimgt.api/APIConsumer.java
.../impl/APIConsumerImpl.java
Updated invokeApiChatExecute method to accept an additional apiType parameter. Adjusted logic to append apiType to resource URLs and handle API type-specific payloads and error handling.
.../org.wso2.carbon.apimgt.api/model/APIChatGraphQLSdl.java Introduced new APIChatGraphQLSdl class with a private schemaDefinition field and public getter/setter for encapsulating a GraphQL SDL string.
.../org.wso2.carbon.apimgt.api/model/APIChatTestInitializerInfo.java Added a new private field schemaDefinition of type APIChatGraphQLSdl with corresponding getter and setter methods.
.../impl/utils/APIUtil.java Modified invokeAIService to treat both HTTP 200 and 201 as successful responses instead of only 201.
.../rest.api.common/src/main/resources/devportal-api.yaml
.../rest.api.store.v1/src/main/resources/devportal-api.yaml
Updated OpenAPI specs to add an optional schemaDefinition property to apiSpec in ApiChatRequest and ApiChatResponse schemas, with examples illustrating GraphQL SDL content.
.../rest.api.store.v1/impl/ApisApiServiceImpl.java Refactored imports. Updated apiChatPost to handle API type: for GraphQL APIs, sets SDL in initializer info; for others, sets service URL and tools in initializer info. Updated call to invokeApiChatExecute to include API type.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ApisApiServiceImpl
    participant APIConsumerImpl
    participant APIUtil

    Client->>ApisApiServiceImpl: POST /apiChat (apiChatPost)
    ApisApiServiceImpl->>ApisApiServiceImpl: Determine API type (GraphQL/HTTP)
    alt API type is GraphQL
        ApisApiServiceImpl->>ApisApiServiceImpl: Set SDL in initializer info
    else API type is HTTP
        ApisApiServiceImpl->>ApisApiServiceImpl: Set service URL and tools in initializer info
    end
    ApisApiServiceImpl->>APIConsumerImpl: invokeApiChatExecute(requestId, apiType, payload)
    APIConsumerImpl->>APIUtil: invokeAIService(..., resource + "?apiType=...", payload, ...)
    APIUtil-->>APIConsumerImpl: AI service response (HTTP 200/201)
    APIConsumerImpl-->>ApisApiServiceImpl: Response
    ApisApiServiceImpl-->>Client: API Chat response
Loading

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ast-grep (0.38.1)
components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 30th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 490e80c and 251b96e.

📒 Files selected for processing (1)
  • components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build-product (2, group2)
  • GitHub Check: build-product (3, group3)
  • GitHub Check: run-benchmark-test
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.

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.

Copy link

@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: 2

🧹 Nitpick comments (4)
components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/ApisApiServiceImpl.java (2)

31-31: Consider specific imports instead of wildcard

The change from specific imports to a wildcard import (org.wso2.carbon.apimgt.api.model.*) makes the code less explicit about which model classes are being used. While this simplifies the import section, it can make dependencies harder to track and may lead to unintended class conflicts.

-import org.wso2.carbon.apimgt.api.model.*;
+import org.wso2.carbon.apimgt.api.model.API;
+import org.wso2.carbon.apimgt.api.model.APIIdentifier;
+import org.wso2.carbon.apimgt.api.model.APIChatAPISpec;
+import org.wso2.carbon.apimgt.api.model.APIChatGraphQLSdl;
+import org.wso2.carbon.apimgt.api.model.APIChatTestInitializerInfo;
+import org.wso2.carbon.apimgt.api.model.APIChatExecutionResponse;
+import org.wso2.carbon.apimgt.api.model.APIChatTestExecutionInfo;
+import org.wso2.carbon.apimgt.api.model.APIRating;
+import org.wso2.carbon.apimgt.api.model.ApiTypeWrapper;
+import org.wso2.carbon.apimgt.api.model.Comment;
+import org.wso2.carbon.apimgt.api.model.CommentList;
+import org.wso2.carbon.apimgt.api.model.Documentation;
+import org.wso2.carbon.apimgt.api.model.DocumentationContent;
+import org.wso2.carbon.apimgt.api.model.Environment;
+import org.wso2.carbon.apimgt.api.model.OrganizationInfo;
+import org.wso2.carbon.apimgt.api.model.ResourceFile;
+import org.wso2.carbon.apimgt.api.model.Tier;

335-344: Add validation for SDL and service URL

The code now properly handles GraphQL APIs differently from other API types, setting the appropriate properties based on API type. However, there's no validation for the SDL or service URL values retrieved from the DTO.

Add null checks to prevent potential NullPointerExceptions:

if (apiType.equalsIgnoreCase(APIConstants.GRAPHQL_API)) {
    APIChatGraphQLSdl apiSdl = new APIChatGraphQLSdl();
-   apiSdl.setSdl(specDTO.getSdl());
+   String sdl = specDTO.getSdl();
+   if (sdl != null) {
+       apiSdl.setSdl(sdl);
+   } else {
+       log.warn("SDL is null for GraphQL API with ID: " + apiId);
+   }
    initializerInfo.setSdl(apiSdl);
} else {
    APIChatAPISpec apiSpec = new APIChatAPISpec();
-   apiSpec.setServiceUrl(specDTO.getServiceUrl());
-   apiSpec.setTools(specDTO.getTools());
+   String serviceUrl = specDTO.getServiceUrl();
+   if (serviceUrl != null) {
+       apiSpec.setServiceUrl(serviceUrl);
+   }
+   apiSpec.setTools(specDTO.getTools()); // Tools can be null
    initializerInfo.setApiSpec(apiSpec);
}
components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml (2)

6145-6161: Suggestion: Use a YAML block scalar for the sdl example
The sdl property in ApiChatRequest.apiSpec is defined with a single-quoted literal containing embedded newlines and leading spaces. This can be hard to read and may introduce unintended whitespace in the example value. Switching to the YAML pipe (|) block scalar will preserve the intended formatting more clearly.

For instance, you could refactor from:

      sdl:
        type: string
        description: GraphQL API schema definition
        example: '
                        schema {
                          query: Query
                        }
                        type Query {
                          hero(id: ID!): Character
                          allHeroes: [Character]
                        }
                        type Character {
                          id: ID!
                          name: String!
                          appearsIn: [String]
                        }'

to:

       sdl:
         type: string
         description: GraphQL API schema definition in SDL format
-        example: '
-                        schema {
-                          query: Query
-                        }
-                        type Query {
-                          hero(id: ID!): Character
-                          allHeroes: [Character]
-                        }
-                        type Character {
-                          id: ID!
-                          name: String!
-                          appearsIn: [String]
-                        }'
+        example: |
+          schema {
+            query: Query
+          }
+          type Query {
+            hero(id: ID!): Character
+            allHeroes: [Character]
+          }
+          type Character {
+            id: ID!
+            name: String!
+            appearsIn: [String]
+          }

6219-6223: Suggestion: Apply the same block scalar approach to the response sdl
The sdl in ApiChatResponse.apiSpec also uses an inline quoted string for the example. For consistency and to improve readability, convert it to a pipe block scalar:

       sdl:
         type: string
         description: Processed GraphQL API schema definition (for GraphQL APIs)
-        example: "schema { query: Query } type Query { hero(id: ID!): Character allHeroes: [Character] } type Character { id: ID! name: String! appearsIn: [String] }"
+        example: |
+          schema {
+            query: Query
+          }
+          type Query {
+            hero(id: ID!): Character
+            allHeroes: [Character]
+          }
+          type Character {
+            id: ID!
+            name: String!
+            appearsIn: [String]
+          }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3a896e6 and 50be8ea.

⛔ Files ignored due to path filters (2)
  • components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/ApiChatRequestApiSpecDTO.java is excluded by !**/gen/**
  • components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/gen/java/org/wso2/carbon/apimgt/rest/api/store/v1/dto/EnrichedAPISpecDTO.java is excluded by !**/gen/**
📒 Files selected for processing (8)
  • components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java (1 hunks)
  • components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/APIChatGraphQLSdl.java (1 hunks)
  • components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/APIChatTestInitializerInfo.java (2 hunks)
  • components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java (2 hunks)
  • components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/utils/APIUtil.java (2 hunks)
  • components/apimgt/org.wso2.carbon.apimgt.rest.api.common/src/main/resources/devportal-api.yaml (2 hunks)
  • components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/ApisApiServiceImpl.java (3 hunks)
  • components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/resources/devportal-api.yaml (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: build-product (3, group3)
  • GitHub Check: build-product (4, group4)
  • GitHub Check: build-product (2, group2)
  • GitHub Check: build-product (1, group1)
  • GitHub Check: build-carbon
  • GitHub Check: run-benchmark-test
🔇 Additional comments (15)
components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/APIChatGraphQLSdl.java (1)

1-13: Class is well-structured for its purpose.

The APIChatGraphQLSdl class is a simple POJO that encapsulates a GraphQL Schema Definition Language (SDL) string. It follows good encapsulation practices with a private field and appropriate getter/setter methods.

components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/model/APIChatTestInitializerInfo.java (2)

27-27: Field addition looks good.

The new GraphQL SDL field is appropriately added to the APIChatTestInitializerInfo class to store GraphQL schema information.


45-51: Getter and setter for GraphQL SDL follow class conventions.

The getter and setter methods for the SDL field follow the same style as other methods in the class, maintaining consistency in the codebase.

components/apimgt/org.wso2.carbon.apimgt.api/src/main/java/org/wso2/carbon/apimgt/api/APIConsumer.java (2)

840-841: API type parameter addition is appropriate.

Adding the apiType parameter to the invokeApiChatExecute method signature will enable type-specific handling of different API types (e.g., GraphQL vs REST).


845-845:

✅ Verification successful

Method signature updated consistently.

The method declaration has been properly updated to include the new apiType parameter. Make sure all implementations of this interface method have been updated accordingly.


🏁 Script executed:

#!/bin/bash
# Find all implementations of the invokeApiChatExecute method
rg -A 3 "invokeApiChatExecute.*String apiType" --type java

Length of output: 1576


invokeApiChatExecute signature updated consistently

Both the interface (APIConsumer.java) and its implementation (APIConsumerImpl.java) now include the new apiType parameter. No further changes are required.

components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/utils/APIUtil.java (2)

272-272: Added import for URLEncoder to support the API Chat feature for GraphQL APIs

The added import for java.net.URLEncoder is necessary to properly encode query parameters when making API calls to the AI service, particularly for the new apiType parameter that distinguishes between OpenAPI and GraphQL schemas.


11217-11218: Enhanced HTTP response handling to support both OK and CREATED status codes

The conditional check has been expanded to accept both HTTP 200 (OK) and HTTP 201 (CREATED) as successful responses, making the method more flexible when interacting with AI services. This is good practice as different API implementations might return either status code for successful operations.

components/apimgt/org.wso2.carbon.apimgt.rest.api.store.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/store/v1/impl/ApisApiServiceImpl.java (2)

328-329: LGTM: API type retrieval for context-aware processing

This code correctly retrieves the API type to enable type-specific handling in the API Chat feature.


370-370: LGTM: Updated method call to include API type

The method call has been correctly updated to include the API type parameter, which is needed to handle type-specific behaviors in the API Chat execution.

components/apimgt/org.wso2.carbon.apimgt.impl/src/main/java/org/wso2/carbon/apimgt/impl/APIConsumerImpl.java (6)

3360-3370: Well-implemented API type support in API Chat execute method

The updated method now includes the API type as a URL parameter when invoking the AI service, which properly supports both GraphQL and HTTP APIs. The URL encoding is correctly applied using UTF-8 charset.


3377-3389: Good dynamic API type handling for API Chat preparation

The implementation correctly retrieves the API type from the database and constructs the appropriate payload based on whether it's a GraphQL or HTTP API. The conditional logic is clear and follows a proper flow with appropriate error handling for unsupported API types.


3381-3384: Well-implemented GraphQL schema support

This code correctly retrieves and includes the GraphQL schema in the payload when handling GraphQL API types, which is essential for the API chat feature to understand GraphQL APIs.


3385-3387: Proper OpenAPI definition handling for HTTP APIs

The code properly parses the OpenAPI definition for HTTP API types and adds it to the payload. The use of ObjectMapper ensures proper JSON handling.


3388-3389: Good error handling for unsupported API types

The implementation throws an appropriate exception with a clear error message when encountering an unsupported API type.


3392-3393: Well-implemented API type parameter in resource URL

The code correctly adds the API type as a query parameter to the prepare resource URL, properly URL-encoded to prevent injection issues.

Comment on lines 6219 to 6223
sdl:
type: string
description: Processed GraphQL API schema definition (for GraphQL APIs)
example: "schema { query: Query } type Query { hero(id: ID!): Character allHeroes: [Character] } type Character { id: ID! name: String! appearsIn: [String] }"
taskStatus:
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Use block scalar for the example in ApiChatResponse.apiSpec.sdl
The example for the sdl property in the response schema is written as a single-line quoted string containing many types. For consistency and valid YAML, convert it to a block scalar.

Proposed fix:

@@ -6217,7 +6217,7 @@
             tools:
               type: array
               description: Extracted Http tools from the OpenAPI specification
-              example: "schema { query: Query } type Query { hero(id: ID!): Character allHeroes: [Character] } type Character { id: ID! name: String! appearsIn: [String] }"
+              example: |
+                        schema {
+                          query: Query
+                        }
+                        type Query {
+                          hero(id: ID!): Character
+                          allHeroes: [Character]
+                        }
+                        type Character {
+                          id: ID!
+                          name: String!
+                          appearsIn: [String]
+                        }
             sdl:
               type: string
               description: Processed GraphQL API schema definition (for GraphQL APIs)

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines 6145 to 6161
sdl:
type: string
description: GraphQL API schema definition
example: '
schema {
query: Query
}
type Query {
hero(id: ID!): Character
allHeroes: [Character]
}
type Character {
id: ID!
name: String!
appearsIn: [String]
}'
response:
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Invalid YAML literal for multiline example
The example value for the new sdl property in ApiChatRequest.apiSpec is wrapped in single quotes but contains actual newlines, which isn’t valid YAML. You should use a block scalar (|) to represent a multiline string.

Proposed fix:

@@ -6139,7 +6139,7 @@
             tools:
               type: array
               description: Extracted Http tools from the OpenAPI specification
-              example: '…'
+              example: |
+                        schema {
+                          query: Query
+                        }
+                        type Query {
+                          hero(id: ID!): Character
+                          allHeroes: [Character]
+                        }
+                        type Character {
+                          id: ID!
+                          name: String!
+                          appearsIn: [String]
+                        }
             sdl:
               type: string
               description: GraphQL API schema definition
-              example: '
-                        schema {
-                          query: Query
-                        }
-                        type Query {
-                          hero(id: ID!): Character
-                          allHeroes: [Character]
-                        }
-                        type Character {
-                          id: ID!
-                          name: String!
-                          appearsIn: [String]
-                        }'
+              example: |
+                        schema {
+                          query: Query
+                        }
+                        type Query {
+                          hero(id: ID!): Character
+                          allHeroes: [Character]
+                        }
+                        type Character {
+                          id: ID!
+                          name: String!
+                          appearsIn: [String]
+                        }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
sdl:
type: string
description: GraphQL API schema definition
example: '
schema {
query: Query
}
type Query {
hero(id: ID!): Character
allHeroes: [Character]
}
type Character {
id: ID!
name: String!
appearsIn: [String]
}'
response:
sdl:
type: string
description: GraphQL API schema definition
example: |
schema {
query: Query
}
type Query {
hero(id: ID!): Character
allHeroes: [Character]
}
type Character {
id: ID!
name: String!
appearsIn: [String]
}
response:

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