File size: 5,102 Bytes
03fe87d 6bfcb60 c98ce10 03fe87d 6bfcb60 bd055b1 6bfcb60 a0b1f51 ab79a5f 6bfcb60 b986d7f 6bfcb60 03fe87d 6bfcb60 03fe87d 6bfcb60 03fe87d 6bfcb60 339ef8e cd53515 6bfcb60 b978731 9ea7c0c 64762cf a0b1f51 30f4ce1 a0b1f51 82867da 30f4ce1 6bfcb60 82867da |
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 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
import os
import json
import bcrypt
import chainlit as cl
from chainlit.input_widget import TextInput, Select, Switch, Slider
from chainlit import user_session
from literalai import LiteralClient
literal_client = LiteralClient(api_key=os.getenv("LITERAL_API_KEY"))
from operator import itemgetter
from pinecone import Pinecone
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_community.llms import HuggingFaceEndpoint
from langchain.memory import ConversationBufferMemory
from langchain.schema import StrOutputParser
from langchain.schema.runnable import Runnable
from langchain.schema.runnable.config import RunnableConfig
from langchain.schema.runnable import Runnable, RunnablePassthrough, RunnableLambda
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.prompts import PromptTemplate
@cl.password_auth_callback
def auth_callback(username: str, password: str):
auth = json.loads(os.environ['CHAINLIT_AUTH_LOGIN'])
ident = next(d['ident'] for d in auth if d['ident'] == username)
pwd = next(d['pwd'] for d in auth if d['ident'] == username)
resultLogAdmin = bcrypt.checkpw(username.encode('utf-8'), bcrypt.hashpw(ident.encode('utf-8'), bcrypt.gensalt()))
resultPwdAdmin = bcrypt.checkpw(password.encode('utf-8'), bcrypt.hashpw(pwd.encode('utf-8'), bcrypt.gensalt()))
resultRole = next(d['role'] for d in auth if d['ident'] == username)
if resultLogAdmin and resultPwdAdmin and resultRole == "admindatapcc":
return cl.User(
identifier=ident + " : 🧑💼 Admin Datapcc", metadata={"role": "admin", "provider": "credentials"}
)
elif resultLogAdmin and resultPwdAdmin and resultRole == "userdatapcc":
return cl.User(
identifier=ident + " : 🧑🎓 User Datapcc", metadata={"role": "user", "provider": "credentials"}
)
@cl.author_rename
def rename(orig_author: str):
rename_dict = {"LLMMathChain": "Albert Einstein", "Doc Chain Assistant": "Assistant Reviewstream"}
return rename_dict.get(orig_author, orig_author)
@cl.set_chat_profiles
async def chat_profile():
return [
cl.ChatProfile(name="Reviewstream",markdown_description="Requêter sur les publications de recherche",icon="/public/logo-ofipe.jpg",),
cl.ChatProfile(name="Imagestream",markdown_description="Requêter sur un ensemble d'images",icon="./public/logo-ofipe.jpg",),
]
@cl.on_chat_start
async def on_chat_start():
await cl.Message(f"> REVIEWSTREAM").send()
await cl.Message(f"Nous avons le plaisir de vous accueillir dans l'application de recherche et d'analyse des publications.").send()
listPrompts_name = f"Liste des revues de recherche"
contentPrompts = """<p><img src='/public/hal-logo-header.png' width='32' align='absmiddle' /> <strong> Hal Archives Ouvertes</strong> : Une archive ouverte est un réservoir numérique contenant des documents issus de la recherche scientifique, généralement déposés par leurs auteurs, et permettant au grand public d'y accéder gratuitement et sans contraintes.
</p>
<p><img src='/public/logo-persee.png' width='32' align='absmiddle' /> <strong>Persée</strong> : offre un accès libre et gratuit à des collections complètes de publications scientifiques (revues, livres, actes de colloques, publications en série, sources primaires, etc.) associé à une gamme d'outils de recherche et d'exploitation.</p>
"""
prompt_elements = []
prompt_elements.append(
cl.Text(content=contentPrompts, name=listPrompts_name, display="side")
)
await cl.Message(content="📚 " + listPrompts_name, elements=prompt_elements).send()
settings = await cl.ChatSettings(
[
Select(
id="Model",
label="Publications de recherche",
values=["---", "HAL", "Persée"],
initial_index=0,
),
]
).send()
@cl.on_message
async def main(message: cl.Message):
os.environ['PINECONE_API_KEY'] = os.environ['PINECONE_API_KEY']
embeddings = HuggingFaceEmbeddings()
index_name = "all-venus"
pc = Pinecone(
api_key=os.environ['PINECONE_API_KEY']
)
index = pc.Index(index_name)
xq = embeddings.embed_query(message.content)
xc = index.query(vector=xq, filter={"categorie": {"$eq": "bibliographie-OPP-DGDIN"}},top_k=150, include_metadata=True)
context_p = ""
for result in xc['matches']:
context_p = context_p + result['metadata']['text']
memory = cl.user_session.get("memory")
runnable = cl.user_session.get("runnable")
msg = cl.Message(author="Assistant Reviewstream",content="")
async for chunk in runnable.astream({"question": message.content, "context":context_p},
config=RunnableConfig(callbacks=[cl.AsyncLangchainCallbackHandler(stream_final_answer=True)])):
await msg.stream_token(chunk)
await msg.send()
memory.chat_memory.add_user_message(message.content)
memory.chat_memory.add_ai_message(msg.content) |