CanerCoban commited on
Commit
924d75b
·
verified ·
1 Parent(s): 6481477

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -58
app.py CHANGED
@@ -1,64 +1,79 @@
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
 
 
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
+ # Python's OS interface for accessing environment variables
2
+ import os
3
+ # Intropesction utilities, you can auto-wrap it as a tool later.
4
+ import inspect
5
+ # HTTP client, Make REST calls for endpoints
6
+ import requests
7
+ # Parses CSV/Excel files
8
+ import pandas as pd
9
+ # Gradio - Provides the web format front-end you see in the Space-text boxes, logs, "Run Agent" button etc.
10
  import gradio as gr
11
+ # smolagent - minimalist agent framework for LLMs with tools
12
+ # CodeAgent - Orchestrate ReAct loop, logs each step
13
+ # Tool - a base class and a decorator (@tool)
14
+ # InferenceClientModel - Wrapper for HF's Serverless Inference API so you dont need to stand up your own TGI/LLM endpoint
15
+ from smolagents import CodeAgent, DuckDuckGoSearchTool, Tool, InferenceClientModel
16
+ # Programmatic huggingface-cli login, so the app can: pull private models, call paid-tier inference, push artefacts
17
+ from huggingface_hub import login
18
+ # Quick helper to pull LangChain's built-in tools so you can blend them with smolagent tools if you wish.
19
+ from langchain.agents import load_tools
20
 
 
 
 
 
21
 
22
+ # Configuration constant
23
+ # Unit-4 scoring micro-services where your agent submits answers and receivess a JSON score.
24
+ # --- Constants
25
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
26
 
27
+ # --- Basic Agent Definition ---
28
+ # ---- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ----
29
+ class BasicAgent:
30
+ def __init__(self):
31
+ # Pull a HF access token from the Space's secrets or your local shell. You can download private models, call paid-tier Inference endpoints, push artefacts
32
+ hf_token = os.getenv("HUGGINGFACE_HUB_TOKEN") or os.getenv("HF_TOKEN")
33
+ # IF IT WORKS LOGIN INTO HF HUB VIA THIS TOKEN
34
+ if hf_token:
35
+ login(token=hf_token)
36
+ else:
37
+ try:
38
+ login()
39
+ except Exception as e:
40
+ raise Exception(
41
+ # helpful, course-style message
42
+ "Authentication failed. Please enter:\n"
43
+ "1. Run 'huggingface-cli login' in your terminal, or\n"
44
+ "2. Set HUGGINGFACE_HUB_TOKEN environment variable with your token, or\n"
45
+ "3. Get a token from https://huggingface.co/settings/tokens"
46
+ ) from e
47
+
48
+ # Warps the servesless inference endpoint for the chosen model
49
+ # Initialize the model
50
+ # InferenceClientModel handles throttling, batching, and streaming under the hood
51
+ self.model = InferenceClientModel("Qwen/Qwen2.5-Code-32B-Instruct")
52
+
53
+ # Add a first tool
54
+ # Initialize the search tool
55
+ # DuckDuckGoSearchTool - Gives the agent web-search super-powers it can pull fresh facts during its reasoning loop.
56
+ self.search_tool = DuckDuckGoSearchTool()
57
 
58
+ # smolagents's flagship class -
59
+ # Code Agent follows a ReAct-style loop, literally write Python code, executes it in a sandbox, inspects the result, then decides its next step
60
+ self.agent = CodeAgent(
61
+ model=self.model,
62
+ tools=[self.search_tool],
63
+ # drops in a small standard library (Python REPL, JSON loader etc.) so you can solve many tasks without defining anything else.
64
+ add_base_tools=True # - python_repl, browser, math etc.
65
+ )
66
 
67
+ # Send a single "bootstrap" run whose only job is lock in behaviour rules:
68
+ self.response = self.agent.run(
69
+ """
70
+ You are a general AI assistant.
71
+ I will ask you a question. Report your thoughts, and finish your answer with the following template: [FINAL ANSWER].
72
+ YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
73
+ If you are asked for a number, do not use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
74
+ If you are asked for a string, do not use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
75
+ If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
76
+ You have access to the following tools:
77
+ Tool Name: search_tool, description: lets you search and browse the internet for accessing the most updated information out there.
78
+ If you require more tools to get a correct answer, create your own tools to utilize.
79
+ """)