pcs-annotator 0.1.1__tar.gz → 0.1.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,108 @@
1
+ Metadata-Version: 2.4
2
+ Name: pcs-annotator
3
+ Version: 0.1.3
4
+ Summary: A Python library for classification tasks using multiple LLMs
5
+ Project-URL: Homepage, https://github.com/salsina/PCS-Python-Library
6
+ Project-URL: Issues, https://github.com/salsina/PCS-Python-Library/issues
7
+ Author-email: Sina Salimian <sina99.sn@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.8
13
+ Requires-Dist: langchain
14
+ Requires-Dist: langchain-anthropic
15
+ Requires-Dist: langchain-community
16
+ Requires-Dist: langchain-groq
17
+ Requires-Dist: langchain-huggingface
18
+ Requires-Dist: langchain-openai
19
+ Requires-Dist: python-dotenv
20
+ Description-Content-Type: text/markdown
21
+
22
+ # PCS Annotator: A Python Library for Classification Tasks Using Multiple LLMs
23
+
24
+ ## How to Install
25
+
26
+ ```bash
27
+ pip install pcs-annotator
28
+ ```
29
+
30
+ ## How to Use
31
+
32
+ ```python
33
+ from pcs_annotator import PCS
34
+ ```
35
+
36
+ ### Create a Prompt for Classification Tasks
37
+
38
+ ```python
39
+ prompt = """Analyze the news article and determine whether it is 'Fake' or 'Real.'
40
+ Label the article using the tag format: <label>Fake</label> or <label>Real</label>.
41
+ Afterward, provide your reasoning after the “<reasoning>” tag and close it with "</reasoning>".
42
+ Respond only with the label and the reasoning.
43
+ """
44
+ ```
45
+
46
+
47
+
48
+
49
+
50
+ ## 🔧 Customizing Hyperparameters
51
+
52
+ The `PCS` class allows you to customize various hyperparameters, including the choice of annotator models, text mutator models, and API keys for different LLM providers.
53
+
54
+ ### 📌 Example Usage
55
+ ```python
56
+ PCS(
57
+ prompt="Your classification prompt here",
58
+ dataset_path="path/to/dataset.csv",
59
+ annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "google/gemma-2-9b-it"],
60
+ textmutator="llama-3.1-8b-instant",
61
+ GROQ_API_KEY=None,
62
+ OPENAI_API_KEY=None,
63
+ ANTHROPIC_API_KEY=None,
64
+ HUGGINGFACE_API_KEY=None
65
+ )
66
+ ```
67
+
68
+ # Configuration
69
+ ## 🔹 Training Dataset (`dataset_path`)
70
+
71
+ You will need a CSV file with two columns: `label` and `text` to ensure better annotation, as the data is used to train the LLMs.
72
+
73
+
74
+ ## 🔹 Annotators (`annotators`)
75
+ Defines the list of LLMs used for annotation.
76
+ * **Default Models**:
77
+ * `"llama3-8b-8192"`
78
+ * `"mistralai/Mistral-7B-Instruct-v0.3"`
79
+ * `"google/gemma-2-9b-it"`
80
+ * **Customization**:
81
+ * You can add, remove, or modify the annotators by passing a list of model names.
82
+
83
+ ## 🔹 Text Mutator (`textmutator`)
84
+ Determines the LLM used for generating text mutations.
85
+ * **Default Model**: `"llama-3.1-8b-instant"`
86
+ * **Customization**:
87
+ * You can replace it by passing a different model name as a string.
88
+
89
+ ## 🔹 API Keys
90
+ To access certain LLM models, you need to provide API keys. These can be passed as arguments during initialization or set as environment variables in a `.env` file.
91
+
92
+ | API Key | Purpose |
93
+ |---------|---------|
94
+ | `GROQ_API_KEY` | Required for **Llama models**. Set via argument or `.env` file. |
95
+ | `OPENAI_API_KEY` | Required for **OpenAI models** (e.g., `"gpt-4"`). |
96
+ | `ANTHROPIC_API_KEY` | Required for **Anthropic models** (e.g., `"claude-3-5-sonnet-20241022"`). |
97
+ | `HUGGINGFACE_API_KEY` | Required for **Mistral and Google Gemma models**. |
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+ ### Annotate a New Text
106
+
107
+ ```python
108
+ print(pcs.annotate("America is a country"))
@@ -0,0 +1,87 @@
1
+ # PCS Annotator: A Python Library for Classification Tasks Using Multiple LLMs
2
+
3
+ ## How to Install
4
+
5
+ ```bash
6
+ pip install pcs-annotator
7
+ ```
8
+
9
+ ## How to Use
10
+
11
+ ```python
12
+ from pcs_annotator import PCS
13
+ ```
14
+
15
+ ### Create a Prompt for Classification Tasks
16
+
17
+ ```python
18
+ prompt = """Analyze the news article and determine whether it is 'Fake' or 'Real.'
19
+ Label the article using the tag format: <label>Fake</label> or <label>Real</label>.
20
+ Afterward, provide your reasoning after the “<reasoning>” tag and close it with "</reasoning>".
21
+ Respond only with the label and the reasoning.
22
+ """
23
+ ```
24
+
25
+
26
+
27
+
28
+
29
+ ## 🔧 Customizing Hyperparameters
30
+
31
+ The `PCS` class allows you to customize various hyperparameters, including the choice of annotator models, text mutator models, and API keys for different LLM providers.
32
+
33
+ ### 📌 Example Usage
34
+ ```python
35
+ PCS(
36
+ prompt="Your classification prompt here",
37
+ dataset_path="path/to/dataset.csv",
38
+ annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "google/gemma-2-9b-it"],
39
+ textmutator="llama-3.1-8b-instant",
40
+ GROQ_API_KEY=None,
41
+ OPENAI_API_KEY=None,
42
+ ANTHROPIC_API_KEY=None,
43
+ HUGGINGFACE_API_KEY=None
44
+ )
45
+ ```
46
+
47
+ # Configuration
48
+ ## 🔹 Training Dataset (`dataset_path`)
49
+
50
+ You will need a CSV file with two columns: `label` and `text` to ensure better annotation, as the data is used to train the LLMs.
51
+
52
+
53
+ ## 🔹 Annotators (`annotators`)
54
+ Defines the list of LLMs used for annotation.
55
+ * **Default Models**:
56
+ * `"llama3-8b-8192"`
57
+ * `"mistralai/Mistral-7B-Instruct-v0.3"`
58
+ * `"google/gemma-2-9b-it"`
59
+ * **Customization**:
60
+ * You can add, remove, or modify the annotators by passing a list of model names.
61
+
62
+ ## 🔹 Text Mutator (`textmutator`)
63
+ Determines the LLM used for generating text mutations.
64
+ * **Default Model**: `"llama-3.1-8b-instant"`
65
+ * **Customization**:
66
+ * You can replace it by passing a different model name as a string.
67
+
68
+ ## 🔹 API Keys
69
+ To access certain LLM models, you need to provide API keys. These can be passed as arguments during initialization or set as environment variables in a `.env` file.
70
+
71
+ | API Key | Purpose |
72
+ |---------|---------|
73
+ | `GROQ_API_KEY` | Required for **Llama models**. Set via argument or `.env` file. |
74
+ | `OPENAI_API_KEY` | Required for **OpenAI models** (e.g., `"gpt-4"`). |
75
+ | `ANTHROPIC_API_KEY` | Required for **Anthropic models** (e.g., `"claude-3-5-sonnet-20241022"`). |
76
+ | `HUGGINGFACE_API_KEY` | Required for **Mistral and Google Gemma models**. |
77
+
78
+
79
+
80
+
81
+
82
+
83
+
84
+ ### Annotate a New Text
85
+
86
+ ```python
87
+ print(pcs.annotate("America is a country"))
@@ -2,8 +2,8 @@ from .LLM import LLM
2
2
  from .Tools import *
3
3
 
4
4
  class Annotator(LLM):
5
- def __init__(self, prompt, labels, model_name="llama3-8b-8192"):
6
- super().__init__(model_name)
5
+ def __init__(self, prompt, labels, model_name="llama3-8b-8192", token=None):
6
+ super().__init__(model_name, token)
7
7
 
8
8
  self.prompt = prompt
9
9
  self.labels = labels
@@ -0,0 +1,65 @@
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from langchain_groq import ChatGroq
4
+ from langchain_core.output_parsers import StrOutputParser
5
+ from langchain_openai import ChatOpenAI
6
+ from langchain_anthropic import ChatAnthropic
7
+ # from langchain_huggingface import HuggingFaceEndpoint
8
+ from huggingface_hub import InferenceClient # Use InferenceClient instead of HuggingFaceEndpoint
9
+ from langchain_huggingface import HuggingFaceEndpoint
10
+
11
+ # from langchain_huggingface import HuggingFacePipeline
12
+
13
+
14
+ class LLM:
15
+ def __init__(self, model_name, token=None):
16
+ self.key = token
17
+ load_dotenv()
18
+ self.model_name = model_name
19
+ self.llm = self._initialize_model()
20
+ parser = StrOutputParser()
21
+ self.llm = self.llm | parser
22
+
23
+ def _initialize_model(self):
24
+ """
25
+ Initialize the appropriate LLM model based on the model_name.
26
+ """
27
+ if self.model_name.startswith("llama"): # e.g., llama-3.1-8b-instant
28
+ if self.key == None:
29
+ self.key = os.getenv('GROQ_API_KEY')
30
+ if not self.key:
31
+ raise ValueError("Missing GROQ_API_KEY in environment variables.")
32
+ model = ChatGroq(api_key=self.key, model_name=self.model_name, temperature=0.1)
33
+
34
+ elif self.model_name.startswith("gpt"): # e.g., gpt-4
35
+ if self.key == None:
36
+ self.key = os.getenv('OPENAI_API_KEY')
37
+ if not self.key:
38
+ raise ValueError("Missing OPENAI_API_KEY in environment variables.")
39
+ model = ChatOpenAI(api_key=self.key, model=self.model_name, temperature=0.1)
40
+
41
+ elif self.model_name.startswith("claude"): # e.g., claude-3-5-sonnet-20241022
42
+ if self.key == None:
43
+ self.key = os.getenv('ANTHROPIC_API_KEY')
44
+ if not self.key:
45
+ raise ValueError("Missing ANTHROPIC_API_KEY in environment variables.")
46
+ model = ChatAnthropic(api_key=self.key, model=self.model_name, temperature=0.1)
47
+
48
+ elif self.model_name.startswith("mistral") or self.model_name.startswith("google"): # e.g., mistralai/Mistral-7B-Instruct-v0.3 or google/gemma-2-9b-it
49
+ if self.key == None:
50
+ self.key = os.getenv('HUGGINGFACE_API_KEY')
51
+ if not self.key:
52
+ raise ValueError("Missing HUGGINGFACE_API_KEY in environment variables.")
53
+
54
+ model = HuggingFaceEndpoint(
55
+ repo_id=self.model_name,
56
+ task="text-generation",
57
+ temperature=0.1,
58
+ huggingfacehub_api_token=self.key,
59
+ )
60
+
61
+
62
+ else:
63
+ raise ValueError(f"Unsupported model name: {self.model_name}")
64
+
65
+ return model
@@ -9,7 +9,7 @@ from tqdm import tqdm
9
9
 
10
10
 
11
11
  class PCS:
12
- def __init__(self, prompt, dataset_path, annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "google/gemma-2-9b-it"]):
12
+ def __init__(self, prompt, dataset_path, annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "google/gemma-2-9b-it"], textmutator="llama-3.1-8b-instant", GROQ_API_KEY=None, OPENAI_API_KEY=None, ANTHROPIC_API_KEY=None, HUGGINGFACE_API_KEY=None):
13
13
  self.prompt=prompt
14
14
  if os.path.exists(dataset_path):
15
15
  self.dataset_path = dataset_path
@@ -17,13 +17,35 @@ class PCS:
17
17
  raise FileNotFoundError(f"Invalid dataset path {dataset_path}")
18
18
  self.annotator_model_names = annotators
19
19
  self.annotators = []
20
- self.textMutator = TextMutator()
20
+
21
+ if textmutator.startswith("llama"):
22
+ self.textMutator = TextMutator(model_name=textmutator, token=GROQ_API_KEY)
23
+ elif textmutator.startswith("gpt"):
24
+ self.textMutator = TextMutator(model_name=textmutator, token=OPENAI_API_KEY)
25
+ elif textmutator.startswith("claude"):
26
+ self.textMutator = TextMutator(model_name=textmutator, token=ANTHROPIC_API_KEY)
27
+ elif textmutator.startswith("mistral") or textmutator.startswith("google"):
28
+ self.textMutator = TextMutator(model_name=textmutator, token=HUGGINGFACE_API_KEY)
29
+ else:
30
+ raise ValueError(f"Unsupported text mutator model name: {textmutator}")
31
+
21
32
 
22
33
  self.annotations_filename = self.dataset_path.rsplit(".csv", 1)[0] + "_annotations.csv"
23
34
  self.dataset = pd.read_csv(dataset_path)
24
35
  self.possible_labels = self.dataset["label"].unique().tolist()
25
36
  for annotator_model_name in self.annotator_model_names:
26
- self.annotators.append(Annotator(prompt=self.prompt, labels=self.possible_labels, model_name=annotator_model_name))
37
+ if annotator_model_name.startswith("llama"):
38
+ token = GROQ_API_KEY
39
+ elif annotator_model_name.startswith("gpt"):
40
+ token = OPENAI_API_KEY
41
+ elif annotator_model_name.startswith("claude"):
42
+ token = ANTHROPIC_API_KEY
43
+ elif annotator_model_name.startswith("mistral") or annotator_model_name.startswith("google"):
44
+ token = HUGGINGFACE_API_KEY
45
+ else:
46
+ raise ValueError(f"Unsupported annotator model name: {annotator_model_name}")
47
+
48
+ self.annotators.append(Annotator(prompt=self.prompt, labels=self.possible_labels, model_name=annotator_model_name, token=token))
27
49
  self.optimal_llm_weights = [1] * len(self.annotators)
28
50
  self.optimal_mr_weights = [1] * 4
29
51
  self.optimal_label_thresholds = [0.5] * len(self.possible_labels)
@@ -2,11 +2,11 @@ from .LLM import LLM
2
2
  from .Tools import *
3
3
 
4
4
  class TextMutator(LLM):
5
- def __init__(self, model_name="llama-3.1-8b-instant"):
6
- super().__init__(model_name)
5
+ def __init__(self, model_name="llama-3.1-8b-instant", token=None):
6
+ super().__init__(model_name, token)
7
7
 
8
8
 
9
- def MutateText(self, text, mr, custom_prompt=None):
9
+ def MutateText(self, text, mr):
10
10
  if mr == "passive_active":
11
11
  prompt = f"""Review the text below and transform all sentences by converting active voice to passive voice and vice versa, where appropriate.
12
12
 
@@ -5,7 +5,7 @@ build-backend = "hatchling.build"
5
5
 
6
6
  [project]
7
7
  name = "pcs-annotator"
8
- version = "0.1.1"
8
+ version = "0.1.3"
9
9
  authors = [
10
10
  { name = "Sina Salimian", email = "sina99.sn@gmail.com" }
11
11
  ]
@@ -1,24 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: pcs-annotator
3
- Version: 0.1.1
4
- Summary: A Python library for classification tasks using multiple LLMs
5
- Project-URL: Homepage, https://github.com/salsina/PCS-Python-Library
6
- Project-URL: Issues, https://github.com/salsina/PCS-Python-Library/issues
7
- Author-email: Sina Salimian <sina99.sn@gmail.com>
8
- License-Expression: MIT
9
- License-File: LICENSE
10
- Classifier: Operating System :: OS Independent
11
- Classifier: Programming Language :: Python :: 3
12
- Requires-Python: >=3.8
13
- Requires-Dist: langchain
14
- Requires-Dist: langchain-anthropic
15
- Requires-Dist: langchain-community
16
- Requires-Dist: langchain-groq
17
- Requires-Dist: langchain-huggingface
18
- Requires-Dist: langchain-openai
19
- Requires-Dist: python-dotenv
20
- Description-Content-Type: text/markdown
21
-
22
- This is a simple example package. You can use
23
- [GitHub-flavored Markdown](https://guides.github.com/features/mastering-markdown/)
24
- to write your content.
@@ -1,3 +0,0 @@
1
- This is a simple example package. You can use
2
- [GitHub-flavored Markdown](https://guides.github.com/features/mastering-markdown/)
3
- to write your content.
@@ -1,74 +0,0 @@
1
- import os
2
- from dotenv import load_dotenv
3
- from langchain_groq import ChatGroq
4
- from langchain_core.output_parsers import StrOutputParser
5
- from langchain_openai import ChatOpenAI
6
- from langchain_anthropic import ChatAnthropic
7
- # from langchain_huggingface import HuggingFaceEndpoint
8
- from huggingface_hub import InferenceClient # Use InferenceClient instead of HuggingFaceEndpoint
9
- from langchain_huggingface import HuggingFaceEndpoint
10
-
11
- # from langchain_huggingface import HuggingFacePipeline
12
-
13
-
14
- class LLM:
15
- def __init__(self, model_name):
16
- load_dotenv()
17
- self.model_name = model_name
18
- self.llm = self._initialize_model()
19
- parser = StrOutputParser()
20
- self.llm = self.llm | parser
21
-
22
- def _initialize_model(self):
23
- """
24
- Initialize the appropriate LLM model based on the model_name.
25
- """
26
- if self.model_name.startswith("llama"): # e.g., llama-3.1-8b-instant
27
- key = os.getenv('GROQ_API_KEY')
28
- if not key:
29
- raise ValueError("Missing GROQ_API_KEY in environment variables.")
30
- model = ChatGroq(api_key=key, model_name=self.model_name, temperature=0.1)
31
-
32
- elif self.model_name.startswith("gpt"): # e.g., gpt-4
33
- key = os.getenv('OPENAI_API_KEY')
34
- if not key:
35
- raise ValueError("Missing OPENAI_API_KEY in environment variables.")
36
- model = ChatOpenAI(api_key=key, model=self.model_name, temperature=0.1)
37
-
38
- elif self.model_name.startswith("claude"): # e.g., claude-3-5-sonnet-20241022
39
- key = os.getenv('ANTHROPIC_API_KEY')
40
- if not key:
41
- raise ValueError("Missing ANTHROPIC_API_KEY in environment variables.")
42
- model = ChatAnthropic(api_key=key, model=self.model_name, temperature=0.1)
43
-
44
- elif self.model_name.startswith("mistral"): # e.g., mistralai/Mistral-7B-Instruct-v0.3
45
- key = os.getenv('HUGGINGFACE_API_KEY')
46
-
47
- if not key:
48
- raise ValueError("Missing HUGGINGFACE_API_KEY in environment variables.")
49
-
50
- model = HuggingFaceEndpoint(
51
- repo_id="mistralai/Mistral-7B-Instruct-v0.3",
52
- task="text-generation",
53
- temperature=0.1,
54
- huggingfacehub_api_token=key,
55
- )
56
-
57
-
58
-
59
- elif self.model_name.startswith("google"): # e.g., gemma-2-9b-it
60
- key = os.getenv('HUGGINGFACE_API_KEY')
61
- if not key:
62
- raise ValueError("Missing HUGGINGFACE_API_KEY in environment variables.")
63
-
64
- model = HuggingFaceEndpoint(
65
- repo_id="google/gemma-2-9b-it",
66
- task="text-generation",
67
- temperature=0.1,
68
- huggingfacehub_api_token=key,
69
- )
70
-
71
- else:
72
- raise ValueError(f"Unsupported model name: {self.model_name}")
73
-
74
- return model
File without changes