-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathreplace-knowledge-base.py
More file actions
86 lines (76 loc) · 2.55 KB
/
Copy pathreplace-knowledge-base.py
File metadata and controls
86 lines (76 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# -*- coding: utf-8 -*-
import http.client, urllib.parse, json, time
# **********************************************
# *** Update or verify the following values. ***
# **********************************************
# Replace this with a valid subscription key.
subscriptionKey = 'ENTER KEY HERE'
# Replace this with a valid knowledge base ID.
kb = 'ENTER ID HERE';
# Represents the various elements used to create HTTP request path
# for QnA Maker operations.
host = 'westus.api.cognitive.microsoft.com'
service = '/qnamaker/v4.0'
method = '/knowledgebases/'
'''
Formats and indents JSON for display.
:param content: The JSON to format and indent.
:type: string
:return: Formatted and indented JSON.
:rtype: string
'''
def pretty_print (content):
# Note: We convert content to and from an object so we can pretty-print it.
return json.dumps(json.loads(content), indent=4)
'''
Sends a PUT HTTP request, to replace the knowledge base.
:param path: The URL path of your request.
:param content: The contents of your PUT request.
:type: string
:return: Status of PUT request in replacing the kb.
:rtype: HTTPResponse
'''
def replace_kb (path, content):
print ('Calling ' + host + path + '.')
headers = {
'Ocp-Apim-Subscription-Key': subscriptionKey,
'Content-Type': 'application/json',
'Content-Length': len (content)
}
conn = http.client.HTTPSConnection(host)
conn.request ("PUT", path, content, headers)
response = conn.getresponse ()
if response.status == 204:
return json.dumps({'result' : 'Success.'})
else:
return response.read ()
'''
Dictionary that holds the knowledge base.
Modifications to the knowledge base are made here, replacing its existing QnA pairs.
'''
req = {
'qnaList': [
{
'id': 0,
'answer': 'You can use our REST APIs to manage your Knowledge Base. See here for details: https://westus.dev.cognitive.microsoft.com/docs/services/5a93fcf85b4ccd136866eb37/operations/5ac266295b4ccd1554da7600',
'source': 'Custom Editorial',
'questions': [
'How do I programmatically update my Knowledge Base?'
],
'metadata': [
{
'name': 'category',
'value': 'api'
}
]
}
]
}
# Builds the path URL.
path = service + method + kb
# Convert the request to a string.
content = json.dumps(req)
# Replaces knowledge base
result = replace_kb (path, content)
# Print request response in JSON with presentable formatting.
print (pretty_print(result))