File size: 2,169 Bytes
90a9c4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Data Scientist.: Dr. Eddy Giusepe Chirinos Isidro 🤓

Link do Panel --> https://panel.holoviz.org/reference/chat/PanelCallbackHandler.html

Link do ANACONDA --> https://www.anaconda.com/blog/

Construa um chatbot de IA com tecnologia LangChain
==================================================
O Panel ChatInterface também se integra perfeitamente ao LangChain, aproveitando 
todo o espectro de recursos do LangChain. Aqui está um exemplo de como usamos 
LangChain 'ConversationChain' para armazenar mensagens com 'ConversationBufferMemory' 
e passar mensagens anteriores para a API OpenAI.

Observe que antes de mergulharmos no código LangChain, definimos 'callback_handler' 
porque a interface LangChain não tem como transmitir a partir de geradores, então 
precisamos agrupar a interface LangChain com 'pn.chat.langchain.PanelCallbackHandler', 
que herda de `langchain.callbacks.base.BaseCallbackHandler`. Para mais informações, veja
o link acima.

Executando este script
----------------------

$ panel serve 2_Building_a_ChatGPT-powered_AI_ChatBot.py 
"""
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory

import panel as pn

pn.extension()

# Substitua sua chave de API OpenAI:
import openai
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key  = os.environ['OPENAI_API_KEY']


async def callback(contents: str, user: str, instance: pn.chat.ChatInterface):
    await chain.apredict(input=contents)

chat_interface = pn.chat.ChatInterface(callback=callback, callback_user="ChatGPT")
callback_handler = pn.chat.langchain.PanelCallbackHandler(chat_interface)

llm = ChatOpenAI(streaming=True,
                 callbacks=[callback_handler],
                 model="gpt-3.5-turbo",
                 temperature=0.0,
                 verbose=True
                )

memory = ConversationBufferMemory()
chain = ConversationChain(llm=llm, memory=memory)

chat_interface.send("Envie uma mensagem para obter uma resposta do ChatGPT!", user="System", respond=False)
chat_interface.servable()