2024-05-09 15:40:36 +02:00
|
|
|
# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
|
|
|
|
#
|
|
|
|
# SPDX-License-Identifier: Apache-2.0
|
2025-01-08 11:28:00 +01:00
|
|
|
from unittest.mock import patch
|
2024-12-20 15:20:54 +01:00
|
|
|
import pytest
|
|
|
|
|
2025-01-08 11:28:00 +01:00
|
|
|
|
2024-04-12 16:07:18 +02:00
|
|
|
import logging
|
2023-11-09 10:45:41 +01:00
|
|
|
import os
|
2024-12-20 15:20:54 +01:00
|
|
|
from datetime import datetime
|
2023-11-09 10:45:41 +01:00
|
|
|
|
2023-12-21 16:21:24 +01:00
|
|
|
from openai import OpenAIError
|
2024-12-20 15:20:54 +01:00
|
|
|
from openai.types.chat import ChatCompletion, ChatCompletionChunk, ChatCompletionMessage, ChatCompletionMessageToolCall
|
|
|
|
from openai.types.chat.chat_completion import Choice
|
|
|
|
from openai.types.chat.chat_completion_message_tool_call import Function
|
|
|
|
from openai.types.chat import chat_completion_chunk
|
2023-11-09 10:45:41 +01:00
|
|
|
|
2024-01-26 16:00:02 +01:00
|
|
|
from haystack.components.generators.utils import print_streaming_chunk
|
2024-12-20 15:20:54 +01:00
|
|
|
from haystack.dataclasses import StreamingChunk
|
2024-04-12 16:07:18 +02:00
|
|
|
from haystack.utils.auth import Secret
|
2025-01-09 12:30:13 +01:00
|
|
|
from haystack.dataclasses import ChatMessage, ToolCall
|
|
|
|
from haystack.tools import Tool
|
2024-12-20 15:20:54 +01:00
|
|
|
from haystack.components.generators.chat.openai import OpenAIChatGenerator
|
2023-11-09 10:45:41 +01:00
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def chat_messages():
|
|
|
|
return [
|
|
|
|
ChatMessage.from_system("You are a helpful assistant"),
|
|
|
|
ChatMessage.from_user("What's the capital of France"),
|
|
|
|
]
|
|
|
|
|
|
|
|
|
2024-12-20 15:20:54 +01:00
|
|
|
@pytest.fixture
|
|
|
|
def mock_chat_completion_chunk_with_tools(openai_mock_stream):
|
|
|
|
"""
|
|
|
|
Mock the OpenAI API completion chunk response and reuse it for tests
|
|
|
|
"""
|
|
|
|
|
|
|
|
with patch("openai.resources.chat.completions.Completions.create") as mock_chat_completion_create:
|
|
|
|
completion = ChatCompletionChunk(
|
|
|
|
id="foo",
|
|
|
|
model="gpt-4",
|
|
|
|
object="chat.completion.chunk",
|
|
|
|
choices=[
|
|
|
|
chat_completion_chunk.Choice(
|
|
|
|
finish_reason="tool_calls",
|
|
|
|
logprobs=None,
|
|
|
|
index=0,
|
|
|
|
delta=chat_completion_chunk.ChoiceDelta(
|
|
|
|
role="assistant",
|
|
|
|
tool_calls=[
|
|
|
|
chat_completion_chunk.ChoiceDeltaToolCall(
|
|
|
|
index=0,
|
|
|
|
id="123",
|
|
|
|
type="function",
|
|
|
|
function=chat_completion_chunk.ChoiceDeltaToolCallFunction(
|
|
|
|
name="weather", arguments='{"city": "Paris"}'
|
|
|
|
),
|
|
|
|
)
|
|
|
|
],
|
|
|
|
),
|
|
|
|
)
|
|
|
|
],
|
|
|
|
created=int(datetime.now().timestamp()),
|
|
|
|
usage={"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97},
|
|
|
|
)
|
|
|
|
mock_chat_completion_create.return_value = openai_mock_stream(
|
|
|
|
completion, cast_to=None, response=None, client=None
|
|
|
|
)
|
|
|
|
yield mock_chat_completion_create
|
|
|
|
|
|
|
|
|
|
|
|
@pytest.fixture
|
|
|
|
def tools():
|
|
|
|
tool_parameters = {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
|
|
|
|
tool = Tool(
|
|
|
|
name="weather",
|
|
|
|
description="useful to determine the weather in a given location",
|
|
|
|
parameters=tool_parameters,
|
|
|
|
function=lambda x: x,
|
|
|
|
)
|
|
|
|
|
|
|
|
return [tool]
|
|
|
|
|
|
|
|
|
2023-12-22 19:37:29 +01:00
|
|
|
class TestOpenAIChatGenerator:
|
2024-02-05 13:17:01 +01:00
|
|
|
def test_init_default(self, monkeypatch):
|
|
|
|
monkeypatch.setenv("OPENAI_API_KEY", "test-api-key")
|
|
|
|
component = OpenAIChatGenerator()
|
2023-12-21 16:21:24 +01:00
|
|
|
assert component.client.api_key == "test-api-key"
|
2024-09-17 10:36:42 +02:00
|
|
|
assert component.model == "gpt-4o-mini"
|
2023-11-09 10:45:41 +01:00
|
|
|
assert component.streaming_callback is None
|
|
|
|
assert not component.generation_kwargs
|
2024-05-15 23:58:41 +02:00
|
|
|
assert component.client.timeout == 30
|
|
|
|
assert component.client.max_retries == 5
|
2024-12-20 15:20:54 +01:00
|
|
|
assert component.tools is None
|
|
|
|
assert not component.tools_strict
|
2023-11-09 10:45:41 +01:00
|
|
|
|
|
|
|
def test_init_fail_wo_api_key(self, monkeypatch):
|
|
|
|
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
|
2024-12-20 15:20:54 +01:00
|
|
|
with pytest.raises(ValueError):
|
2023-12-22 19:37:29 +01:00
|
|
|
OpenAIChatGenerator()
|
2023-11-09 10:45:41 +01:00
|
|
|
|
2024-12-20 15:20:54 +01:00
|
|
|
def test_init_fail_with_duplicate_tool_names(self, monkeypatch, tools):
|
|
|
|
monkeypatch.setenv("OPENAI_API_KEY", "test-api-key")
|
|
|
|
|
|
|
|
duplicate_tools = [tools[0], tools[0]]
|
|
|
|
with pytest.raises(ValueError):
|
|
|
|
OpenAIChatGenerator(tools=duplicate_tools)
|
|
|
|
|
2024-05-15 23:58:41 +02:00
|
|
|
def test_init_with_parameters(self, monkeypatch):
|
2024-12-20 15:20:54 +01:00
|
|
|
tool = Tool(name="name", description="description", parameters={"x": {"type": "string"}}, function=lambda x: x)
|
|
|
|
|
2024-05-15 23:58:41 +02:00
|
|
|
monkeypatch.setenv("OPENAI_TIMEOUT", "100")
|
|
|
|
monkeypatch.setenv("OPENAI_MAX_RETRIES", "10")
|
2023-12-22 19:37:29 +01:00
|
|
|
component = OpenAIChatGenerator(
|
2024-02-05 13:17:01 +01:00
|
|
|
api_key=Secret.from_token("test-api-key"),
|
2024-09-17 10:36:42 +02:00
|
|
|
model="gpt-4o-mini",
|
2024-01-26 16:00:02 +01:00
|
|
|
streaming_callback=print_streaming_chunk,
|
2023-11-09 10:45:41 +01:00
|
|
|
api_base_url="test-base-url",
|
2023-11-22 10:40:48 +01:00
|
|
|
generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"},
|
2024-05-15 23:58:41 +02:00
|
|
|
timeout=40.0,
|
|
|
|
max_retries=1,
|
2024-12-20 15:20:54 +01:00
|
|
|
tools=[tool],
|
|
|
|
tools_strict=True,
|
2023-11-09 10:45:41 +01:00
|
|
|
)
|
2023-12-21 16:21:24 +01:00
|
|
|
assert component.client.api_key == "test-api-key"
|
2024-09-17 10:36:42 +02:00
|
|
|
assert component.model == "gpt-4o-mini"
|
2024-01-26 16:00:02 +01:00
|
|
|
assert component.streaming_callback is print_streaming_chunk
|
2023-11-09 10:45:41 +01:00
|
|
|
assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"}
|
2024-05-15 23:58:41 +02:00
|
|
|
assert component.client.timeout == 40.0
|
|
|
|
assert component.client.max_retries == 1
|
2024-12-20 15:20:54 +01:00
|
|
|
assert component.tools == [tool]
|
|
|
|
assert component.tools_strict
|
2024-05-15 23:58:41 +02:00
|
|
|
|
|
|
|
def test_init_with_parameters_and_env_vars(self, monkeypatch):
|
|
|
|
monkeypatch.setenv("OPENAI_TIMEOUT", "100")
|
|
|
|
monkeypatch.setenv("OPENAI_MAX_RETRIES", "10")
|
|
|
|
component = OpenAIChatGenerator(
|
|
|
|
api_key=Secret.from_token("test-api-key"),
|
2024-09-17 10:36:42 +02:00
|
|
|
model="gpt-4o-mini",
|
2024-05-15 23:58:41 +02:00
|
|
|
streaming_callback=print_streaming_chunk,
|
|
|
|
api_base_url="test-base-url",
|
|
|
|
generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"},
|
|
|
|
)
|
|
|
|
assert component.client.api_key == "test-api-key"
|
2024-09-17 10:36:42 +02:00
|
|
|
assert component.model == "gpt-4o-mini"
|
2024-05-15 23:58:41 +02:00
|
|
|
assert component.streaming_callback is print_streaming_chunk
|
|
|
|
assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"}
|
|
|
|
assert component.client.timeout == 100.0
|
|
|
|
assert component.client.max_retries == 10
|
2023-11-09 10:45:41 +01:00
|
|
|
|
2024-02-05 13:17:01 +01:00
|
|
|
def test_to_dict_default(self, monkeypatch):
|
|
|
|
monkeypatch.setenv("OPENAI_API_KEY", "test-api-key")
|
|
|
|
component = OpenAIChatGenerator()
|
2023-11-09 10:45:41 +01:00
|
|
|
data = component.to_dict()
|
|
|
|
assert data == {
|
2023-12-22 19:37:29 +01:00
|
|
|
"type": "haystack.components.generators.chat.openai.OpenAIChatGenerator",
|
2023-11-09 10:45:41 +01:00
|
|
|
"init_parameters": {
|
2024-02-05 13:17:01 +01:00
|
|
|
"api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"},
|
2024-09-17 10:36:42 +02:00
|
|
|
"model": "gpt-4o-mini",
|
2023-12-21 16:21:24 +01:00
|
|
|
"organization": None,
|
2023-11-09 10:45:41 +01:00
|
|
|
"streaming_callback": None,
|
2023-12-21 16:21:24 +01:00
|
|
|
"api_base_url": None,
|
2023-11-22 10:40:48 +01:00
|
|
|
"generation_kwargs": {},
|
2024-12-20 15:20:54 +01:00
|
|
|
"tools": None,
|
|
|
|
"tools_strict": False,
|
|
|
|
"max_retries": None,
|
|
|
|
"timeout": None,
|
2023-11-09 10:45:41 +01:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2024-02-05 13:17:01 +01:00
|
|
|
def test_to_dict_with_parameters(self, monkeypatch):
|
2024-12-20 15:20:54 +01:00
|
|
|
tool = Tool(name="name", description="description", parameters={"x": {"type": "string"}}, function=print)
|
|
|
|
|
2024-02-05 13:17:01 +01:00
|
|
|
monkeypatch.setenv("ENV_VAR", "test-api-key")
|
2023-12-22 19:37:29 +01:00
|
|
|
component = OpenAIChatGenerator(
|
2024-02-05 13:17:01 +01:00
|
|
|
api_key=Secret.from_env_var("ENV_VAR"),
|
2024-09-17 10:36:42 +02:00
|
|
|
model="gpt-4o-mini",
|
2024-01-26 16:00:02 +01:00
|
|
|
streaming_callback=print_streaming_chunk,
|
2023-11-09 10:45:41 +01:00
|
|
|
api_base_url="test-base-url",
|
2023-11-22 10:40:48 +01:00
|
|
|
generation_kwargs={"max_tokens": 10, "some_test_param": "test-params"},
|
2024-12-20 15:20:54 +01:00
|
|
|
tools=[tool],
|
|
|
|
tools_strict=True,
|
|
|
|
max_retries=10,
|
|
|
|
timeout=100.0,
|
2023-11-09 10:45:41 +01:00
|
|
|
)
|
|
|
|
data = component.to_dict()
|
2024-12-20 15:20:54 +01:00
|
|
|
|
2023-11-09 10:45:41 +01:00
|
|
|
assert data == {
|
2023-12-22 19:37:29 +01:00
|
|
|
"type": "haystack.components.generators.chat.openai.OpenAIChatGenerator",
|
2023-11-09 10:45:41 +01:00
|
|
|
"init_parameters": {
|
2024-02-05 13:17:01 +01:00
|
|
|
"api_key": {"env_vars": ["ENV_VAR"], "strict": True, "type": "env_var"},
|
2024-09-17 10:36:42 +02:00
|
|
|
"model": "gpt-4o-mini",
|
2023-12-21 16:21:24 +01:00
|
|
|
"organization": None,
|
2023-11-09 10:45:41 +01:00
|
|
|
"api_base_url": "test-base-url",
|
2024-12-20 15:20:54 +01:00
|
|
|
"max_retries": 10,
|
|
|
|
"timeout": 100.0,
|
2024-01-26 16:00:02 +01:00
|
|
|
"streaming_callback": "haystack.components.generators.utils.print_streaming_chunk",
|
2023-11-22 10:40:48 +01:00
|
|
|
"generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"},
|
2024-12-20 15:20:54 +01:00
|
|
|
"tools": [
|
|
|
|
{
|
2025-01-09 12:30:13 +01:00
|
|
|
"type": "haystack.tools.tool.Tool",
|
|
|
|
"data": {
|
|
|
|
"description": "description",
|
|
|
|
"function": "builtins.print",
|
|
|
|
"name": "name",
|
|
|
|
"parameters": {"x": {"type": "string"}},
|
|
|
|
},
|
2024-12-20 15:20:54 +01:00
|
|
|
}
|
|
|
|
],
|
|
|
|
"tools_strict": True,
|
2023-11-09 10:45:41 +01:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2024-02-05 13:17:01 +01:00
|
|
|
def test_from_dict(self, monkeypatch):
|
|
|
|
monkeypatch.setenv("OPENAI_API_KEY", "fake-api-key")
|
2023-11-09 10:45:41 +01:00
|
|
|
data = {
|
2023-12-22 19:37:29 +01:00
|
|
|
"type": "haystack.components.generators.chat.openai.OpenAIChatGenerator",
|
2023-11-09 10:45:41 +01:00
|
|
|
"init_parameters": {
|
2024-02-05 13:17:01 +01:00
|
|
|
"api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"},
|
2024-09-17 10:36:42 +02:00
|
|
|
"model": "gpt-4o-mini",
|
2023-11-09 10:45:41 +01:00
|
|
|
"api_base_url": "test-base-url",
|
2024-01-26 16:00:02 +01:00
|
|
|
"streaming_callback": "haystack.components.generators.utils.print_streaming_chunk",
|
2024-12-20 15:20:54 +01:00
|
|
|
"max_retries": 10,
|
|
|
|
"timeout": 100.0,
|
2023-11-22 10:40:48 +01:00
|
|
|
"generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"},
|
2024-12-20 15:20:54 +01:00
|
|
|
"tools": [
|
|
|
|
{
|
2025-01-09 12:30:13 +01:00
|
|
|
"type": "haystack.tools.tool.Tool",
|
|
|
|
"data": {
|
|
|
|
"description": "description",
|
|
|
|
"function": "builtins.print",
|
|
|
|
"name": "name",
|
|
|
|
"parameters": {"x": {"type": "string"}},
|
|
|
|
},
|
2024-12-20 15:20:54 +01:00
|
|
|
}
|
|
|
|
],
|
|
|
|
"tools_strict": True,
|
2023-11-09 10:45:41 +01:00
|
|
|
},
|
|
|
|
}
|
2023-12-22 19:37:29 +01:00
|
|
|
component = OpenAIChatGenerator.from_dict(data)
|
2024-12-20 15:20:54 +01:00
|
|
|
|
|
|
|
assert isinstance(component, OpenAIChatGenerator)
|
2024-09-17 10:36:42 +02:00
|
|
|
assert component.model == "gpt-4o-mini"
|
2024-01-26 16:00:02 +01:00
|
|
|
assert component.streaming_callback is print_streaming_chunk
|
2023-11-09 10:45:41 +01:00
|
|
|
assert component.api_base_url == "test-base-url"
|
|
|
|
assert component.generation_kwargs == {"max_tokens": 10, "some_test_param": "test-params"}
|
2024-02-05 13:17:01 +01:00
|
|
|
assert component.api_key == Secret.from_env_var("OPENAI_API_KEY")
|
2024-12-20 15:20:54 +01:00
|
|
|
assert component.tools == [
|
|
|
|
Tool(name="name", description="description", parameters={"x": {"type": "string"}}, function=print)
|
|
|
|
]
|
|
|
|
assert component.tools_strict
|
|
|
|
assert component.client.timeout == 100.0
|
|
|
|
assert component.client.max_retries == 10
|
2023-11-09 10:45:41 +01:00
|
|
|
|
|
|
|
def test_from_dict_fail_wo_env_var(self, monkeypatch):
|
|
|
|
monkeypatch.delenv("OPENAI_API_KEY", raising=False)
|
|
|
|
data = {
|
2023-12-22 19:37:29 +01:00
|
|
|
"type": "haystack.components.generators.chat.openai.OpenAIChatGenerator",
|
2023-11-09 10:45:41 +01:00
|
|
|
"init_parameters": {
|
2024-02-05 13:17:01 +01:00
|
|
|
"api_key": {"env_vars": ["OPENAI_API_KEY"], "strict": True, "type": "env_var"},
|
2024-12-20 15:20:54 +01:00
|
|
|
"model": "gpt-4",
|
2023-12-21 16:21:24 +01:00
|
|
|
"organization": None,
|
2023-11-09 10:45:41 +01:00
|
|
|
"api_base_url": "test-base-url",
|
2024-01-26 16:00:02 +01:00
|
|
|
"streaming_callback": "haystack.components.generators.utils.print_streaming_chunk",
|
2023-11-22 10:40:48 +01:00
|
|
|
"generation_kwargs": {"max_tokens": 10, "some_test_param": "test-params"},
|
2023-11-09 10:45:41 +01:00
|
|
|
},
|
|
|
|
}
|
2024-12-20 15:20:54 +01:00
|
|
|
with pytest.raises(ValueError):
|
2023-12-22 19:37:29 +01:00
|
|
|
OpenAIChatGenerator.from_dict(data)
|
2023-11-09 10:45:41 +01:00
|
|
|
|
2024-12-20 15:20:54 +01:00
|
|
|
def test_run(self, chat_messages, openai_mock_chat_completion):
|
2024-02-05 13:17:01 +01:00
|
|
|
component = OpenAIChatGenerator(api_key=Secret.from_token("test-api-key"))
|
2023-11-09 10:45:41 +01:00
|
|
|
response = component.run(chat_messages)
|
|
|
|
|
|
|
|
# check that the component returns the correct ChatMessage response
|
|
|
|
assert isinstance(response, dict)
|
|
|
|
assert "replies" in response
|
|
|
|
assert isinstance(response["replies"], list)
|
|
|
|
assert len(response["replies"]) == 1
|
|
|
|
assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
|
|
|
|
|
2024-12-20 15:20:54 +01:00
|
|
|
def test_run_with_params(self, chat_messages, openai_mock_chat_completion):
|
2024-02-05 13:17:01 +01:00
|
|
|
component = OpenAIChatGenerator(
|
|
|
|
api_key=Secret.from_token("test-api-key"), generation_kwargs={"max_tokens": 10, "temperature": 0.5}
|
|
|
|
)
|
2023-11-09 10:45:41 +01:00
|
|
|
response = component.run(chat_messages)
|
|
|
|
|
|
|
|
# check that the component calls the OpenAI API with the correct parameters
|
2024-12-20 15:20:54 +01:00
|
|
|
_, kwargs = openai_mock_chat_completion.call_args
|
2023-11-09 10:45:41 +01:00
|
|
|
assert kwargs["max_tokens"] == 10
|
|
|
|
assert kwargs["temperature"] == 0.5
|
|
|
|
|
2025-01-10 14:46:41 +01:00
|
|
|
# check that the tools are not passed to the OpenAI API (the generator is initialized without tools)
|
|
|
|
assert "tools" not in kwargs
|
|
|
|
|
2023-11-09 10:45:41 +01:00
|
|
|
# check that the component returns the correct response
|
|
|
|
assert isinstance(response, dict)
|
|
|
|
assert "replies" in response
|
|
|
|
assert isinstance(response["replies"], list)
|
|
|
|
assert len(response["replies"]) == 1
|
|
|
|
assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
|
|
|
|
|
2024-12-20 15:20:54 +01:00
|
|
|
def test_run_with_params_streaming(self, chat_messages, openai_mock_chat_completion_chunk):
|
2023-12-21 16:21:24 +01:00
|
|
|
streaming_callback_called = False
|
2023-11-09 10:45:41 +01:00
|
|
|
|
2023-12-21 16:21:24 +01:00
|
|
|
def streaming_callback(chunk: StreamingChunk) -> None:
|
|
|
|
nonlocal streaming_callback_called
|
|
|
|
streaming_callback_called = True
|
2023-11-09 10:45:41 +01:00
|
|
|
|
2024-02-05 13:17:01 +01:00
|
|
|
component = OpenAIChatGenerator(
|
|
|
|
api_key=Secret.from_token("test-api-key"), streaming_callback=streaming_callback
|
|
|
|
)
|
2023-12-21 16:21:24 +01:00
|
|
|
response = component.run(chat_messages)
|
2023-11-09 10:45:41 +01:00
|
|
|
|
2023-12-21 16:21:24 +01:00
|
|
|
# check we called the streaming callback
|
|
|
|
assert streaming_callback_called
|
2023-11-09 10:45:41 +01:00
|
|
|
|
2023-12-21 16:21:24 +01:00
|
|
|
# check that the component still returns the correct response
|
|
|
|
assert isinstance(response, dict)
|
2023-11-09 10:45:41 +01:00
|
|
|
assert "replies" in response
|
|
|
|
assert isinstance(response["replies"], list)
|
2023-12-21 16:21:24 +01:00
|
|
|
assert len(response["replies"]) == 1
|
2023-11-09 10:45:41 +01:00
|
|
|
assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
|
2024-12-20 15:20:54 +01:00
|
|
|
assert "Hello" in response["replies"][0].text # see openai_mock_chat_completion_chunk
|
2023-11-09 10:45:41 +01:00
|
|
|
|
2024-12-20 15:20:54 +01:00
|
|
|
def test_run_with_streaming_callback_in_run_method(self, chat_messages, openai_mock_chat_completion_chunk):
|
2024-07-24 15:49:19 +02:00
|
|
|
streaming_callback_called = False
|
|
|
|
|
|
|
|
def streaming_callback(chunk: StreamingChunk) -> None:
|
|
|
|
nonlocal streaming_callback_called
|
|
|
|
streaming_callback_called = True
|
|
|
|
|
|
|
|
component = OpenAIChatGenerator(api_key=Secret.from_token("test-api-key"))
|
|
|
|
response = component.run(chat_messages, streaming_callback=streaming_callback)
|
|
|
|
|
|
|
|
# check we called the streaming callback
|
|
|
|
assert streaming_callback_called
|
|
|
|
|
|
|
|
# check that the component still returns the correct response
|
|
|
|
assert isinstance(response, dict)
|
|
|
|
assert "replies" in response
|
|
|
|
assert isinstance(response["replies"], list)
|
|
|
|
assert len(response["replies"]) == 1
|
|
|
|
assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
|
2024-12-20 15:20:54 +01:00
|
|
|
assert "Hello" in response["replies"][0].text # see openai_mock_chat_completion_chunk
|
2024-10-31 23:56:17 +08:00
|
|
|
|
2023-11-09 10:45:41 +01:00
|
|
|
def test_check_abnormal_completions(self, caplog):
|
2024-04-12 16:07:18 +02:00
|
|
|
caplog.set_level(logging.INFO)
|
2024-02-05 13:17:01 +01:00
|
|
|
component = OpenAIChatGenerator(api_key=Secret.from_token("test-api-key"))
|
2023-11-09 10:45:41 +01:00
|
|
|
messages = [
|
|
|
|
ChatMessage.from_assistant(
|
2023-12-21 17:09:58 +05:30
|
|
|
"", meta={"finish_reason": "content_filter" if i % 2 == 0 else "length", "index": i}
|
2023-11-09 10:45:41 +01:00
|
|
|
)
|
|
|
|
for i, _ in enumerate(range(4))
|
|
|
|
]
|
|
|
|
|
|
|
|
for m in messages:
|
2024-12-20 15:20:54 +01:00
|
|
|
component._check_finish_reason(m.meta)
|
2023-11-09 10:45:41 +01:00
|
|
|
|
|
|
|
# check truncation warning
|
|
|
|
message_template = (
|
|
|
|
"The completion for index {index} has been truncated before reaching a natural stopping point. "
|
|
|
|
"Increase the max_tokens parameter to allow for longer completions."
|
|
|
|
)
|
|
|
|
|
|
|
|
for index in [1, 3]:
|
|
|
|
assert caplog.records[index].message == message_template.format(index=index)
|
|
|
|
|
|
|
|
# check content filter warning
|
|
|
|
message_template = "The completion for index {index} has been truncated due to the content filter."
|
|
|
|
for index in [0, 2]:
|
|
|
|
assert caplog.records[index].message == message_template.format(index=index)
|
|
|
|
|
2024-12-20 15:20:54 +01:00
|
|
|
def test_run_with_tools(self, tools):
|
|
|
|
with patch("openai.resources.chat.completions.Completions.create") as mock_chat_completion_create:
|
|
|
|
completion = ChatCompletion(
|
|
|
|
id="foo",
|
|
|
|
model="gpt-4",
|
|
|
|
object="chat.completion",
|
|
|
|
choices=[
|
|
|
|
Choice(
|
|
|
|
finish_reason="tool_calls",
|
|
|
|
logprobs=None,
|
|
|
|
index=0,
|
|
|
|
message=ChatCompletionMessage(
|
|
|
|
role="assistant",
|
|
|
|
tool_calls=[
|
|
|
|
ChatCompletionMessageToolCall(
|
|
|
|
id="123",
|
|
|
|
type="function",
|
|
|
|
function=Function(name="weather", arguments='{"city": "Paris"}'),
|
|
|
|
)
|
|
|
|
],
|
|
|
|
),
|
|
|
|
)
|
|
|
|
],
|
|
|
|
created=int(datetime.now().timestamp()),
|
|
|
|
usage={"prompt_tokens": 57, "completion_tokens": 40, "total_tokens": 97},
|
|
|
|
)
|
|
|
|
|
|
|
|
mock_chat_completion_create.return_value = completion
|
|
|
|
|
2025-01-10 14:46:41 +01:00
|
|
|
component = OpenAIChatGenerator(api_key=Secret.from_token("test-api-key"), tools=tools, tools_strict=True)
|
2024-12-20 15:20:54 +01:00
|
|
|
response = component.run([ChatMessage.from_user("What's the weather like in Paris?")])
|
|
|
|
|
2025-01-10 14:46:41 +01:00
|
|
|
# ensure that the tools are passed to the OpenAI API
|
|
|
|
assert mock_chat_completion_create.call_args[1]["tools"] == [
|
|
|
|
{"type": "function", "function": {**tools[0].tool_spec, "strict": True}}
|
|
|
|
]
|
|
|
|
|
2024-12-20 15:20:54 +01:00
|
|
|
assert len(response["replies"]) == 1
|
|
|
|
message = response["replies"][0]
|
|
|
|
|
|
|
|
assert not message.texts
|
|
|
|
assert not message.text
|
|
|
|
|
|
|
|
assert message.tool_calls
|
|
|
|
tool_call = message.tool_call
|
|
|
|
assert isinstance(tool_call, ToolCall)
|
|
|
|
assert tool_call.tool_name == "weather"
|
|
|
|
assert tool_call.arguments == {"city": "Paris"}
|
|
|
|
assert message.meta["finish_reason"] == "tool_calls"
|
|
|
|
|
|
|
|
def test_run_with_tools_streaming(self, mock_chat_completion_chunk_with_tools, tools):
|
|
|
|
streaming_callback_called = False
|
|
|
|
|
|
|
|
def streaming_callback(chunk: StreamingChunk) -> None:
|
|
|
|
nonlocal streaming_callback_called
|
|
|
|
streaming_callback_called = True
|
|
|
|
|
|
|
|
component = OpenAIChatGenerator(
|
|
|
|
api_key=Secret.from_token("test-api-key"), streaming_callback=streaming_callback
|
|
|
|
)
|
|
|
|
chat_messages = [ChatMessage.from_user("What's the weather like in Paris?")]
|
|
|
|
response = component.run(chat_messages, tools=tools)
|
|
|
|
|
|
|
|
# check we called the streaming callback
|
|
|
|
assert streaming_callback_called
|
|
|
|
|
|
|
|
# check that the component still returns the correct response
|
|
|
|
assert isinstance(response, dict)
|
|
|
|
assert "replies" in response
|
|
|
|
assert isinstance(response["replies"], list)
|
|
|
|
assert len(response["replies"]) == 1
|
|
|
|
assert [isinstance(reply, ChatMessage) for reply in response["replies"]]
|
|
|
|
|
|
|
|
message = response["replies"][0]
|
|
|
|
|
|
|
|
assert message.tool_calls
|
|
|
|
tool_call = message.tool_call
|
|
|
|
assert isinstance(tool_call, ToolCall)
|
|
|
|
assert tool_call.tool_name == "weather"
|
|
|
|
assert tool_call.arguments == {"city": "Paris"}
|
|
|
|
assert message.meta["finish_reason"] == "tool_calls"
|
|
|
|
|
|
|
|
def test_invalid_tool_call_json(self, tools, caplog):
|
|
|
|
caplog.set_level(logging.WARNING)
|
|
|
|
|
|
|
|
with patch("openai.resources.chat.completions.Completions.create") as mock_create:
|
|
|
|
mock_create.return_value = ChatCompletion(
|
|
|
|
id="test",
|
|
|
|
model="gpt-4o-mini",
|
|
|
|
object="chat.completion",
|
|
|
|
choices=[
|
|
|
|
Choice(
|
|
|
|
finish_reason="tool_calls",
|
|
|
|
index=0,
|
|
|
|
message=ChatCompletionMessage(
|
|
|
|
role="assistant",
|
|
|
|
tool_calls=[
|
|
|
|
ChatCompletionMessageToolCall(
|
|
|
|
id="1",
|
|
|
|
type="function",
|
|
|
|
function=Function(name="weather", arguments='"invalid": "json"'),
|
|
|
|
)
|
|
|
|
],
|
|
|
|
),
|
|
|
|
)
|
|
|
|
],
|
|
|
|
created=1234567890,
|
|
|
|
usage={"prompt_tokens": 50, "completion_tokens": 30, "total_tokens": 80},
|
|
|
|
)
|
|
|
|
|
|
|
|
component = OpenAIChatGenerator(api_key=Secret.from_token("test-api-key"), tools=tools)
|
|
|
|
response = component.run([ChatMessage.from_user("What's the weather in Paris?")])
|
|
|
|
|
|
|
|
assert len(response["replies"]) == 1
|
|
|
|
message = response["replies"][0]
|
|
|
|
assert len(message.tool_calls) == 0
|
|
|
|
assert "OpenAI returned a malformed JSON string for tool call arguments" in caplog.text
|
|
|
|
|
2023-11-09 10:45:41 +01:00
|
|
|
@pytest.mark.skipif(
|
|
|
|
not os.environ.get("OPENAI_API_KEY", None),
|
|
|
|
reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.",
|
|
|
|
)
|
|
|
|
@pytest.mark.integration
|
|
|
|
def test_live_run(self):
|
|
|
|
chat_messages = [ChatMessage.from_user("What's the capital of France")]
|
2024-02-05 13:17:01 +01:00
|
|
|
component = OpenAIChatGenerator(generation_kwargs={"n": 1})
|
2023-11-09 10:45:41 +01:00
|
|
|
results = component.run(chat_messages)
|
|
|
|
assert len(results["replies"]) == 1
|
|
|
|
message: ChatMessage = results["replies"][0]
|
2024-11-28 11:16:07 +01:00
|
|
|
assert "Paris" in message.text
|
2024-12-20 15:20:54 +01:00
|
|
|
assert "gpt-4o" in message.meta["model"]
|
2023-12-21 14:09:31 +01:00
|
|
|
assert message.meta["finish_reason"] == "stop"
|
2023-11-09 10:45:41 +01:00
|
|
|
|
|
|
|
@pytest.mark.skipif(
|
|
|
|
not os.environ.get("OPENAI_API_KEY", None),
|
|
|
|
reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.",
|
|
|
|
)
|
|
|
|
@pytest.mark.integration
|
|
|
|
def test_live_run_wrong_model(self, chat_messages):
|
2024-02-05 13:17:01 +01:00
|
|
|
component = OpenAIChatGenerator(model="something-obviously-wrong")
|
2023-12-21 16:21:24 +01:00
|
|
|
with pytest.raises(OpenAIError):
|
2023-11-09 10:45:41 +01:00
|
|
|
component.run(chat_messages)
|
|
|
|
|
|
|
|
@pytest.mark.skipif(
|
|
|
|
not os.environ.get("OPENAI_API_KEY", None),
|
|
|
|
reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.",
|
|
|
|
)
|
|
|
|
@pytest.mark.integration
|
|
|
|
def test_live_run_streaming(self):
|
|
|
|
class Callback:
|
|
|
|
def __init__(self):
|
|
|
|
self.responses = ""
|
|
|
|
self.counter = 0
|
|
|
|
|
|
|
|
def __call__(self, chunk: StreamingChunk) -> None:
|
|
|
|
self.counter += 1
|
|
|
|
self.responses += chunk.content if chunk.content else ""
|
|
|
|
|
|
|
|
callback = Callback()
|
2023-12-22 19:37:29 +01:00
|
|
|
component = OpenAIChatGenerator(streaming_callback=callback)
|
2023-11-09 10:45:41 +01:00
|
|
|
results = component.run([ChatMessage.from_user("What's the capital of France?")])
|
|
|
|
|
|
|
|
assert len(results["replies"]) == 1
|
|
|
|
message: ChatMessage = results["replies"][0]
|
2024-11-28 11:16:07 +01:00
|
|
|
assert "Paris" in message.text
|
2023-11-09 10:45:41 +01:00
|
|
|
|
2024-12-20 15:20:54 +01:00
|
|
|
assert "gpt-4o" in message.meta["model"]
|
2023-12-21 14:09:31 +01:00
|
|
|
assert message.meta["finish_reason"] == "stop"
|
2023-11-09 10:45:41 +01:00
|
|
|
|
|
|
|
assert callback.counter > 1
|
|
|
|
assert "Paris" in callback.responses
|
2024-11-20 10:27:22 +01:00
|
|
|
|
2025-01-17 09:58:45 +01:00
|
|
|
# check that the completion_start_time is set and valid ISO format
|
|
|
|
assert "completion_start_time" in message.meta
|
|
|
|
assert datetime.fromisoformat(message.meta["completion_start_time"]) < datetime.now()
|
|
|
|
|
2024-11-20 10:27:22 +01:00
|
|
|
@pytest.mark.skipif(
|
|
|
|
not os.environ.get("OPENAI_API_KEY", None),
|
|
|
|
reason="Export an env var called OPENAI_API_KEY containing the OpenAI API key to run this test.",
|
|
|
|
)
|
|
|
|
@pytest.mark.integration
|
2024-12-20 15:20:54 +01:00
|
|
|
def test_live_run_with_tools(self, tools):
|
|
|
|
chat_messages = [ChatMessage.from_user("What's the weather like in Paris?")]
|
|
|
|
component = OpenAIChatGenerator(tools=tools)
|
|
|
|
results = component.run(chat_messages)
|
2024-11-20 10:27:22 +01:00
|
|
|
assert len(results["replies"]) == 1
|
2024-12-20 15:20:54 +01:00
|
|
|
message = results["replies"][0]
|
|
|
|
|
|
|
|
assert not message.texts
|
|
|
|
assert not message.text
|
|
|
|
assert message.tool_calls
|
|
|
|
tool_call = message.tool_call
|
|
|
|
assert isinstance(tool_call, ToolCall)
|
|
|
|
assert tool_call.tool_name == "weather"
|
|
|
|
assert tool_call.arguments == {"city": "Paris"}
|
|
|
|
assert message.meta["finish_reason"] == "tool_calls"
|