tests for gpt4visionapi

pull/190/head
Kye 1 year ago
parent 9c3a292938
commit 0802091b7f

@ -10,7 +10,7 @@ img = "images/swarms.jpeg"
## Initialize the workflow ## Initialize the workflow
flow = Flow( flow = Flow(
llm=llm, llm=llm,
max_loops='auto', max_loops="auto",
dashboard=True, dashboard=True,
) )

@ -53,8 +53,8 @@ topic_selection_task = (
"Generate 10 topics on gaining mental clarity using ancient practices" "Generate 10 topics on gaining mental clarity using ancient practices"
) )
topics = llm( topics = llm(
f"Your System Instructions: {TOPIC_GENERATOR_SYSTEM_PROMPT}, Your current task:" f"Your System Instructions: {TOPIC_GENERATOR_SYSTEM_PROMPT}, Your current"
f" {topic_selection_task}" f" task: {topic_selection_task}"
) )
dashboard = print( dashboard = print(

@ -52,5 +52,4 @@ __all__ = [
# "Dalle3", # "Dalle3",
# "DistilWhisperModel", # "DistilWhisperModel",
"GPT4VisionAPI", "GPT4VisionAPI",
] ]

@ -185,11 +185,9 @@ def build_extra_kwargs(
if field_name in extra_kwargs: if field_name in extra_kwargs:
raise ValueError(f"Found {field_name} supplied twice.") raise ValueError(f"Found {field_name} supplied twice.")
if field_name not in all_required_field_names: if field_name not in all_required_field_names:
warnings.warn( warnings.warn(f"""WARNING! {field_name} is not default parameter.
f"""WARNING! {field_name} is not default parameter.
{field_name} was transferred to model_kwargs. {field_name} was transferred to model_kwargs.
Please confirm that {field_name} is what you intended.""" Please confirm that {field_name} is what you intended.""")
)
extra_kwargs[field_name] = values.pop(field_name) extra_kwargs[field_name] = values.pop(field_name)
invalid_model_kwargs = all_required_field_names.intersection( invalid_model_kwargs = all_required_field_names.intersection(

@ -168,8 +168,10 @@ class Dalle3:
# Handling exceptions and printing the errors details # Handling exceptions and printing the errors details
print( print(
colored( colored(
(
f"Error running Dalle3: {error} try optimizing your api" f"Error running Dalle3: {error} try optimizing your api"
" key and or try again", " key and or try again"
),
"red", "red",
) )
) )
@ -231,8 +233,10 @@ class Dalle3:
except (Exception, openai.OpenAIError) as error: except (Exception, openai.OpenAIError) as error:
print( print(
colored( colored(
(
f"Error running Dalle3: {error} try optimizing your api" f"Error running Dalle3: {error} try optimizing your api"
" key and or try again", " key and or try again"
),
"red", "red",
) )
) )
@ -306,8 +310,10 @@ class Dalle3:
except Exception as error: except Exception as error:
print( print(
colored( colored(
(
f"Error running Dalle3: {error} try optimizing" f"Error running Dalle3: {error} try optimizing"
" your api key and or try again", " your api key and or try again"
),
"red", "red",
) )
) )

@ -7,6 +7,7 @@ from dotenv import load_dotenv
load_dotenv() load_dotenv()
openai_api_key = os.getenv("OPENAI_API_KEY") openai_api_key = os.getenv("OPENAI_API_KEY")
class GPT4VisionAPI: class GPT4VisionAPI:
""" """
GPT-4 Vision API GPT-4 Vision API
@ -37,10 +38,8 @@ class GPT4VisionAPI:
""" """
def __init__(
self, def __init__(self, openai_api_key: str = openai_api_key):
openai_api_key: str = openai_api_key
):
super().__init__() super().__init__()
self.openai_api_key = openai_api_key self.openai_api_key = openai_api_key
@ -68,7 +67,9 @@ class GPT4VisionAPI:
{ {
"type": "image_url", "type": "image_url",
"image_url": { "image_url": {
"url": f"data:image/jpeg;base64,{base64_image}" "url": (
f"data:image/jpeg;base64,{base64_image}"
)
}, },
}, },
], ],
@ -108,7 +109,9 @@ class GPT4VisionAPI:
{ {
"type": "image_url", "type": "image_url",
"image_url": { "image_url": {
"url": f"data:image/jpeg;base64,{base64_image}" "url": (
f"data:image/jpeg;base64,{base64_image}"
)
}, },
}, },
], ],

@ -291,8 +291,10 @@ class HuggingfaceLLM:
except Exception as e: except Exception as e:
print( print(
colored( colored(
(
"HuggingfaceLLM could not generate text because of" "HuggingfaceLLM could not generate text because of"
f" error: {e}, try optimizing your arguments", f" error: {e}, try optimizing your arguments"
),
"red", "red",
) )
) )

@ -140,8 +140,10 @@ class SSD1B:
# Handling exceptions and printing the errors details # Handling exceptions and printing the errors details
print( print(
colored( colored(
(
f"Error running SSD1B: {error} try optimizing your api" f"Error running SSD1B: {error} try optimizing your api"
" key and or try again", " key and or try again"
),
"red", "red",
) )
) )
@ -226,8 +228,10 @@ class SSD1B:
except Exception as error: except Exception as error:
print( print(
colored( colored(
(
f"Error running SSD1B: {error} try optimizing" f"Error running SSD1B: {error} try optimizing"
" your api key and or try again", " your api key and or try again"
),
"red", "red",
) )
) )

@ -274,5 +274,3 @@ Check Accuracy:
- Flag any bold claims that lack credible evidence for fact-checker review. - Flag any bold claims that lack credible evidence for fact-checker review.
""" """

@ -489,8 +489,10 @@ class Flow:
except Exception as error: except Exception as error:
print( print(
colored( colored(
(
"Error activating autonomous agent. Try optimizing your" "Error activating autonomous agent. Try optimizing your"
" parameters...", " parameters..."
),
"red", "red",
) )
) )
@ -657,7 +659,7 @@ class Flow:
while attempt < self.retry_attempts: while attempt < self.retry_attempts:
try: try:
response = self.llm( response = self.llm(
task ** kwargs, task**kwargs,
) )
if self.interactive: if self.interactive:
print(f"AI: {response}") print(f"AI: {response}")

@ -385,9 +385,11 @@ class SequentialWorkflow:
except Exception as e: except Exception as e:
print( print(
colored( colored(
(
f"Error initializing the Sequential workflow: {e} try" f"Error initializing the Sequential workflow: {e} try"
" optimizing your inputs like the flow class and task" " optimizing your inputs like the flow class and task"
" description", " description"
),
"red", "red",
attrs=["bold", "underline"], attrs=["bold", "underline"],
) )

@ -0,0 +1,122 @@
import pytest
from unittest.mock import mock_open, patch, Mock
from requests.exceptions import RequestException
from swarms.models.gpt4_vision_api import GPT4VisionAPI
import os
from dotenv import load_dotenv
load_dotenv()
custom_api_key = os.environ.get("OPENAI_API_KEY")
img = "images/swarms.jpeg"
@pytest.fixture
def vision_api():
return GPT4VisionAPI(openai_api_key="test_api_key")
def test_init(vision_api):
assert vision_api.openai_api_key == "test_api_key"
def test_encode_image(vision_api):
with patch(
"builtins.open", mock_open(read_data=b"test_image_data"), create=True
):
encoded_image = vision_api.encode_image("test_image.jpg")
assert encoded_image == "dGVzdF9pbWFnZV9kYXRh"
def test_run_success(vision_api):
expected_response = {"choices": [{"text": "This is the model's response."}]}
with patch(
"requests.post", return_value=Mock(json=lambda: expected_response)
) as mock_post:
result = vision_api.run("What is this?", "test_image.jpg")
mock_post.assert_called_once()
assert result == "This is the model's response."
def test_run_request_error(vision_api):
with patch(
"requests.post", side_effect=RequestException("Request Error")
) as mock_post:
with pytest.raises(RequestException):
vision_api.run("What is this?", "test_image.jpg")
def test_run_response_error(vision_api):
expected_response = {"error": "Model Error"}
with patch(
"requests.post", return_value=Mock(json=lambda: expected_response)
) as mock_post:
with pytest.raises(RuntimeError):
vision_api.run("What is this?", "test_image.jpg")
def test_call(vision_api):
expected_response = {"choices": [{"text": "This is the model's response."}]}
with patch(
"requests.post", return_value=Mock(json=lambda: expected_response)
) as mock_post:
result = vision_api("What is this?", "test_image.jpg")
mock_post.assert_called_once()
assert result == "This is the model's response."
@pytest.fixture
def gpt_api():
return GPT4VisionAPI()
def test_initialization_with_default_key():
api = GPT4VisionAPI()
assert api.openai_api_key == custom_api_key
def test_initialization_with_custom_key():
custom_key = custom_api_key
api = GPT4VisionAPI(openai_api_key=custom_key)
assert api.openai_api_key == custom_key
def test_run_successful_response(gpt_api):
task = "What is in the image?"
img_url = img
response_json = {"choices": [{"text": "Answer from GPT-4 Vision"}]}
mock_response = Mock()
mock_response.json.return_value = response_json
with patch("requests.post", return_value=mock_response) as mock_post:
result = gpt_api.run(task, img_url)
mock_post.assert_called_once()
assert result == response_json["choices"][0]["text"]
def test_run_with_exception(gpt_api):
task = "What is in the image?"
img_url = img
with patch("requests.post", side_effect=Exception("Test Exception")):
with pytest.raises(Exception):
gpt_api.run(task, img_url)
def test_call_method_successful_response(gpt_api):
task = "What is in the image?"
img_url = img
response_json = {"choices": [{"text": "Answer from GPT-4 Vision"}]}
mock_response = Mock()
mock_response.json.return_value = response_json
with patch("requests.post", return_value=mock_response) as mock_post:
result = gpt_api(task, img_url)
mock_post.assert_called_once()
assert result == response_json
def test_call_method_with_exception(gpt_api):
task = "What is in the image?"
img_url = img
with patch("requests.post", side_effect=Exception("Test Exception")):
with pytest.raises(Exception):
gpt_api(task, img_url)
Loading…
Cancel
Save