Documentation
search
Call Function
Introduction

Introduction

AIDocs is a user-friendly platform that enables you to quickly call your backend API. The process is simple:

  1. Define your API in the AIDocs editor. 在 AIDocs 编辑器中定义您的 API。
  2. Ask a question. 问一个问题。
  3. The language model will determine whether to call your API or not. 语言模型将确定是否调用您的 API。
  4. Send a post request to your API. 发送一个post请求到你的 API。
  5. Return the result to the user. If you choose to use AI to explain your JSON result, the generated explanation will be returned to the user. Otherwise, the original JSON result will be returned. 将结果返回给用户。如果您选择使用 AI 来解释您的 JSON 结果,生成的解释将返回给用户。否则,将返回原始的 JSON 结果。

Example

ℹ️

In this example, we'll create a simple API. The API will enable users to book a flight ticket by specifying a date and destination. The API will return a JSON result that includes the flight information and price. We'll use the large language model to explain the result.

Note: The following example is using Next.js. You can use any framework you like.

在这个例子中,我们将创建一个简单的 API。 该 API 将允许用户通过指定日期和目的地来预订机票。 API 将返回一个包含航班信息和价格的 JSON 结果。最后,我们将使用大型语言模型来解释结果。

Step 1: Use pnpm to create next app

pnpm create next-app

This will give you a basic Next.js app with following structure:

      • page.tsx
        • route.ts
  • Note that we have a route.ts file under api folder. This is where we'll define our API. 注意,我们在api文件夹下有一个route.ts文件。这是我们定义 API 的地方。

    Step 2: Define your Booking logic

    Since this is just an example, we'll use a simple logic to book a flight ticket. We will create a list for each destination and date. When a user books a ticket, we'll check if the destination and date are available. We will also create a map to map their api key to their user information. This simulates the database authentication logic.

    既然这只是一个例子,我们将使用一个简单的逻辑来预订机票。 我们将为每个目的地和日期创建一个列表。当用户预订机票时, 我们将检查目的地和日期是否可用。我们还将创建一个映射, 将他们的 API 密钥映射到他们的用户信息。这模拟了数据库身份验证逻辑。

        const airpords = ["HKG", "LAX", "JFK", "SIN", "PVG"];
     
        const userMap = {
            "some-random-api-key": {
            userId: "123",
            name: "John Doe",
            };
        };

    Step 3: Define your API

    Now we can define our API. The AIDocs Server will send a POST request to your server with the x-api-key in header. You can use this header to authenticate the user and check whether the request was sent from AIDocs Server. Remember to return a JSON object with message field back to the server.

    现在我们可以定义我们的 API。AIDocs 服务器将使用头部的x-api-key向您的服务器发送一个POST请求。 你可以用这个来确定请求是来自我们的服务器的。

    Our request body would have the following fields:

    • to: The destination of the flight.
    • date: The date of the flight.
    • from: The starting point of the flight.

    Note that to and from are both the airport code. For example, HKG is the airport code for Hong Kong International Airport.

    export async function POST(request: Request) {
      const body: RequestBody = await request.json();
      console.log(body);
      const headers = request.headers;
      const apiKey = headers.get("x-api-key");
     
      // Check if the API key is valid and exists in the userMap
      if (!apiKey || !userMap[apiKey]) {
        return NextResponse.json(
          {
            message:
              message: "Invalid API key",
          },
          {
            status: 401,
          }
        );
      }
     
      // Check if the request body is valid
      if (!body.from) {
        return NextResponse.json(
          {
            message:  "Missing required fields `from`",
          },
          {
            status: 400,
          }
        );
      }
     
      if (!body.to) {
        return NextResponse.json(
          {
            message:
              message: "Missing required fields `to`",
          },
          {
            status: 400,
          }
        );
      }
     
      if (!body.date) {
        return NextResponse.json(
          {
            message:
              message: "Missing required fields `date`",
          },
          {
            status: 400,
          }
        );
      }
     
      // Check if the date is valid
      const date = new Date(body.date);
      if (isNaN(date.getTime())) {
        return NextResponse.json(
          {
            message: "Invalid date",
          },
          {
            status: 400,
          }
        );
      }
     
      // check if the date is in the past
      if (date.getTime() < Date.now()) {
        return NextResponse.json(
          {
            message: "Date is in the past",
          },
          {
            status: 400,
          }
        );
      }
     
      // Check if the airport codes are valid
      if (!airpords.includes(body.from) || !airpords.includes(body.to)) {
        return NextResponse.json(
          {
            message: "Invalid airport code",
          },
          {
            status: 400,
          }
        );
      }
     
      // Return the response
      return NextResponse.json({
        message: `User ${userMap[apiKey].name} successfully booked a flight from ${body.from} to ${body.to} on ${body.date}`,
      });
    }

    Step 4: Test the API

    {
        "from": "LAX",
        "to": "HKG",
        "date": "2023-09-01"
    }

    Step 5: Define your API in AIDocs

    Open project detail, click Edit Apis button, then add a new API as follow:

    • Name: flight_booking
    • Description: This api is used for airline booking
    • Endpoint": https://your-domain.com/api/route or our deployed endpoint https://ai-kongshum-api.vercel.app/api/flight
    • Use AI for response: Yes
    • Parameters
    {
      "to": {
        "type": "string",
        "title": "to",
        "description": "AIRPORT CODE, for example, LAX, HKG, and PVG"
      },
      "date": {
        "type": "string",
        "title": "date",
        "description": "Date time in format YYYY-MM-DD"
      },
      "from": {
        "type": "string",
        "title": "from",
        "description": "AIRPORT CODE, for example, LAX, HKG, and PVG"
      }
    }

    Step 6: Test the API in AIDocs

    Now you can ask AI Book an airline ticket from Hong Kong to Los angels on 2023-09-23 and you will get the response:

    John Doe successfully booked a flight from Hong Kong (HKG) to Los Angeles (LAX) on September 23, 2023

    If there exists an Error, you will get the response with error message explained by AI:

    🚫

    The question is not answerable using the question's language because it does not provide all the necessary information required to book a ticket. The error message indicates that a required field "from" is missing. In order to book a ticket, the "from" field should specify the departure location or origin. Without this information, it is not possible to proceed with the booking process. The error message does not provide any date-related problems, so there is no need to provide a specific date in the response.