File size: 1,826 Bytes
7aa2ccc
b34f2eb
 
 
7aa2ccc
 
b34f2eb
7aa2ccc
 
b34f2eb
 
 
 
 
 
 
7aa2ccc
 
b34f2eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7aa2ccc
 
b34f2eb
7aa2ccc
b34f2eb
 
7aa2ccc
b34f2eb
 
 
7aa2ccc
 
b34f2eb
 
 
 
7aa2ccc
 
b34f2eb
7aa2ccc
 
 
b34f2eb
 
 
 
 
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
import gradio as gr
from langchain_community.agent_toolkits.load_tools import load_tools
from langchain.agents import initialize_agent, AgentType
from langchain_openai import ChatOpenAI
import warnings

warnings.filterwarnings("ignore", message=".*TqdmWarning.*")


# ----------------------
# Chatbot function
# ----------------------
def chatbot(api_key: str, query: str) -> str:
    """Handles user query and returns agent response using the provided API key."""
    if not api_key.strip():
        return "⚠️ Please enter a valid OpenAI API key."

    try:
        # Initialize model with user-provided key
        llm_model = "gpt-3.5-turbo"
        llm = ChatOpenAI(temperature=0, model=llm_model, openai_api_key=api_key)

        # Load tools
        tools = load_tools(["llm-math", "wikipedia"], llm=llm)

        # Initialize agent
        agent = initialize_agent(
            tools,
            llm,
            agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
            handle_parsing_errors=True,
            verbose=True
        )

        # Run the query
        response = agent.run(query)
        return response

    except Exception as e:
        return f"❌ Error: {str(e)}"


# ----------------------
# Gradio Interface
# ----------------------
demo = gr.Interface(
    fn=chatbot,
    inputs=[
        gr.Textbox(label="πŸ”‘ OpenAI API Key", type="password", placeholder="Paste your API key here..."),
        gr.Textbox(label="Your Question", placeholder="Ask me anything...")
    ],
    outputs=gr.Textbox(label="Response"),
    title="LangChain AI Chatbot",
    description="Enter your OpenAI API key and ask me anything! Powered by OpenAI and LangChain.",
    theme="compact"
)

# ----------------------
# Launch
# ----------------------
if __name__ == "__main__":
    demo.launch(share=True)