Skip to content

Maira Integration

In the previous tutorials, we went through Maira's Data Management, Data Training, Profile and Settings management. After these steps, you are ready to integrate Maira into your system, send queries, and get customized responses.

To get a response from Maira, use the endpoint:

POST /v1/maira/iask

iAsk is the improved version of the legacy POST /v1/maira/ask endpoint. In addition to text queries, it accepts file attachments (images, PDF and PPTX), and it can return the response as a stream or as a background task.

Request format

The request body is multipart/form-data (not a plain JSON body). It has two parts:

Part Type Required Description
payload str (JSON) Yes JSON-encoded request body, carrying the query and options. See Payload fields below.
files file[] No Up to 10 files (image, PDF or PPTX) to attach to the query.

Here is a sample payload:

{
  "user_id": "a0cc6beb-2909-459b-be55-62196af78ce4",
  "member_id": "df3456tg-2909-459b-be55-62196afedf85",
  "user_name": "Taro Yamada",
  "query": "ask anything you want...",
  "conversation_type": "question",
  "gpt_profile_id": "48b3bc7c-0af1-4fd5-a8c4-b15015f46e44",
  "session_id": "48b3bc7c-0af1-4fd5-a8c4-b15015f46e44",
  "platform": "web",
  "language": "ja",
  "context_preference": {
    "preferred": {
      "dataset_id": "123456",
      "project_id": 45678
    },
    "excludes": {
      "client_id": "48b3bc7c-0af1-4fd5-a8c4-b15015f46e44"
    }
  },
  "conversation_metadata": {
    "project_id": "project1",
    "client_id": "client1"
  },
  "result_includes": [
    "key_name_1",
    "key_name_2"
  ],
  "top_k": 20,
  "keyword_ngram": 3,
  "is_keyword_enabled": true,
  "acknowledge_only": false,
  "is_background_task": false,
  "is_streaming": false
}

And here is an example curl request that sends the payload with an image attached:

curl -X POST \
  'https://api.recommender.gigalogy.com/v1/maira/iask' \
  -H 'accept: application/json' \
  -H 'project-key: <your-project-key>' \
  -H 'api-key: <your-api-key>' \
  -H 'Content-Type: multipart/form-data' \
  -F 'payload={"user_id": "test_12345", "query": "What is in this image?"}' \
  -F 'files=@product.png;type=image/png'

To attach more than one file, repeat the -F 'files=@...' line for each file.

Payload fields

Field Type Required Description
user_id str Yes Unique identifier for the user.
query str Yes* The user's query. *May be omitted if files is not empty.
conversation_type str No "chat" keeps conversation history; "question" is stateless. Default: "question".
gpt_profile_id str No Identifier of the GPT profile to use.
session_id str No Session identifier. Omit it to start a new session automatically.
member_id str No Member identifier (if applicable).
user_name str No Full name of the user.
platform str No Client platform identifier (e.g. "web").
language str No Query language hint (e.g. "ja").
context_preference dict No Dataset filters, with preferred and excludes dicts.
conversation_metadata dict No Arbitrary client metadata (e.g. project or client IDs).
result_includes list[str] No Specific fields to include in the response.
top_k int (1–20) No Number of top keywords to emphasize. Default: 20.
keyword_ngram int (1–3) No Keyword segmentation level. Default: 3.
is_keyword_enabled bool No Enable or disable keyword-based query expansion. Default: true.
acknowledge_only bool No If true, logs the query without generating a response.
sent_at datetime No Timestamp recorded by the client when the query was sent. Defaults to server time if omitted.
image_generation dict No Image generation options. Only used when the selected profile's model generates images.
file_transcriptions dict[str, str] No Transcription text for audio or video files in files, keyed by file name.
ts_metadata dict No Answers a pending time series field confirmation. See ts_metadata.
is_background_task bool No If true, returns 202 with a task_id immediately. See Background task mode.
is_streaming bool No If true, responds with a Server-Sent Events stream instead of JSON. Takes precedence over is_background_task. See Streaming mode.

Let's go through the fields in more detail.

user_id

A unique identifier for the user making the request. This is a required field and must be a non-empty string.

member_id

An identifier for a member associated with the request. member_id represents the logged-in unique ID of a user. This is useful to identify users across platforms or devices.

If your users log in to your application, we recommend sending member_id. With a member_id, a user keeps their context on whichever device they log in from, and you can list their sessions by member_id (see the "Sessions and Conversations" tutorial).

user_name and platform

user_name is the full name of the user, and platform identifies the client platform the query was sent from, such as "web".

query

The query text that the user wants to ask Maira. It is required, unless you attach at least one file in files. In that case, you can omit query and Maira will respond to the attached files.

conversation_type

Defines the type of conversation. Acceptable values are question and chat. The default value is question. A chat type conversation takes previous conversations into context to reply, whereas a question type conversation only considers the present query and is not aware of previous interactions. For example:

Chat-based conversation (remembers context):

  - User_query-1: I like sci-fi books. Can you suggest some?
  - AI_reply: Sure, here are some great sci-fi books for you.
  - User_query-2: Can you recommend some movies too?
  - AI_reply: Since you like sci-fi, here are some sci-fi movies you might enjoy.

Question-based conversation (no memory of context):

  - User_query-1: I like sci-fi books. Can you suggest some?
  - AI_reply: Sure, here are some great sci-fi books for you.
  - User_query-2: Can you recommend some movies too?
  - AI_reply: Here are some popular movies --> Not considering the sci-fi preference.

Note: Using the Chat History Length setting in your profile, you can set how many previous interactions Maira will consider to generate the reply for the current query.

gpt_profile_id

Specifies the GPT profile to be used. As discussed in the Profiles tutorial, you can have multiple profiles for various needs. Here, you can pass the ID of the profile you want to use for the scenario. If no profile ID is provided, the default profile will be used. (Refer to the Profiles tutorial to learn more about the default profile.)

session_id

An identifier for the session. Sessions are used to track the context of the conversation. Conversations in the same session know the context of the previous conversations.

  • No session_id: a new session is created automatically.
  • Existing session_id: the conversation continues in that session.

How many previous conversations are used as context is defined by the Chat History Length setting in the profile. See the "Profiles" tutorial for more details.

language

A hint for the language of the query, for example ja.

context_preference

Allows specifying preferences for context usage, including preferred and excluded datasets or projects. In the sample payload above, there is a preference for a dataset_id and a project_id, and a specific client_id is excluded. Here you can use dataset_id, idx_column, secondary_idx_column, or keys you included in the filterable_fields of your datasets.

conversation_metadata

Additional metadata related to the conversation, such as project and client identifiers. This can be an empty object or omitted. You can add anything here.

result_includes

A list of specific keys or fields that should be included in the response. Defaults to an empty list.

top_k

Controls the number of top keywords to consider while prioritizing reference documents. The value can be between 1 and 20. Defaults to 20. A higher top_k value considers more keywords, broadening the search, while a lower value narrows it down to fewer, more specific terms, making Maira more strict with its response.

keyword_ngram

Defines the n-gram size for keyword extraction, between 1 and 3. Defaults to 3.

  • Based on this setting, the model identifies the top keywords from a query, allowing for more flexible and accurate extraction. For example, for the sentence "I love natural language processing.":
    • If the value is 1: ["I", "love", "natural", "language", "processing"]
    • If the value is 2: ["I love", "love natural", "natural language", "language processing"]
    • If the value is 3: ["I love natural", "love natural language", "natural language processing"]
  • Each n-gram represents a sequence of words from the sentence, based on the specified value of n.

is_keyword_enabled

Enables or disables keyword-based query expansion. Defaults to true.

Tip

When Enabled (true)

  • The system prioritizes exact keyword matches.
  • Effect: Enhances precision by ensuring only documents containing the exact terms are retrieved. However, this may exclude relevant results that use different wording.
  • Use Case: Ideal for scenarios requiring highly specific matches, such as regulatory compliance, legal research, and technical terminology.

Examples:

  1. Supply Chain Management: Searching for "ISO 28000 certification" in a compliance database to find documents that specifically mention this supply chain security standard.
  2. Cybersecurity Reports: Looking for "Zero Trust Architecture" in technical documents to retrieve materials that focus strictly on this specific security framework.

When Disabled (false)

  • The system prioritizes semantic matching and broader relevance.
  • Effect: Expands search coverage by considering synonyms and related concepts, which increases the number of results but may reduce precision.
  • Use Case: Best suited for exploratory research, brainstorming, and when variations of a keyword matter.

Examples:

  1. Market Research: Searching for "sustainable fashion trends" to find reports on ethical clothing, eco-friendly materials, and slow fashion.
  2. Academic Research: Looking up "climate change policies" to retrieve papers covering carbon emissions, global warming regulations, and environmental sustainability initiatives.

Recommendation:

  • Turn On: When highly specific and targeted results are necessary (e.g., compliance verification, legal or technical document retrieval).
  • Turn Off: When a broader set of relevant results is required (e.g., exploratory research, brainstorming, or when keyword variations are important).

acknowledge_only

If true, Maira only logs the query without generating a response. When building AI agents, not all inputs require an immediate response. Sometimes the agent only needs to listen and retain context for future interactions. This flag enables that, improving contextual continuity in conversations.

sent_at

The timestamp recorded by the client when the query was sent. If omitted, the server time is used.

image_generation

Options for image generation. This is only used when the model of the selected profile generates images.

file_transcriptions

If you attach audio or video files in files, you can provide their transcription text here. The keys are the file names, and the values are the transcription text. For example:

{
  "file_transcriptions": {
    "meeting.mp4": "Transcription text of the meeting..."
  }
}

ts_metadata

Used with time series datasets. When Maira asks the user to confirm which time series fields to use, send the answer in ts_metadata as a confirmed_fields list of field names. For example:

{
  "ts_metadata": {
    "confirmed_fields": ["timestamp"]
  }
}

If the reply does not include a valid list, Maira asks for the confirmation again.

is_background_task and is_streaming

These two flags control how the response is returned. See Response modes below.


Minimum request

After the project setup is done, you can try the endpoint with only the required fields. Note that a default profile must be set first (refer to the Settings tutorial).

{
  "user_id": "test_12345",
  "query": "tell me what you know"
}

Sample response

Here is a sample 200 response:

{
  "detail": {
    "response": "Hello! I'm your virtual support assistant. How can I help you today?",
    "sections": [],
    "references": [],
    "generated_images": [],
    "tokens": 7593,
    "usage": {
      "prompt_tokens": 7407,
      "completion_tokens": 186,
      "total_tokens": 7593,
      "cached_tokens": 0,
      "reasoning_tokens": 107,
      "query_tokens": 3
    },
    "session_id": "48b3bc7c-0af1-4fd5-a8c4-b15015f46e44",
    "conversation_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
    "gpt_profile_id": "a0cc6beb-2909-459b-be55-62196af78ce4",
    "run_time": 8.94
  }
}

Some of the key fields:

  • response: The AI response to show to the user.
  • references: The reference documents the answer was based on.
  • generated_images: Images generated by the model, if any.
  • usage: Token usage of the request.
  • session_id: The session of the conversation. Send it in the next request to continue the session.
  • conversation_id: The ID of this conversation. Use it to send feedback (see the "Maira Feedback" tutorial) or to delete the conversation (see the "Sessions and Conversations" tutorial). It is also used for evaluation, which we will talk about in detail in the "Maira Evaluation" tutorial.
  • run_time: The time taken to generate the response, in seconds.

Response modes

iAsk can return the response in three ways. The flags are checked in this order:

  1. is_streaming: true → Server-Sent Events stream. See Streaming mode.
  2. is_background_task: true → 202 Accepted with a task_id to poll. See Background task mode.
  3. Otherwise → 200 with the full JSON response body.

If both flags are true, the response is streamed.

Background task mode

When is_background_task is true:

  1. The endpoint returns 202 Accepted immediately, with the task_id, conversation_id and session_id.
  2. Poll GET /v1/tasks/{task_id} until the status is success or failed.
  3. On success, message contains the JSON-encoded response body, with the same shape as the synchronous (200) response.
  4. On failed, message contains the reason for the error.

Streaming mode

When is_streaming is true, the endpoint returns Content-Type: text/event-stream instead of JSON. Each frame has the form data: <json>, followed by a blank line, and every payload has a type:

type Payload When
meta conversation_id, session_id, gpt_profile_id First frame
status {"step": ..., "message": ...} Progress updates before and during generation
delta {"text": "..."} Incremental chunks of the answer
done {"detail": {...}} Final frame, with the authoritative, complete response
error {"detail": {"response": ..., "error": ...}} The request failed after the stream opened

A : ping heartbeat is sent after every 15 seconds of inactivity to keep the connection alive. It has no data: field, and clients should ignore it.

Client notes

  • Render the final answer from done.detail.response, not from the concatenated delta text. Citations and response filters are applied to the final text only, and citation numbers can differ from what appeared in the deltas.
  • Some answers produce no delta frames at all (for example, image generation). Always be ready to render from done.
  • Files the model generates are listed in done.detail.files. Links that appear in delta text are placeholders. Only the links in done are final.
  • Closing the connection mid-stream cancels the request. Whatever text had already been streamed is kept as the saved answer.

Here is an example of reading the stream in Python:

import json
import requests

url = "https://api.recommender.gigalogy.com/v1/maira/iask"
headers = {
    "project-key": "<your-project-key>",
    "api-key": "<your-api-key>",
}
payload = {
    "user_id": "test_12345",
    "query": "tell me what you know",
    "is_streaming": True,
}

# (None, ...) sends "payload" as a plain multipart form field
with requests.post(
    url,
    headers=headers,
    files={"payload": (None, json.dumps(payload))},
    stream=True,
) as response:
    for raw_line in response.iter_lines():
        line = raw_line.decode("utf-8")
        # Skip blank lines and ": ping" heartbeats
        if not line or not line.startswith("data: "):
            continue
        event = json.loads(line[len("data: "):])

        if event["type"] == "delta":
            print(event["text"], end="", flush=True)  # live preview only
        elif event["type"] == "done":
            final_answer = event["detail"]["response"]  # render this
        elif event["type"] == "error":
            print("Error:", event["detail"]["error"])