Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

deprecate OpenAIDavinci and add OpenAILegacy #216

Merged
merged 5 commits into from
Jan 22, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions langkit/docs/faq.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Frequently Asked Questions

**Q**: Does Langkit integrate with which Large Language Models?

**A**: Most of Langkit's metrics require only the presence of one of two (or both) specific columns: a `prompt` column and a `response` column. You can use any LLM you wish with Langkit, as long as you provide the prompt and response columns. There are, however, two modules that require additional LLM calls to calculate metrics: `response_hallucination` and `proactive_injection_detection`. For these two modules, only OpenAI models are supported through `langkit.openai`'s `OpenAILegacy`, `OpenAIDefault`, and `OpenAIGPT4`. Azure-hosted OpenAI models are also supported through `OpenAIAzure`.

---

**Q**: Can I choose individual metrics in LangKit?

**A**: The finest granularity with which you can enable metrics is by metric namespaces. For example, you can import the `textstat` namespace, which will calculate all the text quality metrics (automated_readability_index,flesch_kincaid_grade, etc.) defined in that namespace. You can't, for example, pick the single metric `flesch_kincaid_grade`.
Expand Down
8 changes: 5 additions & 3 deletions langkit/docs/modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
The `hallucination` namespace will compute the consistency between the target response and a group of additional response samples. It will create a new column named `response.hallucination`. The premise is that if the LLM has knowledge of the topic, then it should be able to generate similar and consistent responses when asked the same question multiple times. For more information on this approach see [SELFCHECKGPT: Zero-Resource Black-Box Hallucination Detection
for Generative Large Language Models](https://arxiv.org/pdf/2303.08896.pdf)

> Note: Requires additional LLM calls to calculate the consistency score.
> Note: Requires additional LLM calls to calculate the consistency score. Currently, only OpenAI models are supported through `langkit.openai`'s `OpenAILegacy`, `OpenAIDefault`, and `OpenAIGPT4`, and `OpenAIAzure`.

### Usage

Expand Down Expand Up @@ -114,7 +114,7 @@ profile = why.log({"prompt":"What is the primary function of the mitochondria in

The `response.relevance_to_prompt` computed column will contain a similarity score between the prompt and response. The higher the score, the more relevant the response is to the prompt.

The similarity score is computed by calculating the cosine similarity between embeddings generated from both prompt and response. The embeddings are generated using the hugginface's model `sentence-transformers/all-MiniLM-L6-v2`.
The similarity score is computed by calculating the cosine similarity between embeddings generated from both prompt and response. The embeddings are generated using the hugginface's model [sentence-transformers/all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2).

## Proactive Injection Detection

Expand All @@ -123,6 +123,8 @@ is an injection attack.

The instruction prompt will instruct the LLM to repeat a randomly generated string. If the response does not contain the string, a potential injection attack is detected, and the detector will return a score of 1. Otherwise, it will return a score of 0.

> Note: Requires an additional LLM call to calculate the score. Currently, only OpenAI models are supported through `langkit.openai`'s `OpenAILegacy`, `OpenAIDefault`, and `OpenAIGPT4`, and `OpenAIAzure`.

Reference: https://arxiv.org/abs/2310.12815

### Usage
Expand Down Expand Up @@ -329,7 +331,7 @@ This method returns the number of words with one syllable present in the input t

The `themes` namespace will compute similarity scores for every column of type `String` against a set of themes. The themes are defined in `themes.json`, and can be customized by the user. It will create a new udf submetric with the name of each theme defined in the json file.

The similarity score is computed by calculating the cosine similarity between embeddings generated from the target text and set of themes. For each theme, the returned score is the maximum score found for all the examples in the related set. The embeddings are generated using the hugginface's model `sentence-transformers/all-MiniLM-L6-v2`.
The similarity score is computed by calculating the cosine similarity between embeddings generated from the target text and set of themes. For each theme, the returned score is the maximum score found for all the examples in the related set. The embeddings are generated using the hugginface's model [sentence-transformers/all-MiniLM-L6-v2](https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2).

Currently, supported themes are: `jailbreaks` and `refusals`.

Expand Down
2 changes: 2 additions & 0 deletions langkit/openai/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
OpenAIDavinci,
OpenAIGPT4,
OpenAIDefault,
OpenAILegacy,
)

__ALL__ = [
Expand All @@ -18,4 +19,5 @@
OpenAIDavinci,
OpenAIDefault,
OpenAIGPT4,
OpenAILegacy,
]
73 changes: 73 additions & 0 deletions langkit/openai/openai.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import os
from typing import Dict, List, Literal, Optional
import openai
from langkit.utils import deprecated


openai.api_key = os.getenv("OPENAI_API_KEY")
Expand Down Expand Up @@ -108,6 +109,10 @@ def copy(self) -> "LLMInvocationParams":
)


@deprecated(
message="text-davinci models were deprecated by OpenAI on Jan 4 2024. \
Please use OpenAILegacy for access to legacy models that use the Completions API"
)
@dataclass
class OpenAIDavinci(LLMInvocationParams):
model: str = field(default_factory=lambda: "text-davinci-003")
Expand Down Expand Up @@ -176,6 +181,74 @@ def copy(self) -> LLMInvocationParams:
)


@dataclass
class OpenAILegacy(LLMInvocationParams):
model: str = field(default_factory=lambda: "gpt-3.5-turbo-instruct")
temperature: float = field(default_factory=lambda: _llm_model_temperature)
max_tokens: int = field(default_factory=lambda: _llm_model_max_tokens)
frequency_penalty: float = field(
default_factory=lambda: _llm_model_frequency_penalty
)
presence_penalty: float = field(default_factory=lambda: _llm_model_presence_penalty)

def completion(self, messages: List[Dict[str, str]]):
last_message = messages[-1]
prompt = ""
if _llm_concatenate_history:
for row in messages:
content = row["content"]
prompt += f"content: {content}\n"
prompt += "content: "
elif "content" in last_message:
prompt = last_message["content"]
else:
raise ValueError(
f"last message must exist and contain a content key but got {last_message}"
)
params = asdict(self)
openai.api_key = os.getenv("OPENAI_API_KEY")
text_completion_respone = create_completion(prompt=prompt, **params)
content = text_completion_respone.choices[0].text
response = type(
"ChatCompletions",
(),
{
"choices": [
type(
"choice",
(),
{
"message": type(
"message",
(),
{"content": text_completion_respone.choices[0].text},
)
},
)
],
"usage": type(
"usage",
(),
{
"prompt_tokens": text_completion_respone.usage.prompt_tokens,
"completion_tokens": text_completion_respone.usage.completion_tokens,
"total_tokens": text_completion_respone.usage.total_tokens,
},
),
},
)
return response

def copy(self) -> LLMInvocationParams:
return OpenAIDavinci(
jamie256 marked this conversation as resolved.
Show resolved Hide resolved
model=self.model,
temperature=self.temperature,
max_tokens=self.max_tokens,
frequency_penalty=self.frequency_penalty,
presence_penalty=self.presence_penalty,
)


@dataclass
class OpenAIDefault(LLMInvocationParams):
model: str = field(default_factory=lambda: "gpt-3.5-turbo")
Expand Down
15 changes: 15 additions & 0 deletions langkit/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,21 @@
from langkit import lang_config
import string
import random
import functools
import warnings


def deprecated(message):
def decorator_deprecated(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
func(*args, **kwargs)
warnings.warn(message, DeprecationWarning, stacklevel=2)
return func(*args, **kwargs)

return wrapper

return decorator_deprecated


def _get_data_home() -> str:
Expand Down