2022-10-24 21:51:15 +00:00
|
|
|
"""Test OpenAI API wrapper."""
|
2022-12-13 14:46:01 +00:00
|
|
|
from pathlib import Path
|
2023-08-03 22:02:16 +00:00
|
|
|
from typing import Generator
|
2022-12-13 14:46:01 +00:00
|
|
|
|
2022-11-25 04:01:20 +00:00
|
|
|
import pytest
|
2023-12-11 21:53:30 +00:00
|
|
|
from langchain_core.callbacks import CallbackManager
|
2023-11-21 16:35:29 +00:00
|
|
|
from langchain_core.outputs import LLMResult
|
2022-11-25 04:01:20 +00:00
|
|
|
|
2023-12-11 21:53:30 +00:00
|
|
|
from langchain_community.chat_models.openai import ChatOpenAI
|
|
|
|
from langchain_community.llms.loading import load_llm
|
|
|
|
from langchain_community.llms.openai import OpenAI
|
2023-07-27 19:39:39 +00:00
|
|
|
from tests.unit_tests.callbacks.fake_callback_handler import (
|
|
|
|
FakeCallbackHandler,
|
|
|
|
)
|
2022-10-24 21:51:15 +00:00
|
|
|
|
|
|
|
|
2023-08-08 21:55:25 +00:00
|
|
|
@pytest.mark.scheduled
|
2022-10-26 03:22:16 +00:00
|
|
|
def test_openai_call() -> None:
|
|
|
|
"""Test valid call to openai."""
|
2023-08-08 21:55:25 +00:00
|
|
|
llm = OpenAI()
|
Use serialized format for messages in tracer (#6827)
<!-- Thank you for contributing to LangChain!
Replace this comment with:
- Description: a description of the change,
- Issue: the issue # it fixes (if applicable),
- Dependencies: any dependencies required for this change,
- Tag maintainer: for a quicker response, tag the relevant maintainer
(see below),
- Twitter handle: we announce bigger features on Twitter. If your PR
gets announced and you'd like a mention, we'll gladly shout you out!
If you're adding a new integration, please include:
1. a test for the integration, preferably unit tests that do not rely on
network access,
2. an example notebook showing its use.
Maintainer responsibilities:
- General / Misc / if you don't know who to tag: @dev2049
- DataLoaders / VectorStores / Retrievers: @rlancemartin, @eyurtsev
- Models / Prompts: @hwchase17, @dev2049
- Memory: @hwchase17
- Agents / Tools / Toolkits: @vowelparrot
- Tracing / Callbacks: @agola11
- Async: @agola11
If no one reviews your PR within a few days, feel free to @-mention the
same people again.
See contribution guidelines for more information on how to write/run
tests, lint, etc:
https://github.com/hwchase17/langchain/blob/master/.github/CONTRIBUTING.md
-->
2023-07-04 09:19:08 +00:00
|
|
|
output = llm("Say something nice:")
|
2022-10-24 21:51:15 +00:00
|
|
|
assert isinstance(output, str)
|
2022-11-25 04:01:20 +00:00
|
|
|
|
|
|
|
|
2023-03-17 04:55:55 +00:00
|
|
|
def test_openai_llm_output_contains_model_name() -> None:
|
|
|
|
"""Test llm_output contains model_name."""
|
|
|
|
llm = OpenAI(max_tokens=10)
|
|
|
|
llm_result = llm.generate(["Hello, how are you?"])
|
|
|
|
assert llm_result.llm_output is not None
|
|
|
|
assert llm_result.llm_output["model_name"] == llm.model_name
|
|
|
|
|
|
|
|
|
2022-12-01 06:20:13 +00:00
|
|
|
def test_openai_stop_valid() -> None:
|
|
|
|
"""Test openai stop logic on valid configuration."""
|
|
|
|
query = "write an ordered list of five items"
|
|
|
|
first_llm = OpenAI(stop="3", temperature=0)
|
|
|
|
first_output = first_llm(query)
|
|
|
|
second_llm = OpenAI(temperature=0)
|
|
|
|
second_output = second_llm(query, stop=["3"])
|
|
|
|
# Because it stops on new lines, shouldn't return anything
|
|
|
|
assert first_output == second_output
|
|
|
|
|
|
|
|
|
|
|
|
def test_openai_stop_error() -> None:
|
|
|
|
"""Test openai stop logic on bad configuration."""
|
|
|
|
llm = OpenAI(stop="3", temperature=0)
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
llm("write an ordered list of five items", stop=["\n"])
|
2022-12-13 14:46:01 +00:00
|
|
|
|
|
|
|
|
|
|
|
def test_saving_loading_llm(tmp_path: Path) -> None:
|
2023-03-07 23:22:05 +00:00
|
|
|
"""Test saving/loading an OpenAI LLM."""
|
2022-12-13 14:46:01 +00:00
|
|
|
llm = OpenAI(max_tokens=10)
|
|
|
|
llm.save(file_path=tmp_path / "openai.yaml")
|
|
|
|
loaded_llm = load_llm(tmp_path / "openai.yaml")
|
|
|
|
assert loaded_llm == llm
|
2022-12-17 15:02:58 +00:00
|
|
|
|
|
|
|
|
2023-08-08 21:55:25 +00:00
|
|
|
@pytest.mark.scheduled
|
2022-12-17 15:02:58 +00:00
|
|
|
def test_openai_streaming() -> None:
|
|
|
|
"""Test streaming tokens from OpenAI."""
|
|
|
|
llm = OpenAI(max_tokens=10)
|
|
|
|
generator = llm.stream("I'm Pickle Rick")
|
|
|
|
|
|
|
|
assert isinstance(generator, Generator)
|
|
|
|
|
|
|
|
for token in generator:
|
Runnable single protocol (#7800)
Objects implementing Runnable: BasePromptTemplate, LLM, ChatModel,
Chain, Retriever, OutputParser
- [x] Implement Runnable in base Retriever
- [x] Raise TypeError in operator methods for unsupported things
- [x] Implement dict which calls values in parallel and outputs dict
with results
- [x] Merge in `+` for prompts
- [x] Confirm precedence order for operators, ideal would be `+` `|`,
https://docs.python.org/3/reference/expressions.html#operator-precedence
- [x] Add support for openai functions, ie. Chat Models must return
messages
- [x] Implement BaseMessageChunk return type for BaseChatModel, a
subclass of BaseMessage which implements __add__ to return
BaseMessageChunk, concatenating all str args
- [x] Update implementation of stream/astream for llm and chat models to
use new `_stream`, `_astream` optional methods, with default
implementation in base class `raise NotImplementedError` use
https://stackoverflow.com/a/59762827 to see if it is implemented in base
class
- [x] Delete the IteratorCallbackHandler (leave the async one because
people using)
- [x] Make BaseLLMOutputParser implement Runnable, accepting either str
or BaseMessage
---------
Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-07-26 19:16:46 +00:00
|
|
|
assert isinstance(token, str)
|
|
|
|
|
|
|
|
|
2023-08-08 21:55:25 +00:00
|
|
|
@pytest.mark.scheduled
|
Runnable single protocol (#7800)
Objects implementing Runnable: BasePromptTemplate, LLM, ChatModel,
Chain, Retriever, OutputParser
- [x] Implement Runnable in base Retriever
- [x] Raise TypeError in operator methods for unsupported things
- [x] Implement dict which calls values in parallel and outputs dict
with results
- [x] Merge in `+` for prompts
- [x] Confirm precedence order for operators, ideal would be `+` `|`,
https://docs.python.org/3/reference/expressions.html#operator-precedence
- [x] Add support for openai functions, ie. Chat Models must return
messages
- [x] Implement BaseMessageChunk return type for BaseChatModel, a
subclass of BaseMessage which implements __add__ to return
BaseMessageChunk, concatenating all str args
- [x] Update implementation of stream/astream for llm and chat models to
use new `_stream`, `_astream` optional methods, with default
implementation in base class `raise NotImplementedError` use
https://stackoverflow.com/a/59762827 to see if it is implemented in base
class
- [x] Delete the IteratorCallbackHandler (leave the async one because
people using)
- [x] Make BaseLLMOutputParser implement Runnable, accepting either str
or BaseMessage
---------
Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-07-26 19:16:46 +00:00
|
|
|
async def test_openai_astream() -> None:
|
|
|
|
"""Test streaming tokens from OpenAI."""
|
|
|
|
llm = OpenAI(max_tokens=10)
|
|
|
|
|
|
|
|
async for token in llm.astream("I'm Pickle Rick"):
|
|
|
|
assert isinstance(token, str)
|
|
|
|
|
|
|
|
|
2023-08-08 21:55:25 +00:00
|
|
|
@pytest.mark.scheduled
|
Runnable single protocol (#7800)
Objects implementing Runnable: BasePromptTemplate, LLM, ChatModel,
Chain, Retriever, OutputParser
- [x] Implement Runnable in base Retriever
- [x] Raise TypeError in operator methods for unsupported things
- [x] Implement dict which calls values in parallel and outputs dict
with results
- [x] Merge in `+` for prompts
- [x] Confirm precedence order for operators, ideal would be `+` `|`,
https://docs.python.org/3/reference/expressions.html#operator-precedence
- [x] Add support for openai functions, ie. Chat Models must return
messages
- [x] Implement BaseMessageChunk return type for BaseChatModel, a
subclass of BaseMessage which implements __add__ to return
BaseMessageChunk, concatenating all str args
- [x] Update implementation of stream/astream for llm and chat models to
use new `_stream`, `_astream` optional methods, with default
implementation in base class `raise NotImplementedError` use
https://stackoverflow.com/a/59762827 to see if it is implemented in base
class
- [x] Delete the IteratorCallbackHandler (leave the async one because
people using)
- [x] Make BaseLLMOutputParser implement Runnable, accepting either str
or BaseMessage
---------
Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-07-26 19:16:46 +00:00
|
|
|
async def test_openai_abatch() -> None:
|
|
|
|
"""Test streaming tokens from OpenAI."""
|
|
|
|
llm = OpenAI(max_tokens=10)
|
|
|
|
|
|
|
|
result = await llm.abatch(["I'm Pickle Rick", "I'm not Pickle Rick"])
|
|
|
|
for token in result:
|
|
|
|
assert isinstance(token, str)
|
|
|
|
|
|
|
|
|
|
|
|
async def test_openai_abatch_tags() -> None:
|
|
|
|
"""Test streaming tokens from OpenAI."""
|
|
|
|
llm = OpenAI(max_tokens=10)
|
|
|
|
|
|
|
|
result = await llm.abatch(
|
|
|
|
["I'm Pickle Rick", "I'm not Pickle Rick"], config={"tags": ["foo"]}
|
|
|
|
)
|
|
|
|
for token in result:
|
|
|
|
assert isinstance(token, str)
|
|
|
|
|
|
|
|
|
2023-08-08 21:55:25 +00:00
|
|
|
@pytest.mark.scheduled
|
Runnable single protocol (#7800)
Objects implementing Runnable: BasePromptTemplate, LLM, ChatModel,
Chain, Retriever, OutputParser
- [x] Implement Runnable in base Retriever
- [x] Raise TypeError in operator methods for unsupported things
- [x] Implement dict which calls values in parallel and outputs dict
with results
- [x] Merge in `+` for prompts
- [x] Confirm precedence order for operators, ideal would be `+` `|`,
https://docs.python.org/3/reference/expressions.html#operator-precedence
- [x] Add support for openai functions, ie. Chat Models must return
messages
- [x] Implement BaseMessageChunk return type for BaseChatModel, a
subclass of BaseMessage which implements __add__ to return
BaseMessageChunk, concatenating all str args
- [x] Update implementation of stream/astream for llm and chat models to
use new `_stream`, `_astream` optional methods, with default
implementation in base class `raise NotImplementedError` use
https://stackoverflow.com/a/59762827 to see if it is implemented in base
class
- [x] Delete the IteratorCallbackHandler (leave the async one because
people using)
- [x] Make BaseLLMOutputParser implement Runnable, accepting either str
or BaseMessage
---------
Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-07-26 19:16:46 +00:00
|
|
|
def test_openai_batch() -> None:
|
|
|
|
"""Test streaming tokens from OpenAI."""
|
|
|
|
llm = OpenAI(max_tokens=10)
|
|
|
|
|
|
|
|
result = llm.batch(["I'm Pickle Rick", "I'm not Pickle Rick"])
|
|
|
|
for token in result:
|
|
|
|
assert isinstance(token, str)
|
|
|
|
|
|
|
|
|
2023-08-08 21:55:25 +00:00
|
|
|
@pytest.mark.scheduled
|
Runnable single protocol (#7800)
Objects implementing Runnable: BasePromptTemplate, LLM, ChatModel,
Chain, Retriever, OutputParser
- [x] Implement Runnable in base Retriever
- [x] Raise TypeError in operator methods for unsupported things
- [x] Implement dict which calls values in parallel and outputs dict
with results
- [x] Merge in `+` for prompts
- [x] Confirm precedence order for operators, ideal would be `+` `|`,
https://docs.python.org/3/reference/expressions.html#operator-precedence
- [x] Add support for openai functions, ie. Chat Models must return
messages
- [x] Implement BaseMessageChunk return type for BaseChatModel, a
subclass of BaseMessage which implements __add__ to return
BaseMessageChunk, concatenating all str args
- [x] Update implementation of stream/astream for llm and chat models to
use new `_stream`, `_astream` optional methods, with default
implementation in base class `raise NotImplementedError` use
https://stackoverflow.com/a/59762827 to see if it is implemented in base
class
- [x] Delete the IteratorCallbackHandler (leave the async one because
people using)
- [x] Make BaseLLMOutputParser implement Runnable, accepting either str
or BaseMessage
---------
Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-07-26 19:16:46 +00:00
|
|
|
async def test_openai_ainvoke() -> None:
|
|
|
|
"""Test streaming tokens from OpenAI."""
|
|
|
|
llm = OpenAI(max_tokens=10)
|
|
|
|
|
|
|
|
result = await llm.ainvoke("I'm Pickle Rick", config={"tags": ["foo"]})
|
|
|
|
assert isinstance(result, str)
|
|
|
|
|
|
|
|
|
2023-08-08 21:55:25 +00:00
|
|
|
@pytest.mark.scheduled
|
Runnable single protocol (#7800)
Objects implementing Runnable: BasePromptTemplate, LLM, ChatModel,
Chain, Retriever, OutputParser
- [x] Implement Runnable in base Retriever
- [x] Raise TypeError in operator methods for unsupported things
- [x] Implement dict which calls values in parallel and outputs dict
with results
- [x] Merge in `+` for prompts
- [x] Confirm precedence order for operators, ideal would be `+` `|`,
https://docs.python.org/3/reference/expressions.html#operator-precedence
- [x] Add support for openai functions, ie. Chat Models must return
messages
- [x] Implement BaseMessageChunk return type for BaseChatModel, a
subclass of BaseMessage which implements __add__ to return
BaseMessageChunk, concatenating all str args
- [x] Update implementation of stream/astream for llm and chat models to
use new `_stream`, `_astream` optional methods, with default
implementation in base class `raise NotImplementedError` use
https://stackoverflow.com/a/59762827 to see if it is implemented in base
class
- [x] Delete the IteratorCallbackHandler (leave the async one because
people using)
- [x] Make BaseLLMOutputParser implement Runnable, accepting either str
or BaseMessage
---------
Co-authored-by: Eugene Yurtsev <eyurtsev@gmail.com>
2023-07-26 19:16:46 +00:00
|
|
|
def test_openai_invoke() -> None:
|
|
|
|
"""Test streaming tokens from OpenAI."""
|
|
|
|
llm = OpenAI(max_tokens=10)
|
|
|
|
|
|
|
|
result = llm.invoke("I'm Pickle Rick", config=dict(tags=["foo"]))
|
|
|
|
assert isinstance(result, str)
|
2022-12-17 15:02:58 +00:00
|
|
|
|
|
|
|
|
2023-08-08 21:55:25 +00:00
|
|
|
@pytest.mark.scheduled
|
2023-06-25 04:03:31 +00:00
|
|
|
def test_openai_multiple_prompts() -> None:
|
|
|
|
"""Test completion with multiple prompts."""
|
|
|
|
llm = OpenAI(max_tokens=10)
|
|
|
|
output = llm.generate(["I'm Pickle Rick", "I'm Pickle Rick"])
|
|
|
|
assert isinstance(output, LLMResult)
|
|
|
|
assert isinstance(output.generations, list)
|
|
|
|
assert len(output.generations) == 2
|
|
|
|
|
|
|
|
|
2023-02-14 23:06:14 +00:00
|
|
|
def test_openai_streaming_best_of_error() -> None:
|
|
|
|
"""Test validation for streaming fails if best_of is not 1."""
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
OpenAI(best_of=2, streaming=True)
|
|
|
|
|
|
|
|
|
|
|
|
def test_openai_streaming_n_error() -> None:
|
|
|
|
"""Test validation for streaming fails if n is not 1."""
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
OpenAI(n=2, streaming=True)
|
|
|
|
|
|
|
|
|
|
|
|
def test_openai_streaming_multiple_prompts_error() -> None:
|
|
|
|
"""Test validation for streaming fails if multiple prompts are given."""
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
OpenAI(streaming=True).generate(["I'm Pickle Rick", "I'm Pickle Rick"])
|
|
|
|
|
|
|
|
|
2023-08-08 21:55:25 +00:00
|
|
|
@pytest.mark.scheduled
|
2023-02-14 23:06:14 +00:00
|
|
|
def test_openai_streaming_call() -> None:
|
|
|
|
"""Test valid call to openai."""
|
|
|
|
llm = OpenAI(max_tokens=10, streaming=True)
|
|
|
|
output = llm("Say foo:")
|
|
|
|
assert isinstance(output, str)
|
|
|
|
|
|
|
|
|
|
|
|
def test_openai_streaming_callback() -> None:
|
|
|
|
"""Test that streaming correctly invokes on_llm_new_token callback."""
|
|
|
|
callback_handler = FakeCallbackHandler()
|
|
|
|
callback_manager = CallbackManager([callback_handler])
|
|
|
|
llm = OpenAI(
|
|
|
|
max_tokens=10,
|
|
|
|
streaming=True,
|
|
|
|
temperature=0,
|
|
|
|
callback_manager=callback_manager,
|
|
|
|
verbose=True,
|
|
|
|
)
|
|
|
|
llm("Write me a sentence with 100 words.")
|
|
|
|
assert callback_handler.llm_streams == 10
|
|
|
|
|
|
|
|
|
2023-08-08 21:55:25 +00:00
|
|
|
@pytest.mark.scheduled
|
2023-02-08 05:21:57 +00:00
|
|
|
async def test_openai_async_generate() -> None:
|
|
|
|
"""Test async generation."""
|
|
|
|
llm = OpenAI(max_tokens=10)
|
|
|
|
output = await llm.agenerate(["Hello, how are you?"])
|
|
|
|
assert isinstance(output, LLMResult)
|
2023-02-14 23:06:14 +00:00
|
|
|
|
|
|
|
|
|
|
|
async def test_openai_async_streaming_callback() -> None:
|
|
|
|
"""Test that streaming correctly invokes on_llm_new_token callback."""
|
|
|
|
callback_handler = FakeCallbackHandler()
|
|
|
|
callback_manager = CallbackManager([callback_handler])
|
|
|
|
llm = OpenAI(
|
|
|
|
max_tokens=10,
|
|
|
|
streaming=True,
|
|
|
|
temperature=0,
|
|
|
|
callback_manager=callback_manager,
|
|
|
|
verbose=True,
|
|
|
|
)
|
|
|
|
result = await llm.agenerate(["Write me a sentence with 100 words."])
|
|
|
|
assert callback_handler.llm_streams == 10
|
|
|
|
assert isinstance(result, LLMResult)
|
2023-03-02 05:55:43 +00:00
|
|
|
|
|
|
|
|
2023-04-13 18:13:34 +00:00
|
|
|
def test_openai_modelname_to_contextsize_valid() -> None:
|
|
|
|
"""Test model name to context size on a valid model."""
|
|
|
|
assert OpenAI().modelname_to_contextsize("davinci") == 2049
|
|
|
|
|
|
|
|
|
|
|
|
def test_openai_modelname_to_contextsize_invalid() -> None:
|
|
|
|
"""Test model name to context size on an invalid model."""
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
OpenAI().modelname_to_contextsize("foobar")
|
2023-05-22 13:17:26 +00:00
|
|
|
|
|
|
|
|
|
|
|
_EXPECTED_NUM_TOKENS = {
|
|
|
|
"ada": 17,
|
|
|
|
"babbage": 17,
|
|
|
|
"curie": 17,
|
|
|
|
"davinci": 17,
|
|
|
|
"gpt-4": 12,
|
|
|
|
"gpt-4-32k": 12,
|
|
|
|
"gpt-3.5-turbo": 12,
|
|
|
|
}
|
|
|
|
|
|
|
|
_MODELS = models = [
|
|
|
|
"ada",
|
|
|
|
"babbage",
|
|
|
|
"curie",
|
|
|
|
"davinci",
|
|
|
|
]
|
|
|
|
_CHAT_MODELS = [
|
|
|
|
"gpt-4",
|
|
|
|
"gpt-4-32k",
|
|
|
|
"gpt-3.5-turbo",
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("model", _MODELS)
|
|
|
|
def test_openai_get_num_tokens(model: str) -> None:
|
|
|
|
"""Test get_tokens."""
|
|
|
|
llm = OpenAI(model=model)
|
|
|
|
assert llm.get_num_tokens("表情符号是\n🦜🔗") == _EXPECTED_NUM_TOKENS[model]
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.mark.parametrize("model", _CHAT_MODELS)
|
|
|
|
def test_chat_openai_get_num_tokens(model: str) -> None:
|
|
|
|
"""Test get_tokens."""
|
|
|
|
llm = ChatOpenAI(model=model)
|
|
|
|
assert llm.get_num_tokens("表情符号是\n🦜🔗") == _EXPECTED_NUM_TOKENS[model]
|
2023-07-27 19:39:39 +00:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def mock_completion() -> dict:
|
|
|
|
return {
|
|
|
|
"id": "cmpl-3evkmQda5Hu7fcZavknQda3SQ",
|
|
|
|
"object": "text_completion",
|
|
|
|
"created": 1689989000,
|
2023-12-18 21:49:46 +00:00
|
|
|
"model": "gpt-3.5-turbo-instruct",
|
2023-07-27 19:39:39 +00:00
|
|
|
"choices": [
|
|
|
|
{"text": "Bar Baz", "index": 0, "logprobs": None, "finish_reason": "length"}
|
|
|
|
],
|
|
|
|
"usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3},
|
|
|
|
}
|