Skip to content

Commit 8270af8

Browse files
committed
Apply temperature compatibility fix from PR #939 and format code
- Change temperature default from 1e-8 to 0.01 for better LLM compatibility - Fix issues with Mistral7b and Mixtral8x22 hosted via Hugging Face TGI - Apply code formatting fixes
1 parent ebc75b1 commit 8270af8

32 files changed

+116
-128
lines changed

examples/ragas_examples/_version.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# file generated by setuptools-scm
2+
# don't change, don't track in version control
3+
4+
__all__ = [
5+
"__version__",
6+
"__version_tuple__",
7+
"version",
8+
"version_tuple",
9+
"__commit_id__",
10+
"commit_id",
11+
]
12+
13+
TYPE_CHECKING = False
14+
if TYPE_CHECKING:
15+
from typing import Tuple
16+
from typing import Union
17+
18+
VERSION_TUPLE = Tuple[Union[int, str], ...]
19+
COMMIT_ID = Union[str, None]
20+
else:
21+
VERSION_TUPLE = object
22+
COMMIT_ID = object
23+
24+
version: str
25+
__version__: str
26+
__version_tuple__: VERSION_TUPLE
27+
version_tuple: VERSION_TUPLE
28+
commit_id: COMMIT_ID
29+
__commit_id__: COMMIT_ID
30+
31+
__version__ = version = "0.3.3.dev51+g8e7ead097"
32+
__version_tuple__ = version_tuple = (0, 3, 3, "dev51", "g8e7ead097")
33+
34+
__commit_id__ = commit_id = "g8e7ead097"

src/ragas/callbacks.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,6 @@ def parse_run_traces(
135135
traces: t.Dict[str, ChainRun],
136136
parent_run_id: t.Optional[str] = None,
137137
) -> t.List[t.Dict[str, t.Any]]:
138-
139138
root_traces = [
140139
chain_trace
141140
for chain_trace in traces.values()

src/ragas/embeddings/base.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,8 @@ def __get_pydantic_core_schema__(
9696
Define how Pydantic generates a schema for BaseRagasEmbeddings.
9797
"""
9898
return core_schema.no_info_after_validator_function(
99-
cls, core_schema.is_instance_schema(cls) # The validator function
99+
cls,
100+
core_schema.is_instance_schema(cls), # The validator function
100101
)
101102

102103

@@ -269,9 +270,9 @@ def embed_documents(self, texts: List[str]) -> List[List[float]]:
269270
from sentence_transformers.SentenceTransformer import SentenceTransformer
270271
from torch import Tensor
271272

272-
assert isinstance(
273-
self.model, SentenceTransformer
274-
), "Model is not of the type Bi-encoder"
273+
assert isinstance(self.model, SentenceTransformer), (
274+
"Model is not of the type Bi-encoder"
275+
)
275276
embeddings = self.model.encode(
276277
texts, normalize_embeddings=True, **self.encode_kwargs
277278
)
@@ -286,9 +287,9 @@ def predict(self, texts: List[List[str]]) -> List[List[float]]:
286287
from sentence_transformers.cross_encoder import CrossEncoder
287288
from torch import Tensor
288289

289-
assert isinstance(
290-
self.model, CrossEncoder
291-
), "Model is not of the type CrossEncoder"
290+
assert isinstance(self.model, CrossEncoder), (
291+
"Model is not of the type CrossEncoder"
292+
)
292293

293294
predictions = self.model.predict(texts, **self.encode_kwargs)
294295

src/ragas/integrations/langchain.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -48,14 +48,14 @@ def __init__(self, metric: Metric, **kwargs: t.Any):
4848
t.cast(MetricWithLLM, self.metric).llm = LangchainLLMWrapper(llm)
4949
if isinstance(self.metric, MetricWithEmbeddings):
5050
embeddings = get_or_init(kwargs, "embeddings", OpenAIEmbeddings)
51-
t.cast(MetricWithEmbeddings, self.metric).embeddings = (
52-
LangchainEmbeddingsWrapper(embeddings)
53-
)
51+
t.cast(
52+
MetricWithEmbeddings, self.metric
53+
).embeddings = LangchainEmbeddingsWrapper(embeddings)
5454
self.metric.init(run_config)
5555

56-
assert isinstance(
57-
self.metric, SingleTurnMetric
58-
), "Metric must be SingleTurnMetric"
56+
assert isinstance(self.metric, SingleTurnMetric), (
57+
"Metric must be SingleTurnMetric"
58+
)
5959

6060
@property
6161
def input_keys(self) -> list[str]:
@@ -87,9 +87,9 @@ def _call(
8787
_run_manager = run_manager or CallbackManagerForChainRun.get_noop_manager()
8888
callbacks = _run_manager.get_child()
8989

90-
assert isinstance(
91-
self.metric, SingleTurnMetric
92-
), "Metric must be SingleTurnMetric"
90+
assert isinstance(self.metric, SingleTurnMetric), (
91+
"Metric must be SingleTurnMetric"
92+
)
9393
score = self.metric.single_turn_score(
9494
inputs,
9595
callbacks=callbacks,
@@ -119,9 +119,9 @@ async def _acall(
119119
_run_manager = run_manager or AsyncCallbackManagerForChainRun.get_noop_manager()
120120
# TODO: currently AsyncCallbacks are not supported in ragas
121121
_run_manager.get_child()
122-
assert isinstance(
123-
self.metric, SingleTurnMetric
124-
), "Metric must be SingleTurnMetric"
122+
assert isinstance(self.metric, SingleTurnMetric), (
123+
"Metric must be SingleTurnMetric"
124+
)
125125
score = await self.metric.single_turn_ascore(
126126
inputs,
127127
callbacks=[],
@@ -160,9 +160,9 @@ def _validate_langsmith_eval(self, run: Run, example: t.Optional[Example]) -> No
160160
"Expected 'question' and 'ground_truth' in example."
161161
f"Got: {[k for k in example.inputs.keys()]}"
162162
)
163-
assert (
164-
run.outputs is not None
165-
), "the current run has no outputs. The chain should output 'answer' and 'contexts' keys."
163+
assert run.outputs is not None, (
164+
"the current run has no outputs. The chain should output 'answer' and 'contexts' keys."
165+
)
166166
output_keys = get_required_columns_v1(self.metric)
167167
output_keys = [
168168
key for key in output_keys if key not in ["question", "ground_truth"]

src/ragas/integrations/langgraph.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@ def _validate_string_content(message, message_type: str) -> str:
4646
return message.content
4747

4848
def _extract_metadata(message) -> dict:
49-
5049
return {k: v for k, v in message.__dict__.items() if k != "content"}
5150

5251
if metadata:

src/ragas/llms/base.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,7 @@ def generate_text(
7171
temperature: float = 0.01,
7272
stop: t.Optional[t.List[str]] = None,
7373
callbacks: Callbacks = None,
74-
) -> LLMResult:
75-
...
74+
) -> LLMResult: ...
7675

7776
@abstractmethod
7877
async def agenerate_text(
@@ -82,8 +81,7 @@ async def agenerate_text(
8281
temperature: t.Optional[float] = 0.01,
8382
stop: t.Optional[t.List[str]] = None,
8483
callbacks: Callbacks = None,
85-
) -> LLMResult:
86-
...
84+
) -> LLMResult: ...
8785

8886
async def generate(
8987
self,

src/ragas/losses.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ def __get_pydantic_core_schema__(
2222
Define how Pydantic generates a schema for BaseRagasEmbeddings.
2323
"""
2424
return core_schema.no_info_after_validator_function(
25-
cls, core_schema.is_instance_schema(cls) # The validator function
25+
cls,
26+
core_schema.is_instance_schema(cls), # The validator function
2627
)
2728

2829

@@ -34,7 +35,6 @@ class MSELoss(Loss):
3435
reduction: t.Literal["mean", "sum"] = "mean"
3536

3637
def __call__(self, predicted: t.List[float], actual: t.List[float]) -> float:
37-
3838
errors = [(p - a) ** 2 for p, a in zip(predicted, actual)]
3939
if self.reduction == "mean":
4040
return sum(errors) / len(errors)

src/ragas/metrics/_answer_relevance.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,9 +95,9 @@ class ResponseRelevancy(MetricWithLLM, MetricWithEmbeddings, SingleTurnMetric):
9595
strictness: int = 3
9696

9797
def calculate_similarity(self, question: str, generated_questions: list[str]):
98-
assert (
99-
self.embeddings is not None
100-
), f"Error: '{self.name}' requires embeddings to be set."
98+
assert self.embeddings is not None, (
99+
f"Error: '{self.name}' requires embeddings to be set."
100+
)
101101
question_vec = np.asarray(self.embeddings.embed_query(question)).reshape(1, -1)
102102
gen_question_vec = np.asarray(
103103
self.embeddings.embed_documents(generated_questions)

src/ragas/metrics/_answer_similarity.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,9 @@ async def _single_turn_ascore(
6565
return await self._ascore(row, callbacks)
6666

6767
async def _ascore(self, row: t.Dict, callbacks: Callbacks) -> float:
68-
assert (
69-
self.embeddings is not None
70-
), f"Error: '{self.name}' requires embeddings to be set."
68+
assert self.embeddings is not None, (
69+
f"Error: '{self.name}' requires embeddings to be set."
70+
)
7171

7272
ground_truth = t.cast(str, row["reference"])
7373
answer = t.cast(str, row["response"])

src/ragas/metrics/_bleu_score.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ def init(self, run_config: RunConfig):
3232
async def _single_turn_ascore(
3333
self, sample: SingleTurnSample, callbacks: Callbacks
3434
) -> float:
35-
3635
reference, response = sample.reference, sample.response
3736
assert isinstance(reference, str), "BleuScore expects a valid reference string"
3837
assert isinstance(response, str), "BleuScore expects a valid response string"

0 commit comments

Comments
 (0)