forked from NVIDIA/garak
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcohere.py
More file actions
211 lines (182 loc) · 9.23 KB
/
Copy pathcohere.py
File metadata and controls
211 lines (182 loc) · 9.23 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
"""Cohere AI model support
Support for Cohere's text generation API. Uses the command model by default,
but just supply the name of another either on the command line or as the
constructor param if you want to use that. You'll need to set an environment
variable called COHERE_API_KEY to your Cohere API key, for this generator.
NOTE: As of Cohere v5.0.0+, the generate API is legacy and chat API is recommended.
This implementation follows Cohere's official migration guide:
- For v1 API: Uses cohere.Client() to maintain full backward compatibility
- For v2 API: Uses cohere.ClientV2() for the recommended chat interface
"""
import logging
from typing import List, Union
import backoff
import tqdm
from garak import _config
from garak.attempt import Message, Conversation
from garak.exception import GeneratorBackoffTrigger
from garak.generators.base import Generator
COHERE_GENERATION_LIMIT = (
5 # c.f. https://docs.cohere.com/reference/generate 18 may 2023
)
class CohereGenerator(Generator):
"""Interface to Cohere's python library for their text2text model.
Expects API key in COHERE_API_KEY environment variable.
Following Cohere's migration guide, this implementation:
- For api_version="v1": Uses cohere.Client() with generate() API (supports multiple generations)
- For api_version="v2": Uses cohere.ClientV2() with chat() API (recommended, requires multiple API calls)
"""
ENV_VAR = "COHERE_API_KEY"
DEFAULT_PARAMS = Generator.DEFAULT_PARAMS | {
"temperature": 0.750,
"k": 0,
"p": 0.75,
"frequency_penalty": 0.0,
"presence_penalty": 0.0,
"stop": [], # Used for end_sequences in v1 API
"preset": None, # Only used with v1 API
"api_version": "v2", # "v1" for legacy generate API, "v2" for chat API (recommended)
}
extra_dependency_names = ["cohere"]
generator_family_name = "Cohere"
def __init__(self, name="command", config_root=_config):
self.name = name
self.fullname = f"Cohere {self.name}"
super().__init__(self.name, config_root=config_root)
logging.debug(
"Cohere generation request limit capped at %s", COHERE_GENERATION_LIMIT
)
# Validate api_version
if self.api_version not in ["v1", "v2"]:
logging.warning(
f"Invalid api_version '{self.api_version}'. Using 'v2' instead."
)
self.api_version = "v2"
# Initialize appropriate client based on API version
# Following Cohere's guidance to use Client() for v1 and ClientV2() for v2
if self.api_version == "v1":
self.generator = self.cohere.Client(api_key=self.api_key)
else: # api_version == "v2"
self.generator = self.cohere.ClientV2(api_key=self.api_key)
@backoff.on_exception(backoff.fibo, GeneratorBackoffTrigger, max_value=70)
def _call_cohere_api(self, prompt_text, request_size=COHERE_GENERATION_LIMIT):
"""Empty prompts raise API errors (e.g. invalid request: prompt must be at least 1 token long).
We catch these using the ApiError base class in Cohere v5+.
Filtering exceptions based on message instead of type, in backoff, isn't immediately obvious
- on the other hand blank prompt / RTP shouldn't hang forever
"""
if not prompt_text:
return [Message("")] * request_size
else:
if self.api_version == "v2":
# Use chat API with ClientV2 (recommended in v5+)
responses = []
# Chat API doesn't support num_generations, so we need to make multiple calls
for _ in range(request_size):
try:
response = self.generator.chat(
model=self.name,
messages=prompt_text,
temperature=self.temperature,
max_tokens=self.max_tokens,
k=self.k,
p=self.p,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
# Note: stop_sequences/end_sequences, logit_bias, truncate, and preset
# are not supported in the Chat endpoint per Cohere migration guide
)
# Extract text from message content
if hasattr(response, "message") and hasattr(
response.message, "content"
):
# Get the first text content item
for content_item in response.message.content:
if hasattr(content_item, "text"):
responses.append(content_item.text)
break
else:
# No text content found
logging.warning(
"No text content found in chat response"
)
responses.append(str(response))
else:
logging.warning(
"Chat response structure doesn't match expected format"
)
responses.append(str(response))
except Exception as e:
backoff_exception_types = (
self.cohere.errors.GatewayTimeoutError,
self.cohere.errors.TooManyRequestsError,
self.cohere.errors.ServiceUnavailableError,
self.cohere.errors.InternalServerError,
)
for backoff_exception in backoff_exception_types:
if isinstance(e, backoff_exception):
raise GeneratorBackoffTrigger from e # bubble up ApiError for backoff handling
logging.error(f"Chat API error: {e}")
responses.append(None)
# Ensure we return the correct number of responses
if len(responses) < request_size:
responses.extend([None] * (request_size - len(responses)))
return responses
else: # api_version == "v1"
# Use legacy generate API with cohere.Client()
# Following Cohere's guidance for full backward compatibility
try:
message = prompt_text[-1]["content"]
response = self.generator.generate(
model=self.name,
prompt=message,
temperature=self.temperature,
num_generations=request_size,
max_tokens=self.max_tokens,
preset=self.preset,
k=self.k,
p=self.p,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
end_sequences=self.stop,
)
# Handle response based on structure
if hasattr(response, "generations"):
# Handle the v5+ API response format
return [gen.text for gen in response.generations]
else:
# Try to handle other possible response formats
try:
if isinstance(response, list):
return [g.text for g in response]
elif hasattr(response, "text"):
return [response.text]
else:
# Last resort - try to convert response to string
return [str(response)]
except RuntimeError as e:
logging.error(
f"Failed to extract text from Cohere response: {e}"
)
return [None] * request_size
except RuntimeError as e:
logging.error(f"Generate API error: {e}")
return [None] * request_size
def _call_model(
self, prompt: Conversation, generations_this_call: int = 1
) -> List[Union[Message, None]]:
"""Cohere's _call_model does sub-batching before calling,
and so manages chunking internally"""
quotient, remainder = divmod(generations_this_call, COHERE_GENERATION_LIMIT)
request_sizes = [COHERE_GENERATION_LIMIT] * quotient
if remainder:
request_sizes += [remainder]
outputs = []
generation_iterator = tqdm.tqdm(request_sizes, leave=False)
generation_iterator.set_description(self.fullname)
for request_size in generation_iterator:
outputs += self._call_cohere_api(
self._conversation_to_list(prompt), request_size=request_size
)
return outputs
DEFAULT_CLASS = "CohereGenerator"