nurasaki commited on
Commit
570b60c
·
1 Parent(s): 4c38df2

Created first Gradio Space (MVP)

Browse files
Files changed (10) hide show
  1. .gitattributes +1 -0
  2. .gitignore +6 -0
  3. README.md +9 -5
  4. app.py +142 -0
  5. config.yaml +26 -0
  6. data/vdb/index.faiss +3 -0
  7. data/vdb/index.pkl +3 -0
  8. requirements.txt +9 -0
  9. src/tools.py +123 -0
  10. src/vectorstore.py +83 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.faiss filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ venv/
2
+ .env
3
+ __pycache__
4
+ .qodo
5
+ .DS_Store
6
+ *nogit*
README.md CHANGED
@@ -1,12 +1,16 @@
1
  ---
2
  title: Aina RAG
3
- emoji: 🚀
4
- colorFrom: indigo
5
- colorTo: purple
6
  sdk: gradio
7
- sdk_version: 5.45.0
8
  app_file: app.py
9
  pinned: false
 
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
1
  ---
2
  title: Aina RAG
3
+ emoji: 🐡
4
+ colorFrom: purple
5
+ colorTo: blue
6
  sdk: gradio
7
+ sdk_version: 5.28.0
8
  app_file: app.py
9
  pinned: false
10
+ license: apache-2.0
11
+ short_description: Conversational space enhanced for Aina Challenge
12
  ---
13
 
14
+ # Aina Challenge
15
+
16
+ An example chatbot using [Gradio](https://gradio.app), [`huggingface_hub`](https://huggingface.co/docs/huggingface_hub/v0.22.2/en/index), and the [Hugging Face Inference API](https://huggingface.co/docs/api-inference/index).
app.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+
3
+
4
+ import gradio as gr
5
+ from gradio import ChatMessage
6
+
7
+ import json
8
+ from openai import OpenAI
9
+ from datetime import datetime
10
+ import os
11
+ import re
12
+
13
+ from termcolor import cprint
14
+ import logging
15
+ logging.basicConfig(level=logging.INFO, format='[%(asctime)s][%(name)s][%(levelname)s] - %(message)s')
16
+ log = logging.getLogger(__name__)
17
+
18
+
19
+
20
+ from omegaconf import OmegaConf
21
+ from src.tools import tools, oitools
22
+
23
+
24
+ # Load the configuration file
25
+ # ===========================================================================
26
+ # Environment variables
27
+ load_dotenv(".env", override=True)
28
+ HF_TOKEN = os.environ.get("HF_TOKEN")
29
+ LLM_BASE_URL = os.environ.get("LLM_BASE_URL")
30
+
31
+ log.info(f"Using HF_TOKEN: {HF_TOKEN[:4]}...{HF_TOKEN[-4:]}")
32
+ log.info(f"Using LLM_BASE_URL: {LLM_BASE_URL[:10]}...{LLM_BASE_URL[-10:]}")
33
+
34
+ # Configuration file
35
+ config_file = "config.yaml"
36
+ cfg = OmegaConf.load(config_file)
37
+
38
+ # OpenAI API parameters
39
+ chat_params = cfg.openai.chat_params
40
+ client = OpenAI(
41
+ base_url=f"{LLM_BASE_URL}",
42
+ api_key=HF_TOKEN
43
+ )
44
+ logging.info(f"Client initialized: {client}")
45
+ # ===========================================================================
46
+
47
+
48
+ def today_date():
49
+ return datetime.today().strftime('%A, %B %d, %Y, %I:%M %p')
50
+
51
+
52
+ def clean_json_string(json_str):
53
+ return re.sub(r'[ ,}\s]+$', '', json_str) + '}'
54
+
55
+
56
+ def completion(history, model, system_prompt: str, tools=None, chat_params=chat_params):
57
+ messages = [{"role": "system", "content": system_prompt.format(date=today_date())}]
58
+ for msg in history:
59
+ if isinstance(msg, dict):
60
+ msg = ChatMessage(**msg)
61
+ if msg.role == "assistant" and hasattr(msg, "metadata") and msg.metadata:
62
+ tools_calls = json.loads(msg.metadata.get("title", "[]"))
63
+ messages.append({"role": "assistant", "tool_calls": tools_calls, "content": ""})
64
+ messages.append({"role": "tool", "content": msg.content})
65
+ else:
66
+ messages.append({"role": msg.role, "content": msg.content})
67
+
68
+ request_params = {
69
+ "model": model,
70
+ "messages": messages,
71
+ **chat_params
72
+ }
73
+ if tools:
74
+ request_params.update({"tool_choice": "auto", "tools": tools})
75
+
76
+
77
+ return client.chat.completions.create(**request_params)
78
+
79
+
80
+ def llm_in_loop(history, system_prompt, recursive):
81
+
82
+ try:
83
+ models = client.models.list()
84
+ model = models.data[0].id
85
+ except Exception as err:
86
+ gr.Warning("The model is initializing. Please wait; this may take 5 to 10 minutes ⏳.", duration=20)
87
+ raise err
88
+
89
+ arguments = ""
90
+ name = ""
91
+ chat_completion = completion(history=history, tools=oitools, model=model, system_prompt=system_prompt)
92
+ appended = False
93
+
94
+
95
+ for chunk in chat_completion:
96
+ if chunk.choices and chunk.choices[0].delta.tool_calls:
97
+ call = chunk.choices[0].delta.tool_calls[0]
98
+ if hasattr(call.function, "name") and call.function.name:
99
+ name = call.function.name
100
+ if hasattr(call.function, "arguments") and call.function.arguments:
101
+ arguments += call.function.arguments
102
+
103
+ elif chunk.choices[0].delta.content:
104
+ if not appended:
105
+ history.append(ChatMessage(role="assistant", content=""))
106
+ appended = True
107
+ history[-1].content += chunk.choices[0].delta.content
108
+ yield history[recursive:]
109
+
110
+ arguments = clean_json_string(arguments) if arguments else "{}"
111
+ arguments = json.loads(arguments)
112
+
113
+
114
+ if appended:
115
+ recursive -= 1
116
+ if name:
117
+ try:
118
+ result = str(tools[name].invoke(input=arguments))
119
+
120
+ except Exception as err:
121
+ result = f"💥 Error: {err}"
122
+
123
+ history.append(ChatMessage(
124
+ role="assistant",
125
+ content=result,
126
+ metadata={"title": json.dumps([{"id": "call_id", "function": {"arguments": json.dumps(arguments, ensure_ascii=False), "name": name}, "type": "function"}], ensure_ascii=False)}))
127
+
128
+ yield history[recursive:]
129
+ yield from llm_in_loop(history, system_prompt, recursive - 1)
130
+
131
+
132
+ def respond(message, history, additional_inputs):
133
+ history.append(ChatMessage(role="user", content=message))
134
+ yield from llm_in_loop(history, additional_inputs, -1)
135
+
136
+
137
+
138
+ if __name__ == "__main__":
139
+
140
+ system_prompt = gr.Textbox(label="System prompt", value=cfg.system_prompt_template, lines=10)
141
+ demo = gr.ChatInterface(respond, type="messages", additional_inputs=[system_prompt])
142
+ demo.launch()
config.yaml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # Embeddings configuration
3
+ # ================================================================================
4
+ vdb:
5
+ embeddings_model: BAAI/bge-m3
6
+ number_of_contexts: 5
7
+ vs_local_path: data/vdb
8
+ embedding_score_threshold: 0.4
9
+
10
+ # Context formatting (join retrieved chunks with this string)
11
+ join_str: "\n\n"
12
+
13
+
14
+ # LLM client configuration
15
+ # ================================================================================
16
+ llm_generation: true
17
+ system_prompt_template: |
18
+ You are an AI assistant designed to answer user questions using externally retrieved information. You must detect the user's language, **translate the query into Spanish**, and **respond to the user in their original language**.
19
+ All retrieved content is available **only in Spanish**.
20
+
21
+ openai:
22
+ chat_params:
23
+ stream: True
24
+ max_tokens: 1000
25
+ temperature: 0.0
26
+ top_p: 0.9
data/vdb/index.faiss ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c78a012f3c7a62af99e9515f37add0dfb07da93af82fd451313a5362b825c7b
3
+ size 147501
data/vdb/index.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e4bc944ed53d695d51403efd5131ba8ff0c98439a617b18f823dd33a4c37ed0
3
+ size 24884
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ gradio==5.23.0
2
+ openai==1.68.2
3
+ python-dotenv==1.1.0
4
+ langchain-community==0.3.20
5
+ langchain-core==0.3.48
6
+ faiss-cpu==1.10.0
7
+ faiss-gpu==1.7.2
8
+ sentence-transformers==3.4.1
9
+ termcolor
src/tools.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from abc import ABC, abstractmethod
3
+ from typing import Dict, Union, get_origin, get_args
4
+ from pydantic import BaseModel, Field
5
+ from types import UnionType
6
+ import logging
7
+ from src.vectorstore import VectorStore
8
+ from omegaconf import OmegaConf
9
+
10
+
11
+ class ToolBase(BaseModel, ABC):
12
+ @abstractmethod
13
+ def invoke(cls, input: Dict):
14
+ pass
15
+
16
+ @classmethod
17
+ def to_openai_tool(cls):
18
+ """
19
+ Extracts function metadata from a Pydantic class, including function name, parameters, and descriptions.
20
+ Formats it into a structure similar to OpenAI's function metadata.
21
+ """
22
+ function_metadata = {
23
+ "type": "function",
24
+ "function": {
25
+ "name": cls.__name__, # Function name is same as the class name, in lowercase
26
+ "description": cls.__doc__.strip(),
27
+ "parameters": {
28
+ "type": "object",
29
+ "properties": {},
30
+ "required": [],
31
+ },
32
+ },
33
+ }
34
+
35
+ # Iterate over the fields to add them to the parameters
36
+ for field_name, field_info in cls.model_fields.items():
37
+
38
+ # Field properties
39
+ field_type = "string" # Default to string, will adjust if it's a different type
40
+ annotation = field_info.annotation.__args__[0] if getattr(field_info.annotation, "__origin__", None) is Union else field_info.annotation
41
+
42
+ has_none = False
43
+ if get_origin(annotation) is UnionType: # Check if it's a Union type
44
+ args = get_args(annotation)
45
+ if type(None) in args:
46
+ has_none = True
47
+ args = [arg for arg in args if type(None) != arg]
48
+ if len(args) > 1:
49
+ raise TypeError("It can be union of only a valid type (str, int, bool, etc) and None")
50
+ elif len(args) == 0:
51
+ raise TypeError("There must be a valid type (str, int, bool, etc) not only None")
52
+ else:
53
+ annotation = args[0]
54
+
55
+ if annotation == int:
56
+ field_type = "integer"
57
+ elif annotation == bool:
58
+ field_type = "boolean"
59
+
60
+ # Add the field's description and type to the properties
61
+ function_metadata["function"]["parameters"]["properties"][field_name] = {
62
+ "type": field_type,
63
+ "description": field_info.description,
64
+ }
65
+
66
+ # Determine if the field is required (not Optional or None)
67
+ if field_info.is_required():
68
+ function_metadata["function"]["parameters"]["required"].append(field_name)
69
+ has_none = True
70
+
71
+ # If there's an enum (like for `unit`), add it to the properties
72
+ if hasattr(field_info, 'default') and field_info.default is not None and isinstance(field_info.default, list):
73
+ function_metadata["function"]["parameters"]["properties"][field_name]["enum"] = field_info.default
74
+ if not has_none:
75
+ function_metadata["function"]["parameters"]["required"].append(field_name)
76
+
77
+
78
+
79
+ return function_metadata
80
+
81
+
82
+
83
+ # Load the configuration file
84
+ # ===========================================================================
85
+ config_file = "config.yaml"
86
+ cfg = OmegaConf.load(config_file)
87
+
88
+
89
+ # Initialize VectorStore, tools and oitools
90
+ # ===========================================================================
91
+ vdb = VectorStore(**cfg.vdb)
92
+ tools: Dict[str, ToolBase] = {}
93
+ oitools = []
94
+
95
+
96
+
97
+ def tool_register(cls: BaseModel):
98
+ oaitool = cls.to_openai_tool()
99
+
100
+ oitools.append(oaitool)
101
+ tools[oaitool["function"]["name"]] = cls
102
+
103
+
104
+ @tool_register
105
+ class retrieve_aina_data(ToolBase):
106
+ """Retrieves relevant information from Aina Challenge vectorstore, based on the user's query."""
107
+ logging.info("@tool_register: retrieve_aina_data()")
108
+
109
+ query: str = Field(description="The user's input or question, used to search in Aina Challenge vectorstore.")
110
+ logging.info(f"query: {query}")
111
+
112
+ @classmethod
113
+ def invoke(cls, input: Dict) -> str:
114
+ logging.info(f"retrieve_aina_data.invoke() input: {input}")
115
+
116
+ # Check if the input is a dictionary
117
+ query = input.get("query", None)
118
+ if not query:
119
+ return "Missing required argument: query."
120
+
121
+ return vdb.get_context(query)
122
+
123
+
src/vectorstore.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain_community.vectorstores import FAISS
2
+ # from langchain_community.embeddings import HuggingFaceEmbeddings
3
+ from langchain_huggingface import HuggingFaceEmbeddings
4
+ from huggingface_hub import snapshot_download
5
+ import logging
6
+
7
+ from termcolor import cprint
8
+
9
+
10
+ class VectorStore:
11
+ def __init__(self,
12
+ embeddings_model: str,
13
+ vs_local_path: str = None,
14
+ vs_hf_path: str = None,
15
+ number_of_contexts: int = 2,
16
+ context_template: str = "{}",
17
+ embedding_score_threshold: float = None,
18
+ join_str: str = "\n\n"
19
+ ):
20
+
21
+ logging.info("Loading vectorstore...")
22
+
23
+
24
+ self.number_of_contexts = number_of_contexts
25
+ self.context_template = context_template
26
+ self.join_str = join_str
27
+ self.embedding_score_threshold = embedding_score_threshold
28
+
29
+ embeddings = HuggingFaceEmbeddings(model_name=embeddings_model)
30
+ logging.info(f"Loaded embeddings model: {embeddings_model}")
31
+
32
+
33
+ if vs_hf_path:
34
+ hf_vectorstore = snapshot_download(repo_id=vs_hf_path)
35
+ self.vdb = FAISS.load_local(hf_vectorstore, embeddings, allow_dangerous_deserialization=True)
36
+ logging.info(f"Loaded vectorstore from {vs_hf_path}")
37
+ else:
38
+ self.vdb = FAISS.load_local(vs_local_path, embeddings, allow_dangerous_deserialization=True)
39
+ logging.info(f"Loaded vectorstore from {vs_local_path}")
40
+
41
+
42
+ def get_context(self, query,):
43
+
44
+
45
+ # Retrieve documents
46
+ results = self.vdb.similarity_search_with_relevance_scores(query=query, k=self.number_of_contexts, score_threshold=self.embedding_score_threshold)
47
+ logging.info(f"Retrieved {len(results)} documents from the vectorstore.")
48
+
49
+ # Return formatted context
50
+ return self._beautiful_context(results)
51
+
52
+
53
+ def _beautiful_context(self, docs):
54
+
55
+ logging.info(f"Formatting {len(docs)} contexts...")
56
+
57
+
58
+ contexts = []
59
+
60
+ for i, doc in enumerate(docs):
61
+
62
+ print()
63
+ cprint("-"*150, "yellow")
64
+ cprint(f"Document {i}:", "yellow")
65
+ cprint(f"Score: {doc[1]}", "yellow")
66
+ cprint("-"*150, "yellow")
67
+ print(doc[0].page_content)
68
+
69
+ contexts.append(doc[0].page_content)
70
+
71
+
72
+ context = self.join_str.join(contexts)
73
+
74
+
75
+ print()
76
+ cprint("-"*150, "green")
77
+ cprint(f"Final formatted context:", "green")
78
+ cprint("-"*150, "green")
79
+ print(context)
80
+
81
+
82
+ return context
83
+