The Glean Chat API is a powerful tool for integrating conversational AI into your products. It allows you to create custom conversational interfaces that leverage Glean’s AI capabilities. This page provides examples of how to use the Chat API to integrate conversational AI into your products.
curl'https://<your-domain>-be.glean.com/rest/api/v1/chat'\-H'Content-Type: application/json'\-H'Authorization: Bearer <TOKEN>'\-d '{"stream": false,"messages":[{"author":"USER","fragments":[{"text":"What are the holidays this year?"}]}]}'
Note: The following example streams the output as it becomes available, whenever possible. To turn off streaming outputs, please set the stream field in the request body to False
import requestsimport jsondefprocess_message_fragment(message): message_type = message['messageType'] fragments = message.get('fragments',[]) citations = message.get('citations',[]) message_fragment_str =''if message_type =='CONTENT':if fragments:for fragment in fragments: text = fragment.get('text','')print(text, end='', flush=True)if citations:print('\nSources:')for idx, citation inenumerate(citations): sourceDocument = citation.get('sourceDocument',{})if sourceDocument: source = citation['sourceDocument']print(f'Source {idx +1}: Document title - {source["title"]}, url: {source["url"]}') sourcePerson = citation.get('sourcePerson',{})if sourcePerson: source = citation['sourcePerson']print(f'Source {idx +1}: Person name - {source["name"]}')defprocess_response_message_stream(response):for line in response.iter_lines():if line: line_json = json.loads(line) messages = line_json.get('messages',[])for message in messages: process_message_fragment(message)defmain(): url ='https://<your-domain>-be.glean.com/rest/api/v1/chat' headers ={'Content-Type':'application/json','Authorization':'Bearer <TOKEN>'} data ={'stream':True,# Set to False to toggle off streaming mode'messages':[{'author':'USER','fragments':[{'text':'What are the holidays this year?'}]}],}try:with requests.post(url, headers=headers, json=data, stream=True)as response:if response.status_code ==200: process_response_message_stream(response)else:print(f'Status code: {response.status_code}, error: {response.text}') exit(1)except requests.exceptions.RequestException as e:print(f'Request Exception: {str(e)}') exit(1)if __name__ =='__main__': main()