CoolFace
Apppublic

RohitKeswani/react_agent

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
app.py96 linesDownload Raw Back to root
1import gradio as gr2import os3from huggingface_hub import InferenceClient4from langgraph.prebuilt import create_react_agent5from search_agent import tools6from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint7from search_agent import tools8from langchain_core.messages import HumanMessage, AIMessage, SystemMessage9huggingfacehub_api_token = os.getenv('hf_api')10 11"""12For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference13"""14# client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")15llm = HuggingFaceEndpoint(16    repo_id="meta-llama/Llama-3.2-1B-Instruct"  ,17    huggingfacehub_api_token=huggingfacehub_api_token,18)19 20chat_model = ChatHuggingFace(llm=llm, verbose =  True)21graph = create_react_agent(chat_model, tools=tools)22 23 24def respond(25    message,26    history: list[tuple[str, str]],27    system_message,28    max_tokens,29    temperature,30    top_p,31):32    messages = [{"role": "system", "content": system_message}]33 34    for val in history:35        if val[0]:36            messages.append({"role": "user", "content": val[0]})37        if val[1]:38            messages.append({"role": "assistant", "content": val[1]})39 40    messages.append({"role": "user", "content": message})41 42    # response = ""43 44    # for message in client.chat_completion(45    #     messages,46    #     max_tokens=max_tokens,47    #     stream=True,48    #     temperature=temperature,49    #     top_p=top_p,50    # ):51    #     token = message.choices[0].delta.content52 53    #     response += token54    #     yield response55    def convert(msg):56        if msg["role"] in ["user", "human"]:57            return HumanMessage(content=msg["content"])58        elif msg["role"] in ["assistant", "ai"]:59            return AIMessage(content=msg["content"])60        elif msg["role"] == "system":61            return SystemMessage(content=msg["content"])62        else:63            raise ValueError(f"Unsupported role: {msg['role']}")64        65    inputs = {"messages": [convert(m) for m in messages]}66    67    # Get the response from the agent (this integrates your agent with the model)68    agent_response = graph.invoke(inputs)  # Process the inputs through your agent69    70    # Return the final message from the agent71    return agent_response['messages'][-1][1]72 73 74"""75For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface76"""77demo = gr.ChatInterface(78    respond,79    additional_inputs=[80        gr.Textbox(value="You are a friendly Chatbot.", label="System message"),81        gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),82        gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),83        gr.Slider(84            minimum=0.1,85            maximum=1.0,86            value=0.95,87            step=0.05,88            label="Top-p (nucleus sampling)",89        ),90    ],91)92 93 94if __name__ == "__main__":95    demo.launch()96