Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
<html>
<head>
<title>API Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var accessToken = "<your agent's client access token>";
var baseUrl = "https://api.api.ai/v1/";
$(document).ready(function() {
$("#input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
send();
}
});
$("#rec").click(function(event) {
switchRecognition();
});
});
var recognition;
function startRecognition() {
recognition = new webkitSpeechRecognition();
recognition.onstart = function(event) {
updateRec();
};
recognition.onresult = function(event) {
var text = "";
for (var i = event.resultIndex; i < event.results.length; ++i) {
text += event.results[i][0].transcript;
}
setInput(text);
stopRecognition();
};
recognition.onend = function() {
stopRecognition();
};
recognition.lang = "en-US";
recognition.start();
}
function stopRecognition() {
if (recognition) {
recognition.stop();
recognition = null;
}
updateRec();
}
function switchRecognition() {
if (recognition) {
stopRecognition();
} else {
startRecognition();
}
}
function setInput(text) {
$("#input").val(text);
send();
}
function updateRec() {
$("#rec").text(recognition ? "Stop" : "Speak");
}
function send() {
var text = $("#input").val();
$.ajax({
type: "POST",
url: baseUrl + "query?v=20150910",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
success: function(data) {
setResponse(JSON.stringify(data, undefined, 2));
},
error: function() {
setResponse("Internal Server Error");
}
});
setResponse("Loading...");
}
function setResponse(val) {
$("#response").text(val);
}
</script>
<style type="text/css">
body { width: 500px; margin: 0 auto; text-align: center; margin-top: 20px; }
div { position: absolute; }
input { width: 400px; }
button { width: 50px; }
textarea { width: 100%; }
</style>
</head>
<body>
<div>
<input id="input" type="text"> <button id="rec">Speak</button>
<br>Response<br> <textarea id="response" cols="40" rows="20"></textarea>
</div>
</body>
</html>

This isn't working for me. It says Internal Server Error.

It is not working. It says Internal Server Error.
If we see Browser Network log, Each POST request to API returning two responses.
One with code 204 (empty response) and another is 200 (JSON response)
screen

Owner

Gugic commented Dec 8, 2016

@bipulraman, @jib123456 - can you check it now? Just copy to my local machine and execute with my access token.

Worked well here. Thanks Gugic.
ai2

Hi!

To add speech response add the following piece of code to function setResponse(), and let synth be a global var.

Also do not JSON.stringify() in function send():success, do this in function setResponse() so that val for the below is an Object.

Also test your sound, e.g. ensure sound is not muted on computer.

Works in Chrome:

            if (val.result) {
                var say=""; 
                say = val.result.fulfillment.speech;
                
                synth = window.speechSynthesis;
                var utterThis = new SpeechSynthesisUtterance(say);
                //utterThis.lang = "en-US";
                synth.speak(utterThis);
            }

A-Guidry commented Jan 1, 2017 edited

I am getting a 401 error and the "internal server message" I have tried everything I can think of to allow it connect.
screen shot 2017-01-01 at 1 38 15 pm

ankitch01 commented Jan 9, 2017 edited

Copy the client access token and paste it in your html code .. check attached screenshot for reference.

image

mepower2 commented Mar 8, 2017

Could someone please explain the updateRec function and how it works?

I have also getting JSON Respond. How I can use only reply from that format
{
"id": "0ed65683-64b3-41eb-990b-4d1f2b6606e7",
"timestamp": "2017-03-11T20:24:21.693Z",
"result": {
"source": "domains",
"resolvedQuery": "Hi",
"action": "smalltalk.greetings",
"parameters": {
"simplified": "hello"
},
"metadata": {},
"fulfillment": {
"speech": "Howdy."
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success"
},
"sessionId": "somerandomthing"
}

SABTECH commented Mar 26, 2017

i have copied my client access token to the HTML code but still, it doesn't run

betagoro commented Apr 27, 2017 edited

Remove this symbol < from client token, and tadaaaaaaaa....
Put only number at this way ===>> "99999999999999"

supprix commented Apr 28, 2017

How it running in mobile application iOS or android?

It works like a charm!
Just find accessToken in the example code and put the Client Access token.

image

isn't there a version 2 already? I tried updating this part

var baseUrl TO = "https://api.api.ai/v2/";

But doesn't seem to work

Works perfectly for me. Can anyone help with -

  1. Making it work in Android native browser. If there are any particular dependencies, setting requests etc. Ill be running it in the webview
  2. Train the agent on proper nouns. Do I specify entities,

@panconjugo: It seems one can use:

var baseUrl = "https://api.api.ai/api/";

Can you please tell me how to set only the result of the bot's speech in the response section and not the entire json code.
I tried to make the folowing change in the exisiting code but it didnt help.

var debugJSON = JSON.stringify(val, undefined, 2),
spokenResponse = val.result.speech;
setResponse(spokenResponse);

thnks in advance

SOLUTION TO GET THE SPEECH VALUE FROM THE JSON:

function send() {
			var text = $("#input").val();
			$.ajax({
				type: "POST",
				url: baseUrl + "query?v=20150910",
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				headers: {
					"Authorization": "Bearer " + accessToken
				},
				data: JSON.stringify({ query: text, lang: "en", sessionId: "somerandomthing" }),
				success: function(data) {
					var respText = data.result.fulfillment.speech;
					console.log("Respuesta: " + respText);
					setResponse(respText);
				},
				error: function() {
					setResponse("Internal Server Error");
				}
			});
			setResponse("Thinking...");
		}

how can get text response instead of json

what should I write in base URL?

boegi commented Jul 24, 2017

@SachinNarkhede see the solution from PatricioJulian (Works like a charm)
@nikhil-1337 see the solution from SinanGabel

#var baseUrl = "https://api.api.ai/api/";**

Application responds successfully in chat , My concern is "How to use other intents like web search and map location , navigation etc ". I had added web search, map intents but i get empty responses. I would like to know how application will respond on browser or map instead empty responses or successful json. plz help with the coding

gitdana commented Aug 9, 2017

i want immediate help??

gitdana commented Aug 9, 2017

when the page loading microphone automatically blocked ? what the reason for that ? i changed access settings and all but issue is occur .

Hi @gitdana it's because it needs a http server up and running to up and run with the microphone simply add a nodejs server and it will notblock microphone and will run with http protocol so it's done

hello
please urgent
how can I get the messages I send appear in the discussion with the bot

Towerss commented Aug 18, 2017

@jbakoume, to have a chat-alike version you need to start by implementing @PatricioJulian solution to extract from the JSON reply only the answer. This is a simple approach:

  1. Create an array var conversation = [];
  2. Add conversation.push("Me: " + text + '\r\n'); just before var text = $("#input").val(); to store your query.
  3. Comment or delete setResponse("Loading...");
  4. In setResponse(val) function add conversation.push("AI: " + val + '\r\n'); at the top.
  5. Finally modify the printing method with $("#response").text(asked.join(""));

untitled

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment