Spaces:
Sleeping
Sleeping
File size: 2,604 Bytes
8664eb4 | 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 87 88 89 | import os
from openai import AzureOpenAI
import gradio
from elasticsearch import Elasticsearch
def pretty_response_sc(response):
output_list = [] # List to store formatted output
if len(response["hits"]["hits"]) == 0:
print("Your search returned no results.")
return None
else:
for hit in response["hits"]["hits"]:
id = hit["_id"]
text = hit["_source"]["my_text"]
pretty_output = f"\nID: {id}\ntext: {text}\n"
output_list.append(pretty_output)
return pretty_output
#establish connection to elastic search
es = Elasticsearch(
"https://c707e4d7afe245f895c68fa94429da20.us-central1.gcp.cloud.es.io:443",
api_key="M213RVZJOEJVQmxvUlZjVkxzaEw6eUNFMG83Q0hTSC01NW84TThCXzdFZw==")
#model for embedding text
from sentence_transformers import SentenceTransformer,util
model = SentenceTransformer('all-mpnet-base-v2')
#set up openai llm
client = AzureOpenAI(
api_key = '8a9cfaa2e2fd4de7a84a134528bfc726',
api_version = "2024-02-01",
azure_endpoint = 'https://openai-datafabric-dev-001.openai.azure.com/'
)
prompt="Enter your query here"
def api_calling(prompt):
response = es.search(
index="test",
body={"query": {
"match": {
"my_text": prompt
}
},
"size": 1})
context=pretty_response_sc(response)
llm_response = client.chat.completions.create(
model="gpt-35-turbo", # model = "deployment_name".
messages=[
{"role": "system", "content": "you are an assistant who will answer the user's question"},
{"role": "user", "content": f"based on the context delimted by triple ticks answer the query:{prompt} \
context:```{context}. if you are not sure ,just say you dont know the answer"}
])
return llm_response.choices[0].message.content
def message_and_history(input, history):
history = history or []
s = list(sum(history, ()))
s.append(input)
inp = ' '.join(s)
output = api_calling(inp)
history.append((input, output))
return history, history
block = gradio.Blocks(theme=gradio.themes.Monochrome())
with block:
gradio.Markdown("""<h1><center>ChatGPT
ChatBot with Gradio and OpenAI</center></h1>
""")
chatbot = gradio.Chatbot()
message = gradio.Textbox(placeholder=prompt)
state = gradio.State()
submit = gradio.Button("SEND")
submit.click(message_and_history,
inputs=[message, state],
outputs=[chatbot, state])
block.launch(debug = True)
|