File size: 3,398 Bytes
71e5459
 
 
 
3df06f1
71e5459
 
35a1c5d
71e5459
 
3df06f1
71e5459
 
d9e01bd
 
71e5459
b2c7c29
 
d9e01bd
71e5459
 
d9e01bd
 
71e5459
 
 
 
d9e01bd
71e5459
d9e01bd
71e5459
d35962e
 
 
 
 
d0293b0
d35962e
 
 
 
 
 
d9e01bd
ce46abb
d35962e
d9e01bd
 
 
d35962e
d9e01bd
d35962e
 
 
 
 
71e5459
d35962e
 
71e5459
 
 
 
 
 
 
 
d9e01bd
71e5459
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9e01bd
71e5459
 
 
 
 
 
 
 
d9e01bd
 
71e5459
 
 
 
 
 
 
d9e01bd
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
104
105
106
107
108
109
110
111
import os
from typing import Optional, Tuple

import gradio as gr
from langchain.agents import create_pandas_dataframe_agent
from langchain.llms import Anthropic
import pandas as pd
from threading import Lock

def load_data():
    """Load the data you want to use for the agent."""
    return pd.read_parquet("data/part.17.parquet")

def load_chain():
    """Logic for loading the chain you want to use should go here."""
    llm = Anthropic(temperature=0)
    trans = load_data()
    chain = create_pandas_dataframe_agent(llm, trans)
    return chain

def set_anthropic_api_key(api_key: str):
    """Set the api key and return chain.

    If no api_key, then None is returned.
    """
    if api_key:
        os.environ["ANTHROPIC_API_KEY"] = api_key
        chain = load_chain()
        os.environ["ANTHROPIC_API_KEY"] = ""
        return chain

class ChatWrapper:

    def __init__(self):
        self.lock = Lock()
    def __call__(
        self, api_key: str, inp: str, history: Optional[Tuple[str, str]], chain: Optional[create_pandas_dataframe_agent]
    ):
        """Execute the chat functionality."""
        self.lock.acquire()
        try:
            history = history or []
            # If chain is None, that is because no API key was provided.
            if chain is None:
                history.append((inp, "Please paste your anthropic key to use"))
                return history, history
            # Set anthropic key
            import anthropic
            anthropic.api_key = api_key
            # Run chain and append input.
            output = chain.run(input=inp)
            history.append((inp, output))
        except Exception as e:
            raise e
        finally:
            self.lock.release()
        return history, history

chat = ChatWrapper()

block = gr.Blocks(css=".gradio-container {background-color: lightgray}")

with block:
    with gr.Row():
        gr.Markdown("<h3><center>LangChain Demo</center></h3>")

        anthropic_api_key_textbox = gr.Textbox(
            placeholder="Paste your anthropic API key (sk-...)",
            show_label=False,
            lines=1,
            type="password",
        )

    chatbot = gr.Chatbot()

    with gr.Row():
        message = gr.Textbox(
            label="What's your question?",
            placeholder="What was the average gas price on 2019-01-22?",
            lines=1,
        )
        submit = gr.Button(value="Send", variant="secondary").style(full_width=False)

    gr.Examples(
        examples=[
            "Which to_address spent the most gas?",
            "What was the average gas price on 2019-01-22?",
            "How many unique addresses were sending transactions on 2019-01-22?",
        ],
        inputs=message,
    )

    gr.HTML("Demo application of a LangChain chain.")

    gr.HTML(
        "<center>Powered by <a href='https://github.com/hwchase17/langchain'>LangChain 🦜️🔗</a></center>"
    )

    state = gr.State()
    agent_state = gr.State()

    submit.click(chat, inputs=[anthropic_api_key_textbox, message, state, agent_state], outputs=[chatbot, state])
    message.submit(chat, inputs=[anthropic_api_key_textbox, message, state, agent_state], outputs=[chatbot, state])

    anthropic_api_key_textbox.change(
        set_anthropic_api_key,
        inputs=[anthropic_api_key_textbox],
        outputs=[agent_state],
    )

block.launch(debug=True)