_
File size: 2,207 Bytes
9f09541
 
 
 
 
 
 
 
 
aa7f38f
 
 
 
 
 
9f09541
aa7f38f
 
 
 
 
 
 
 
063aa05
aa7f38f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77ad381
aa7f38f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59dc0ea
aa7f38f
 
 
2355991
aa7f38f
 
83cb46c
aa7f38f
2355991
aa7f38f
 
 
 
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
import os 
import gradio as gr
import datetime as dt
import pytz

from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()

# Get the api key from the environment variable
open_ai_api_key = os.environ.get("OPENAI_API_KEY")
if not open_ai_api_key:
    raise ValueError("OPENAI_API_KEY environment variable is not set")

#intialize openai client
client = OpenAI(api_key = os.environ.get("OPENAI_API_KEY"))

System_msg = "act as an experienced blockchain developer,you have been working in this field from the past 15 years.help me understand some concepts, assume i am a complete begineer"

ipAddress = None

def nowInISt():
    return dt.datetime.now(pytz.timezone("Asia/Kolkata"))

def attachIp(request = gr.Request):
    global ipAddress
    x_forwarded_for = request.headers.get("x-forwarded-for")
    if x_forwarded_for:
        ipAddress = x_forwarded_for

def pprint(log: str):
    now = nowInISt()
    now = now.strftime("%Y-%m-%d %H:%M:%S")
    print(f"[{now}] [{ipAddress}] {log}")

def predict(message,history):
    history_list = [{"role": "system", "content": System_msg}]
    for human,ai in history:
        history_list.append({"role": "user", "content": human})
        history_list.append({"role": "assistant", "content": ai})
    history_list.append({"role": "user", "content": message})

    response = client.chat.completions.create(
        model = "gpt-4o-mini",
        messages = history_list,
        temperature = 1.0,
        max_tokens=4000,
        stream = True   
    )

    partialMessage = ""
    chunkCount = 0
    for chunk in response:
        chunkContent = chunk.choices[0].delta.content
        if chunkContent:
            chunkCount+=1
            partialMessage= partialMessage + chunkContent
            yield partialMessage

    pprint(f"[tokens = {chunkCount}] {message}")        

with gr.ChatInterface(
    predict,
    title = "blockchain teacher",
    theme = gr.themes.Soft(),
    chatbot = gr.Chatbot(label ="learn about blochchain technology"),
    textbox = gr.Textbox(
         placeholder = "ask me anything about blochchain",
         scale = 7,
         max_lines = 2,
    ),
)  as demo:
     demo.load(attachIp,None,None)

demo.launch()