|
|
|
@ -33,8 +33,9 @@ from langchain.utils.utils import build_extra_kwargs
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def update_token_usage(keys: Set[str], response: Dict[str, Any],
|
|
|
|
|
token_usage: Dict[str, Any]) -> None:
|
|
|
|
|
def update_token_usage(
|
|
|
|
|
keys: Set[str], response: Dict[str, Any], token_usage: Dict[str, Any]
|
|
|
|
|
) -> None:
|
|
|
|
|
"""Update token usage."""
|
|
|
|
|
_keys_to_use = keys.intersection(response["usage"])
|
|
|
|
|
for _key in _keys_to_use:
|
|
|
|
@ -45,42 +46,44 @@ def update_token_usage(keys: Set[str], response: Dict[str, Any],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _stream_response_to_generation_chunk(
|
|
|
|
|
stream_response: Dict[str, Any],) -> GenerationChunk:
|
|
|
|
|
stream_response: Dict[str, Any],
|
|
|
|
|
) -> GenerationChunk:
|
|
|
|
|
"""Convert a stream response to a generation chunk."""
|
|
|
|
|
return GenerationChunk(
|
|
|
|
|
text=stream_response["choices"][0]["text"],
|
|
|
|
|
generation_info=dict(
|
|
|
|
|
finish_reason=stream_response["choices"][0].get(
|
|
|
|
|
"finish_reason", None),
|
|
|
|
|
finish_reason=stream_response["choices"][0].get("finish_reason", None),
|
|
|
|
|
logprobs=stream_response["choices"][0].get("logprobs", None),
|
|
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _update_response(response: Dict[str, Any],
|
|
|
|
|
stream_response: Dict[str, Any]) -> None:
|
|
|
|
|
def _update_response(response: Dict[str, Any], stream_response: Dict[str, Any]) -> None:
|
|
|
|
|
"""Update response from the stream response."""
|
|
|
|
|
response["choices"][0]["text"] += stream_response["choices"][0]["text"]
|
|
|
|
|
response["choices"][0]["finish_reason"] = stream_response["choices"][0].get(
|
|
|
|
|
"finish_reason", None)
|
|
|
|
|
response["choices"][0]["logprobs"] = stream_response["choices"][0][
|
|
|
|
|
"logprobs"]
|
|
|
|
|
"finish_reason", None
|
|
|
|
|
)
|
|
|
|
|
response["choices"][0]["logprobs"] = stream_response["choices"][0]["logprobs"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _streaming_response_template() -> Dict[str, Any]:
|
|
|
|
|
return {
|
|
|
|
|
"choices": [{
|
|
|
|
|
"choices": [
|
|
|
|
|
{
|
|
|
|
|
"text": "",
|
|
|
|
|
"finish_reason": None,
|
|
|
|
|
"logprobs": None,
|
|
|
|
|
}]
|
|
|
|
|
}
|
|
|
|
|
]
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _create_retry_decorator(
|
|
|
|
|
llm: Union[BaseOpenAI, OpenAIChat],
|
|
|
|
|
run_manager: Optional[Union[AsyncCallbackManagerForLLMRun,
|
|
|
|
|
CallbackManagerForLLMRun]] = None,
|
|
|
|
|
run_manager: Optional[
|
|
|
|
|
Union[AsyncCallbackManagerForLLMRun, CallbackManagerForLLMRun]
|
|
|
|
|
] = None,
|
|
|
|
|
) -> Callable[[Any], Any]:
|
|
|
|
|
import openai
|
|
|
|
|
|
|
|
|
@ -91,9 +94,9 @@ def _create_retry_decorator(
|
|
|
|
|
openai.error.RateLimitError,
|
|
|
|
|
openai.error.ServiceUnavailableError,
|
|
|
|
|
]
|
|
|
|
|
return create_base_retry_decorator(error_types=errors,
|
|
|
|
|
max_retries=llm.max_retries,
|
|
|
|
|
run_manager=run_manager)
|
|
|
|
|
return create_base_retry_decorator(
|
|
|
|
|
error_types=errors, max_retries=llm.max_retries, run_manager=run_manager
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def completion_with_retry(
|
|
|
|
@ -203,8 +206,7 @@ class BaseOpenAI(BaseLLM):
|
|
|
|
|
API but with different models. In those cases, in order to avoid erroring
|
|
|
|
|
when tiktoken is called, you can specify a model name to use here."""
|
|
|
|
|
|
|
|
|
|
def __new__(cls,
|
|
|
|
|
**data: Any) -> Union[OpenAIChat, BaseOpenAI]: # type: ignore
|
|
|
|
|
def __new__(cls, **data: Any) -> Union[OpenAIChat, BaseOpenAI]: # type: ignore
|
|
|
|
|
"""Initialize the OpenAI object."""
|
|
|
|
|
data.get("model_name", "")
|
|
|
|
|
return super().__new__(cls)
|
|
|
|
@ -219,16 +221,17 @@ class BaseOpenAI(BaseLLM):
|
|
|
|
|
"""Build extra kwargs from additional params that were passed in."""
|
|
|
|
|
all_required_field_names = get_pydantic_field_names(cls)
|
|
|
|
|
extra = values.get("model_kwargs", {})
|
|
|
|
|
values["model_kwargs"] = build_extra_kwargs(extra, values,
|
|
|
|
|
all_required_field_names)
|
|
|
|
|
values["model_kwargs"] = build_extra_kwargs(
|
|
|
|
|
extra, values, all_required_field_names
|
|
|
|
|
)
|
|
|
|
|
return values
|
|
|
|
|
|
|
|
|
|
@root_validator()
|
|
|
|
|
def validate_environment(cls, values: Dict) -> Dict:
|
|
|
|
|
"""Validate that api key and python package exists in environment."""
|
|
|
|
|
values["openai_api_key"] = get_from_dict_or_env(values,
|
|
|
|
|
"openai_api_key",
|
|
|
|
|
"OPENAI_API_KEY")
|
|
|
|
|
values["openai_api_key"] = get_from_dict_or_env(
|
|
|
|
|
values, "openai_api_key", "OPENAI_API_KEY"
|
|
|
|
|
)
|
|
|
|
|
values["openai_api_base"] = get_from_dict_or_env(
|
|
|
|
|
values,
|
|
|
|
|
"openai_api_base",
|
|
|
|
@ -252,8 +255,10 @@ class BaseOpenAI(BaseLLM):
|
|
|
|
|
|
|
|
|
|
values["client"] = openai.Completion
|
|
|
|
|
except ImportError:
|
|
|
|
|
raise ImportError("Could not import openai python package. "
|
|
|
|
|
"Please install it with `pip install openai`.")
|
|
|
|
|
raise ImportError(
|
|
|
|
|
"Could not import openai python package. "
|
|
|
|
|
"Please install it with `pip install openai`."
|
|
|
|
|
)
|
|
|
|
|
if values["streaming"] and values["n"] > 1:
|
|
|
|
|
raise ValueError("Cannot stream results when n > 1.")
|
|
|
|
|
if values["streaming"] and values["best_of"] > 1:
|
|
|
|
@ -290,10 +295,9 @@ class BaseOpenAI(BaseLLM):
|
|
|
|
|
) -> Iterator[GenerationChunk]:
|
|
|
|
|
params = {**self._invocation_params, **kwargs, "stream": True}
|
|
|
|
|
self.get_sub_prompts(params, [prompt], stop) # this mutates params
|
|
|
|
|
for stream_resp in completion_with_retry(self,
|
|
|
|
|
prompt=prompt,
|
|
|
|
|
run_manager=run_manager,
|
|
|
|
|
**params):
|
|
|
|
|
for stream_resp in completion_with_retry(
|
|
|
|
|
self, prompt=prompt, run_manager=run_manager, **params
|
|
|
|
|
):
|
|
|
|
|
chunk = _stream_response_to_generation_chunk(stream_resp)
|
|
|
|
|
yield chunk
|
|
|
|
|
if run_manager:
|
|
|
|
@ -302,7 +306,8 @@ class BaseOpenAI(BaseLLM):
|
|
|
|
|
chunk=chunk,
|
|
|
|
|
verbose=self.verbose,
|
|
|
|
|
logprobs=chunk.generation_info["logprobs"]
|
|
|
|
|
if chunk.generation_info else None,
|
|
|
|
|
if chunk.generation_info
|
|
|
|
|
else None,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
async def _astream(
|
|
|
|
@ -315,7 +320,8 @@ class BaseOpenAI(BaseLLM):
|
|
|
|
|
params = {**self._invocation_params, **kwargs, "stream": True}
|
|
|
|
|
self.get_sub_prompts(params, [prompt], stop) # this mutate params
|
|
|
|
|
async for stream_resp in await acompletion_with_retry(
|
|
|
|
|
self, prompt=prompt, run_manager=run_manager, **params):
|
|
|
|
|
self, prompt=prompt, run_manager=run_manager, **params
|
|
|
|
|
):
|
|
|
|
|
chunk = _stream_response_to_generation_chunk(stream_resp)
|
|
|
|
|
yield chunk
|
|
|
|
|
if run_manager:
|
|
|
|
@ -324,7 +330,8 @@ class BaseOpenAI(BaseLLM):
|
|
|
|
|
chunk=chunk,
|
|
|
|
|
verbose=self.verbose,
|
|
|
|
|
logprobs=chunk.generation_info["logprobs"]
|
|
|
|
|
if chunk.generation_info else None,
|
|
|
|
|
if chunk.generation_info
|
|
|
|
|
else None,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
def _generate(
|
|
|
|
@ -360,32 +367,30 @@ class BaseOpenAI(BaseLLM):
|
|
|
|
|
for _prompts in sub_prompts:
|
|
|
|
|
if self.streaming:
|
|
|
|
|
if len(_prompts) > 1:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"Cannot stream results with multiple prompts.")
|
|
|
|
|
raise ValueError("Cannot stream results with multiple prompts.")
|
|
|
|
|
|
|
|
|
|
generation: Optional[GenerationChunk] = None
|
|
|
|
|
for chunk in self._stream(_prompts[0], stop, run_manager,
|
|
|
|
|
**kwargs):
|
|
|
|
|
for chunk in self._stream(_prompts[0], stop, run_manager, **kwargs):
|
|
|
|
|
if generation is None:
|
|
|
|
|
generation = chunk
|
|
|
|
|
else:
|
|
|
|
|
generation += chunk
|
|
|
|
|
assert generation is not None
|
|
|
|
|
choices.append({
|
|
|
|
|
"text":
|
|
|
|
|
generation.text,
|
|
|
|
|
"finish_reason":
|
|
|
|
|
generation.generation_info.get("finish_reason")
|
|
|
|
|
if generation.generation_info else None,
|
|
|
|
|
"logprobs":
|
|
|
|
|
generation.generation_info.get("logprobs")
|
|
|
|
|
if generation.generation_info else None,
|
|
|
|
|
})
|
|
|
|
|
choices.append(
|
|
|
|
|
{
|
|
|
|
|
"text": generation.text,
|
|
|
|
|
"finish_reason": generation.generation_info.get("finish_reason")
|
|
|
|
|
if generation.generation_info
|
|
|
|
|
else None,
|
|
|
|
|
"logprobs": generation.generation_info.get("logprobs")
|
|
|
|
|
if generation.generation_info
|
|
|
|
|
else None,
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
response = completion_with_retry(self,
|
|
|
|
|
prompt=_prompts,
|
|
|
|
|
run_manager=run_manager,
|
|
|
|
|
**params)
|
|
|
|
|
response = completion_with_retry(
|
|
|
|
|
self, prompt=_prompts, run_manager=run_manager, **params
|
|
|
|
|
)
|
|
|
|
|
choices.extend(response["choices"])
|
|
|
|
|
update_token_usage(_keys, response, token_usage)
|
|
|
|
|
return self.create_llm_result(choices, prompts, token_usage)
|
|
|
|
@ -409,32 +414,32 @@ class BaseOpenAI(BaseLLM):
|
|
|
|
|
for _prompts in sub_prompts:
|
|
|
|
|
if self.streaming:
|
|
|
|
|
if len(_prompts) > 1:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"Cannot stream results with multiple prompts.")
|
|
|
|
|
raise ValueError("Cannot stream results with multiple prompts.")
|
|
|
|
|
|
|
|
|
|
generation: Optional[GenerationChunk] = None
|
|
|
|
|
async for chunk in self._astream(_prompts[0], stop, run_manager,
|
|
|
|
|
**kwargs):
|
|
|
|
|
async for chunk in self._astream(
|
|
|
|
|
_prompts[0], stop, run_manager, **kwargs
|
|
|
|
|
):
|
|
|
|
|
if generation is None:
|
|
|
|
|
generation = chunk
|
|
|
|
|
else:
|
|
|
|
|
generation += chunk
|
|
|
|
|
assert generation is not None
|
|
|
|
|
choices.append({
|
|
|
|
|
"text":
|
|
|
|
|
generation.text,
|
|
|
|
|
"finish_reason":
|
|
|
|
|
generation.generation_info.get("finish_reason")
|
|
|
|
|
if generation.generation_info else None,
|
|
|
|
|
"logprobs":
|
|
|
|
|
generation.generation_info.get("logprobs")
|
|
|
|
|
if generation.generation_info else None,
|
|
|
|
|
})
|
|
|
|
|
choices.append(
|
|
|
|
|
{
|
|
|
|
|
"text": generation.text,
|
|
|
|
|
"finish_reason": generation.generation_info.get("finish_reason")
|
|
|
|
|
if generation.generation_info
|
|
|
|
|
else None,
|
|
|
|
|
"logprobs": generation.generation_info.get("logprobs")
|
|
|
|
|
if generation.generation_info
|
|
|
|
|
else None,
|
|
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
else:
|
|
|
|
|
response = await acompletion_with_retry(self,
|
|
|
|
|
prompt=_prompts,
|
|
|
|
|
run_manager=run_manager,
|
|
|
|
|
**params)
|
|
|
|
|
response = await acompletion_with_retry(
|
|
|
|
|
self, prompt=_prompts, run_manager=run_manager, **params
|
|
|
|
|
)
|
|
|
|
|
choices.extend(response["choices"])
|
|
|
|
|
update_token_usage(_keys, response, token_usage)
|
|
|
|
|
return self.create_llm_result(choices, prompts, token_usage)
|
|
|
|
@ -448,13 +453,13 @@ class BaseOpenAI(BaseLLM):
|
|
|
|
|
"""Get the sub prompts for llm call."""
|
|
|
|
|
if stop is not None:
|
|
|
|
|
if "stop" in params:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"`stop` found in both the input and default params.")
|
|
|
|
|
raise ValueError("`stop` found in both the input and default params.")
|
|
|
|
|
params["stop"] = stop
|
|
|
|
|
if params["max_tokens"] == -1:
|
|
|
|
|
if len(prompts) != 1:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"max_tokens set to -1 not supported for multiple inputs.")
|
|
|
|
|
"max_tokens set to -1 not supported for multiple inputs."
|
|
|
|
|
)
|
|
|
|
|
params["max_tokens"] = self.max_tokens_for_prompt(prompts[0])
|
|
|
|
|
sub_prompts = [
|
|
|
|
|
prompts[i : i + self.batch_size]
|
|
|
|
@ -462,21 +467,25 @@ class BaseOpenAI(BaseLLM):
|
|
|
|
|
]
|
|
|
|
|
return sub_prompts
|
|
|
|
|
|
|
|
|
|
def create_llm_result(self, choices: Any, prompts: List[str],
|
|
|
|
|
token_usage: Dict[str, int]) -> LLMResult:
|
|
|
|
|
def create_llm_result(
|
|
|
|
|
self, choices: Any, prompts: List[str], token_usage: Dict[str, int]
|
|
|
|
|
) -> LLMResult:
|
|
|
|
|
"""Create the LLMResult from the choices and prompts."""
|
|
|
|
|
generations = []
|
|
|
|
|
for i, _ in enumerate(prompts):
|
|
|
|
|
sub_choices = choices[i * self.n : (i + 1) * self.n]
|
|
|
|
|
generations.append([
|
|
|
|
|
generations.append(
|
|
|
|
|
[
|
|
|
|
|
Generation(
|
|
|
|
|
text=choice["text"],
|
|
|
|
|
generation_info=dict(
|
|
|
|
|
finish_reason=choice.get("finish_reason"),
|
|
|
|
|
logprobs=choice.get("logprobs"),
|
|
|
|
|
),
|
|
|
|
|
) for choice in sub_choices
|
|
|
|
|
])
|
|
|
|
|
)
|
|
|
|
|
for choice in sub_choices
|
|
|
|
|
]
|
|
|
|
|
)
|
|
|
|
|
llm_output = {"token_usage": token_usage, "model_name": self.model_name}
|
|
|
|
|
return LLMResult(generations=generations, llm_output=llm_output)
|
|
|
|
|
|
|
|
|
@ -518,14 +527,14 @@ class BaseOpenAI(BaseLLM):
|
|
|
|
|
raise ImportError(
|
|
|
|
|
"Could not import tiktoken python package. "
|
|
|
|
|
"This is needed in order to calculate get_num_tokens. "
|
|
|
|
|
"Please install it with `pip install tiktoken`.")
|
|
|
|
|
"Please install it with `pip install tiktoken`."
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
model_name = self.tiktoken_model_name or self.model_name
|
|
|
|
|
try:
|
|
|
|
|
enc = tiktoken.encoding_for_model(model_name)
|
|
|
|
|
except KeyError:
|
|
|
|
|
logger.warning(
|
|
|
|
|
"Warning: model not found. Using cl100k_base encoding.")
|
|
|
|
|
logger.warning("Warning: model not found. Using cl100k_base encoding.")
|
|
|
|
|
model = "cl100k_base"
|
|
|
|
|
enc = tiktoken.get_encoding(model)
|
|
|
|
|
|
|
|
|
@ -587,7 +596,8 @@ class BaseOpenAI(BaseLLM):
|
|
|
|
|
if context_size is None:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
f"Unknown model: {modelname}. Please provide a valid OpenAI model name."
|
|
|
|
|
"Known models are: " + ", ".join(model_token_mapping.keys()))
|
|
|
|
|
"Known models are: " + ", ".join(model_token_mapping.keys())
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
return context_size
|
|
|
|
|
|
|
|
|
@ -665,15 +675,14 @@ class AzureOpenAI(BaseOpenAI):
|
|
|
|
|
"OPENAI_API_VERSION",
|
|
|
|
|
)
|
|
|
|
|
values["openai_api_type"] = get_from_dict_or_env(
|
|
|
|
|
values, "openai_api_type", "OPENAI_API_TYPE", "azure")
|
|
|
|
|
values, "openai_api_type", "OPENAI_API_TYPE", "azure"
|
|
|
|
|
)
|
|
|
|
|
return values
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
|
def _identifying_params(self) -> Mapping[str, Any]:
|
|
|
|
|
return {
|
|
|
|
|
**{
|
|
|
|
|
"deployment_name": self.deployment_name
|
|
|
|
|
},
|
|
|
|
|
**{"deployment_name": self.deployment_name},
|
|
|
|
|
**super()._identifying_params,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
@ -738,9 +747,7 @@ class OpenAIChat(BaseLLM):
|
|
|
|
|
@root_validator(pre=True)
|
|
|
|
|
def build_extra(cls, values: Dict[str, Any]) -> Dict[str, Any]:
|
|
|
|
|
"""Build extra kwargs from additional params that were passed in."""
|
|
|
|
|
all_required_field_names = {
|
|
|
|
|
field.alias for field in cls.__fields__.values()
|
|
|
|
|
}
|
|
|
|
|
all_required_field_names = {field.alias for field in cls.__fields__.values()}
|
|
|
|
|
|
|
|
|
|
extra = values.get("model_kwargs", {})
|
|
|
|
|
for field_name in list(values):
|
|
|
|
@ -754,8 +761,9 @@ class OpenAIChat(BaseLLM):
|
|
|
|
|
@root_validator()
|
|
|
|
|
def validate_environment(cls, values: Dict) -> Dict:
|
|
|
|
|
"""Validate that api key and python package exists in environment."""
|
|
|
|
|
openai_api_key = get_from_dict_or_env(values, "openai_api_key",
|
|
|
|
|
"OPENAI_API_KEY")
|
|
|
|
|
openai_api_key = get_from_dict_or_env(
|
|
|
|
|
values, "openai_api_key", "OPENAI_API_KEY"
|
|
|
|
|
)
|
|
|
|
|
openai_api_base = get_from_dict_or_env(
|
|
|
|
|
values,
|
|
|
|
|
"openai_api_base",
|
|
|
|
@ -768,10 +776,9 @@ class OpenAIChat(BaseLLM):
|
|
|
|
|
"OPENAI_PROXY",
|
|
|
|
|
default="",
|
|
|
|
|
)
|
|
|
|
|
openai_organization = get_from_dict_or_env(values,
|
|
|
|
|
"openai_organization",
|
|
|
|
|
"OPENAI_ORGANIZATION",
|
|
|
|
|
default="")
|
|
|
|
|
openai_organization = get_from_dict_or_env(
|
|
|
|
|
values, "openai_organization", "OPENAI_ORGANIZATION", default=""
|
|
|
|
|
)
|
|
|
|
|
try:
|
|
|
|
|
import openai
|
|
|
|
|
|
|
|
|
@ -786,15 +793,18 @@ class OpenAIChat(BaseLLM):
|
|
|
|
|
"https": openai_proxy,
|
|
|
|
|
} # type: ignore[assignment] # noqa: E501
|
|
|
|
|
except ImportError:
|
|
|
|
|
raise ImportError("Could not import openai python package. "
|
|
|
|
|
"Please install it with `pip install openai`.")
|
|
|
|
|
raise ImportError(
|
|
|
|
|
"Could not import openai python package. "
|
|
|
|
|
"Please install it with `pip install openai`."
|
|
|
|
|
)
|
|
|
|
|
try:
|
|
|
|
|
values["client"] = openai.ChatCompletion
|
|
|
|
|
except AttributeError:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"`openai` has no `ChatCompletion` attribute, this is likely "
|
|
|
|
|
"due to an old version of the openai package. Try upgrading it "
|
|
|
|
|
"with `pip install --upgrade openai`.")
|
|
|
|
|
"with `pip install --upgrade openai`."
|
|
|
|
|
)
|
|
|
|
|
return values
|
|
|
|
|
|
|
|
|
|
@property
|
|
|
|
@ -802,27 +812,18 @@ class OpenAIChat(BaseLLM):
|
|
|
|
|
"""Get the default parameters for calling OpenAI API."""
|
|
|
|
|
return self.model_kwargs
|
|
|
|
|
|
|
|
|
|
def _get_chat_params(self,
|
|
|
|
|
prompts: List[str],
|
|
|
|
|
stop: Optional[List[str]] = None) -> Tuple:
|
|
|
|
|
def _get_chat_params(
|
|
|
|
|
self, prompts: List[str], stop: Optional[List[str]] = None
|
|
|
|
|
) -> Tuple:
|
|
|
|
|
if len(prompts) > 1:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
f"OpenAIChat currently only supports single prompt, got {prompts}"
|
|
|
|
|
)
|
|
|
|
|
messages = self.prefix_messages + [{
|
|
|
|
|
"role": "user",
|
|
|
|
|
"content": prompts[0]
|
|
|
|
|
}]
|
|
|
|
|
params: Dict[str, Any] = {
|
|
|
|
|
**{
|
|
|
|
|
"model": self.model_name
|
|
|
|
|
},
|
|
|
|
|
**self._default_params
|
|
|
|
|
}
|
|
|
|
|
messages = self.prefix_messages + [{"role": "user", "content": prompts[0]}]
|
|
|
|
|
params: Dict[str, Any] = {**{"model": self.model_name}, **self._default_params}
|
|
|
|
|
if stop is not None:
|
|
|
|
|
if "stop" in params:
|
|
|
|
|
raise ValueError(
|
|
|
|
|
"`stop` found in both the input and default params.")
|
|
|
|
|
raise ValueError("`stop` found in both the input and default params.")
|
|
|
|
|
params["stop"] = stop
|
|
|
|
|
if params.get("max_tokens") == -1:
|
|
|
|
|
# for ChatGPT api, omitting max_tokens is equivalent to having no limit
|
|
|
|
@ -838,10 +839,9 @@ class OpenAIChat(BaseLLM):
|
|
|
|
|
) -> Iterator[GenerationChunk]:
|
|
|
|
|
messages, params = self._get_chat_params([prompt], stop)
|
|
|
|
|
params = {**params, **kwargs, "stream": True}
|
|
|
|
|
for stream_resp in completion_with_retry(self,
|
|
|
|
|
messages=messages,
|
|
|
|
|
run_manager=run_manager,
|
|
|
|
|
**params):
|
|
|
|
|
for stream_resp in completion_with_retry(
|
|
|
|
|
self, messages=messages, run_manager=run_manager, **params
|
|
|
|
|
):
|
|
|
|
|
token = stream_resp["choices"][0]["delta"].get("content", "")
|
|
|
|
|
chunk = GenerationChunk(text=token)
|
|
|
|
|
yield chunk
|
|
|
|
@ -858,7 +858,8 @@ class OpenAIChat(BaseLLM):
|
|
|
|
|
messages, params = self._get_chat_params([prompt], stop)
|
|
|
|
|
params = {**params, **kwargs, "stream": True}
|
|
|
|
|
async for stream_resp in await acompletion_with_retry(
|
|
|
|
|
self, messages=messages, run_manager=run_manager, **params):
|
|
|
|
|
self, messages=messages, run_manager=run_manager, **params
|
|
|
|
|
):
|
|
|
|
|
token = stream_resp["choices"][0]["delta"].get("content", "")
|
|
|
|
|
chunk = GenerationChunk(text=token)
|
|
|
|
|
yield chunk
|
|
|
|
@ -884,19 +885,17 @@ class OpenAIChat(BaseLLM):
|
|
|
|
|
|
|
|
|
|
messages, params = self._get_chat_params(prompts, stop)
|
|
|
|
|
params = {**params, **kwargs}
|
|
|
|
|
full_response = completion_with_retry(self,
|
|
|
|
|
messages=messages,
|
|
|
|
|
run_manager=run_manager,
|
|
|
|
|
**params)
|
|
|
|
|
full_response = completion_with_retry(
|
|
|
|
|
self, messages=messages, run_manager=run_manager, **params
|
|
|
|
|
)
|
|
|
|
|
llm_output = {
|
|
|
|
|
"token_usage": full_response["usage"],
|
|
|
|
|
"model_name": self.model_name,
|
|
|
|
|
}
|
|
|
|
|
return LLMResult(
|
|
|
|
|
generations=[[
|
|
|
|
|
Generation(
|
|
|
|
|
text=full_response["choices"][0]["message"]["content"])
|
|
|
|
|
]],
|
|
|
|
|
generations=[
|
|
|
|
|
[Generation(text=full_response["choices"][0]["message"]["content"])]
|
|
|
|
|
],
|
|
|
|
|
llm_output=llm_output,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
@ -909,8 +908,7 @@ class OpenAIChat(BaseLLM):
|
|
|
|
|
) -> LLMResult:
|
|
|
|
|
if self.streaming:
|
|
|
|
|
generation: Optional[GenerationChunk] = None
|
|
|
|
|
async for chunk in self._astream(prompts[0], stop, run_manager,
|
|
|
|
|
**kwargs):
|
|
|
|
|
async for chunk in self._astream(prompts[0], stop, run_manager, **kwargs):
|
|
|
|
|
if generation is None:
|
|
|
|
|
generation = chunk
|
|
|
|
|
else:
|
|
|
|
@ -920,19 +918,17 @@ class OpenAIChat(BaseLLM):
|
|
|
|
|
|
|
|
|
|
messages, params = self._get_chat_params(prompts, stop)
|
|
|
|
|
params = {**params, **kwargs}
|
|
|
|
|
full_response = await acompletion_with_retry(self,
|
|
|
|
|
messages=messages,
|
|
|
|
|
run_manager=run_manager,
|
|
|
|
|
**params)
|
|
|
|
|
full_response = await acompletion_with_retry(
|
|
|
|
|
self, messages=messages, run_manager=run_manager, **params
|
|
|
|
|
)
|
|
|
|
|
llm_output = {
|
|
|
|
|
"token_usage": full_response["usage"],
|
|
|
|
|
"model_name": self.model_name,
|
|
|
|
|
}
|
|
|
|
|
return LLMResult(
|
|
|
|
|
generations=[[
|
|
|
|
|
Generation(
|
|
|
|
|
text=full_response["choices"][0]["message"]["content"])
|
|
|
|
|
]],
|
|
|
|
|
generations=[
|
|
|
|
|
[Generation(text=full_response["choices"][0]["message"]["content"])]
|
|
|
|
|
],
|
|
|
|
|
llm_output=llm_output,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
@ -957,7 +953,8 @@ class OpenAIChat(BaseLLM):
|
|
|
|
|
raise ImportError(
|
|
|
|
|
"Could not import tiktoken python package. "
|
|
|
|
|
"This is needed in order to calculate get_num_tokens. "
|
|
|
|
|
"Please install it with `pip install tiktoken`.")
|
|
|
|
|
"Please install it with `pip install tiktoken`."
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
enc = tiktoken.encoding_for_model(self.model_name)
|
|
|
|
|
return enc.encode(
|
|
|
|
|