The Qwiery JavaScript client library is an ajax wrapper to easily call the Qwiery API. Besides giving access to all of the public facing Qwiery methods it also contains various utilities to help you build JavaScript applications on top of Qwiery.

The documentation below divides the API in broad sections which combine related methods. You will find a similar organization in the wrapper itself.

In order to access the Qwiery API you need an API key which you get after registration. All Qwiery API requests need this key in the XHR request body. A typical request looks hence like the following:

$.ajax({
        url: Qwiery.serviceURL + '/graph/entity/upsert/',
        beforeSend: function(xhr) {
            xhr.setRequestHeader("ApiKey", Qwiery.apiKey);
        },
        xhrFields: {
            withCredentials: true
        },
        type: "POST",
        data: JSON.stringify(data),
        headers: {'Content-Type': 'application/json'},
        timeout: Qwiery.timeout
    });

The Qwiery.timeout is the the ajax timeout and is set by default to ten seconds.

Concepts

  • input refers to a question posted to Qwiery. This is always a string.
  • output refers to the returned answer. This is in general an object.
  • envelope or session is a message being processed by Qwiery which contains all the information needed for resolving an answer: input, user info, context, templates and much more. An envelope is internally an object but serialized as XML or JSON.
  • correlationId is the unique identifier of an interaction. The unique key of an envelope is the combination of the user id and the correlation id.
  • template always refers to a QTL template.
  • engine is synonymous to Qwiery although the underlying ‘engine’ is more general than the online Qwiery instance.

Graph

The graph methods relate to the storage of entities and knowledge. The underlying GraphDB store is a generic graph storage and the Qwiery API related to entities reflect to some extend the (enterprise-level) GraphDB.Net API.

The graph is mathematically speaking a directed multi-graph. It can have cycles and loops, these occurences are not being checked and the topological implications have to be accounted for in the algorithms.

upsertEntity(entity): id

Updates or inserts the given entity and returns the unique identifier of the upserted entity.

var thought = {
    Title: "A bright, beautiful Sunday morning",
    DataType: "Thought"
};

Qwiery.upsertEntity(thought).then(function(id) {
  // the new Thought was inserted with identifier id
});

The DataType is a hint of the type you wish to upsert. Only the fields relevant to the type will be picked up. If the type is not specified Qwiery will attempt to make sense of the given data and create either a simple Thought or a dictionary entity (a bag of properties) containing a key-value list of the given data.

The effect of adding entities is like adding knowledge to Qwiery but (like the human brain in fact) disconnected entities have little chance to be picked up by Qwiery because relationships really create knowledge rather than standalone facts. For example, adding a ‘window’ entity without specifying the relation to either ‘programming’ or that it’s something part of a house will keep the entity somewhat isolated from the real world. Use the connect method to link entities and create a web of knowledge (aka semantic network).

getEntity(id): entity

Fetches the entity with the specified identitifer.

Qwiery.getEntity("19288-4492-33").then(function(entity){
  if(Qwiery.isDefined(entity)){
    console.log(entity.Title);
  }
})

The DataType field contains the data type of the entity e.g. Thought, Person, Task and so on.

getEntities(ids): array of entities

Similar to getEntity, it fetches a series of entities with the specified identitifers.

Qwiery.getEntities(["19288-4492-33", "665-6546-665-8"]).then(function(entities){
   for(var k=0; k<entities.length; k++){
    console.log(entities[k].Title);
   }
})

deleteEntity(id): bool

Deletes the entity with the given identifier.

Qwiery.deleteEntity("901-55288-492-03").then(function(success){
  if(success){
    console.log("The entity was deleted.");
  }
})

Any link, label or other element that depends on this entity will also be removed. The store ensures integrity of the data at all times.

connect(fromId, toId, label): id

Alias: linkEntities

Connects the entities with the given identifiers. The optional link label allows to give semantic meaning to the new link.

Qwiery.connect("124-4223-55", "234-5-5237", "is related to").then(function(linkId){
console.log("Link with id " + linkId + " was created.")
    })

The underlying graph structure is a directed graph, so the source and target identifiers should in general not be mixed up. For example, the triple “a tree -> is a -> plant” is not true when inverted.

disconnect(fromId, toId, label)

Alias: unlinkEntities

Unlinks the entities with the given identifiers. The label is optional, if not specified all links between the entities will be removed.

getRelated(id): array of entities

Gets the neighbor (parents and children) nodes of the entity with the given identifier.

var john = {
    FirstName: 'John',
    LastName: 'Carston',
    DataType: "Person",
    Title: "The man with a plan"
};
var maria = {
    FirstName: 'Maria',
    LastName: 'Olguar',
    DataType: "Person",
    Title: "She knows why"
};
var johnId, mariaId;
$.when(Qwiery.upsertEntities([john, maria]))
    .then(function(u) {
        johnId = u[0];
        mariaId = u[1];
        $.when(Qwiery.linkEntities(johnId, mariaId, 'awesome')).then(function(linkId) {
            ok(linkId !== null);
            $.when(Qwiery.getRelated(johnId)).then(function(relatedNodes) {
                // relatedNodes is an array of length 1
                // the following gives 'awesome'
                console.log(relatedNodes[0].Relationship);
            });
        });
    });

getRecentEntities

Gets the last ten created entities across all the workspaces the user owns. This method is especially useful in developing a UX which shows a trail of the user’s activity.

getEntityTags(id): array of tags (string)

Gets the tags of the entity with the specified identifier.

Qwiery.tagEntity("SomeEntityId", "A tag name").then(
  function(){
      Qwiery.getEntityTags("SomeEntityId").then(
        function(tags){
          // do something with the tags of the entity
        }
      );
  }
); 

Search

The search methods relate to searching things in Qwiery or via Qwiery. Out of the box Qwiery uses Bing, Wolfram Alpha and Wikipedia as external search engines but it takes just a few line to add additional ones or replace, say, Bing with Google.

searchWeb(term, source, count): array or search results

The source parameter can be image, web or news and defaults to web if not specified.

$.when(Qwiery.searchWeb('Latest', 'News'))
    .then(function(results) {
       // the content of the JSON returned depends on the service (Google, Bing....)
    });
$.when(Qwiery.searchWeb('Elephants', 'Images'))
    .then(function(results) {
       // media urls and so on
    });

searchGraph(term, type): array of entities

Searches the user’s scope for entities with the Title containing the specified term. The optional DataType parameter can narrow down the search to a specified entity type. If not provided all types will be included in the search.
The search will run across all workspaces of the user plus the public and shared ones.

 var address = {
    DataType: "Address",
    Title: "Home sweet home",
    AddressLine1: "Galleria del'Arte 455b",
    "Id": Qwiery.guid()
};
Qwiery.upsertEntity(address).then(function() {
    $.when(Qwiery.searchGraph('*', 'Address'))
        .then(function(results) {
           // the results will contain the added address
        });
});

searchAlpha(term): array of search results

Searches Wolfram Alpha for the specified term.

 $.when(Qwiery.searchAlpha('Coffee'))
    .then(function(results) {
       // Alpha specific JSON content here
    });

searchNews(term): array of search results

Searches news articles for the given term. This is the same as the searchWeb method with ‘News’ as source.

searchWikipedia(term): array of search results

Searches Wikipedia for the given term.

  $.when(Qwiery.searchWikipedia('commedia dell'arte'))
    .then(function(results) {
       // the results.Page will contain the main entry
       // additional pages are in results.Other
    });

Tags

Tags are in essence just labels (a string) which allows to bind entities belonging together. Usually tags are used to group semantically related items. A tag is not bound to a workspace and unrelated to the security context of a workspace. Workspaces and tags are similar to categories and tags in content management systems (e.g. WordPress).

Qwiery has some predefined tags; People, Addresses, Thoughts, Tasks and nore. The Favorites tag is another predefined tag which can be used in client developments to keep some often used entities close at hand. Methods like getAngenda, getAddresses and such reflect the predefined tags but are just shortcuts to the more generic getTagEntities method. Similarly makeFavorite is a special case of the tagEntity method.

getAgenda(from, to): array of appointments

Fetches your agend within the the given window. If none specified the whole collection of appointments will be returned.

Qwiery.ask("Tomorrow to Finland").then(function(answer) {
    Qwiery.getAgenda().then(function(){
       var found = _.find(agenda, {Title: "to Finland"});
    });
});

getTaks(): array of tasks

Returns your tasks, i.e. the entities of type Task.

  Qwiery.("add task: repair bicyle").then(function(answer) {
      Qwiery.getTasks().then(
      function(tasks){
         var found = _.find(tasks, {Title: taskName});
      }
      );
  });

getAddresses

Returns the entities with DataType ‘Address’.

getPeople

Returns the entities with DataType ‘Person’.

getThoughts

Returns the entities with DataType ‘Thought’.

getTagEntities(tagName)

Gets the entities having the specified tag name.

getTags

Gets all the tags of the user. This consists of the predefined tags (people, favorites, tasks and such) and the user defined tags.

The following is taken for instance from the default HTML client:

 $.when(Qwiery.getFavorites(), Qwiery.getTags()).then(function(f, t) {
        var favs = f[0];
        var tags = t[0];
        for(var k = 0; k < favs.length; k++) {
            var fav = favs[k];
            var item = {
                Id: fav.Id,
                Title: fav.Title,
                IsEntity: true,
                DataType: fav.DataType || "Entity",
                IsFavorite: true
            };
            that.favorites.push(item);
        }
        for(var k = 0; k < tags.length; k++) {
            var tag = tags[k];
            that.tags.push({
                Id: tag.Id,
                Title: tag.Title,
                IsEntity: true,
                Type: "Tag",
                IsFavorite: false
            })
        }
    });

makeFavorite(id)

Turns the entity with the given identifier into a favorite of the user.

unFavorite(id)

Removes the entity with the specified identifier as a favorite of the user.

getFavorites

Returns the favorite entities of the user.

isFavorite(id): bool

Returns true if the entity with the specified identifier is a favorite of the user.

tagEntity(id, tagName)

Tags the entity with the specified identifier with the given tag name. The tag will be created automatically if not already present.


Profile

The profile methods relate to the usage of the user, personality traits, history and alike. A user has full access to all the data Qwiery gathers and personalizations can be freely altered.

getTopics

Returns the topics of the user. These topics are induced from interactions with Qwiery.

 $.when(Qwiery.ask('Add topic: food'))
    .then(function() {
        $.when(Qwiery.getTopics())
            .then(function(topics) {
                var found = _.find(topics, function(r) {
                    return r.Type === 'food';
                });
            });
    });

getPersonalization

Returns the personalizations recorded for the user. The personalization are induced from interactions with Qwiery.

 Qwiery.ask("I like chocolate cake").then(function(answer) {
    Qwiery.getPersonalization("Like").then(function(value){
        // the value is 'chocolate cake'.
    });
});

clearAllPersonalization

Removes all the aquired personalizations. This means that Qwiery will again try to ask you certain things. For example, upon asking ‘what is the weather’ Qwiery will first ask again where you live in order to look up the weather. Once this personalization is known, Qwiery will use it onwards again.

clearPersonalization(key)

Removes a single personalization (key-value pair).

getPsy

Returns the psychological profile of the user. This is an MBTI scoring induced from interactions with Qwiery. You can read more about the MBTI classification here.

getPersonality

Returns statistics of the user’s personality. This is induced from interactions with Qwiery and is also related to the psychological profile. In a typical QTL you can alter the personality like so

{
  "Grab":"I don't care $1",
  "UserId":"Everyone",
  "Template":{"Answer": {"String":"What do you care about?"},
  "Think":{"Context":[{"Name":"Personality", "Value":"Arrogant"}]}}
  ...
}

The personality of a user is like the personalization just a simple key-value collection which can be used as input for a neural network or a mapping to something else (see the emotion module for instance).

getTrail

All interactions with Qwiery are historized and this methods returns the last ten interactions of your history. This method is useful for simple trails in the UI, it gives you:

  • the correlationId: this is a unique number of the interaction with Qwiery
  • the input: the question posted to Qwiery
  • the timestamp: the moment the input was received
  • the isEntity tells you whether the returned answer was a GraphDB entity
  • the nodeId contains the unique identifier if the isEntity is true
  • the title of the entity, if any
  • the data type of the entity, if any

If you need the full content of an history item you should use the getHistoryItem instead. This method should be requested with the correlationId and returns the full interaction envelope.

getUser

Returs the name and picture of the user, if available. This information is fetched from the user’s social profile or from explicit input of the user.

getStats

Returns statistics about the user’s usage of Qwiery.

getHistory(count): array of history items

Returns the interaction history of the user. The method only returns a set of properties, use the getHistoryItem to get the full envelope of the item. The properties returned are the same as the getTrail method. The array is order in descending order, the latest item being the first.

getHistoryItem(correlationId)

Returns the full session of an historical item.


Lexic

The lexic methods relate to natural language, question-answers, QTL… which are handle by the oracle module. The crucial ‘ask’ method is of course accessible with a valid API key but
the other methods need in addition admin privileges.

ask(question)

Asks Qwiery a question.

 $.when(Qwiery.ask("I like Japanese food")).then(function(session) {
    //the session.Output.Answer[0].Content
    // will contain somethin like 'I will remember this.'

    $.when(Qwiery.ask("What do I like")).then(function(dd) {
        //the dd.Output.Answer[0].Content will contain 
        // something like 
        //'You like chatting with me. You said you like Japanese food.'
    });
});

lexicUpsert(qtl)

Upserts a QTL entry of Qwiery.

var qtl = {
    Id: 5481,
    Grab: ["Question 1", "Question 2"],
    Category: "My stuff",
    Template: {
        Answer: "Yep, sure. No idea."
    }
};
Qwiery.learn(qtl);

lexicDelete(id)

Deletes a specific entry in Qwiery’s QTL brain.

lexicRandomRecord

Returns a random entry from Qwiery’s brain.

lexicRandomQuestion

Returns a random question or language template.

lexicExists(question)

Returns whether the lexic stack has an answer for the given question.

lexicValidate(template)

Returns whether the supplied QTL template is valid. Various checks are performed to ensured that the logic and content of the QTL works.


Files

The file/storage methods relate to the file-like data added to Qwiery by the user. Currently the file-upload is restricted to the default web-client for security reasons and to avoid abuse.

getFiles

Returns all the entities with DataType Image, Document or File.

getImages

Returns all the entities with DataType Image.

getDocuments

Returns all the entities with DataType Document.

getEntityRandomImage(id)

Returns a single random image attached to the entity with the specified identifier.

 $.when(Qwiery.getEntityRandomImage(entityId, ctx)).then(function(file) {
     // file.Title gives the name of the image or the file name
     // file.Source gives the URL of the image
  });

getEntityAllImages

Returns all images attached to the identity.


Utilities

randomId(length)

Returns a random identifier of the specified length. This identifier can be used for UI purposes (e.g. to set the Id of an HTML element).

guid

Returns a globally unique identifier. Note that the ‘uniqueness’ is however not as strict as generated by other language.

isDefined(object)

Returns true if the given object is not undefined and not null.

isUndefined(object)

Returns true if the given object is either null or undefined.


Admin

The methods in this category can only be used if you have admin privileges.

getAllUsers

Returns all registered users. Note that Qwiery does not store credentials, only pointers.

The following example makes use of a Kendo grid to display the users:

 Qwiery.getAllUsers()
        .then(function(data) {

            $("#grid").kendoGrid({
                dataSource: {
                    data: data,
                    pageSize: 10
                },
                columns: [
                    {field: "Username", title: "Username", width: "130px"},
                    {field: "CreationDate", title: "Created", width: "130px"},
                    {command: {text: "Delete", click: that.deleteUser}, title: " ", width: "140px"}
                ],
                pageable: true
                // dataBinding: function () { record = (this.dataSource.page() - 1) * this.dataSource.pageSize() - 1; }
            });

        })

globalUsage

This returns the amount of questions asked per day across all users.

The following example uses a Kendo chart to display the returned data:

 Qwiery.globalUsage()
        .then(function(data) {

            $("#chart") .kendoChart({
                title: {
                    text: "Global usage"
                },
                legend: {
                    visible: false
                },
                seriesDefaults: {
                    type: "column"
                },
                series: [{
                    name: "Question",
                    data: data,
                    field: "Weight",
                    overlay: {
                        gradient: "none"
                    },
                    categoryField: "Type"
                }]

            });

        })

deleteUser

Removes a user and all the data bound to the user (workspaces, entities, links, files….).

getStandardTopics

Utility method returning the standard topics.

getCategories

Utility method returning the categories.

feedback

Qwiery integrates a feedback system per session. This method allows to dump feedback about a particular session.

 Qwiery.feedback({
        User: UI.ticket.username + " [" + UI.ticket.id + "]",
        Category: category,
        Comments: comments,
        Object: session,
        Subject: "Qwiery feedback"
    });

By default the feedback will be stored as-is and a mail will be sent with the feedback (provided you have configured the mail server of course).