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

Updated ParameterizedModelParser run method for handing run_with_dependencies parameter #923

Merged
merged 28 commits into from
Mar 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
739f9b4
chore: Updated ParameterizedModelParser run method for handing run_wi…
sp6370 Jan 14, 2024
f5ef8ce
test: Add test for running a prompt with dependencies
sp6370 Jan 14, 2024
57a02a7
modified run with dep tests
sp6370 Jan 25, 2024
5f4c489
Added new aiconfig for tests
sp6370 Jan 27, 2024
2eade61
Added new test for run with dependencies
sp6370 Jan 27, 2024
a4d2024
Update openai.py
sp6370 Jan 27, 2024
d365e07
Update openai.py
sp6370 Jan 27, 2024
75de4f6
Update tarvel_gpt_prompts_with_dependency.json
sp6370 Jan 27, 2024
3af8ac0
Update test_run_config.py
sp6370 Jan 27, 2024
39e5986
Merge branch 'main' into main
sp6370 Jan 31, 2024
9617bd9
Update test_run_config.py
sp6370 Jan 31, 2024
9df553d
Merge branch 'lastmile-ai:main' into main
sp6370 Feb 6, 2024
9546fbd
Merge branch 'lastmile-ai:main' into main
sp6370 Feb 7, 2024
150257e
Merge branch 'lastmile-ai:main' into main
sp6370 Feb 11, 2024
e1267db
Remove unnecessary kwargs hack in ModelParser constructor
sp6370 Feb 11, 2024
a93af45
Merge branch 'lastmile-ai:main' into main
sp6370 Feb 25, 2024
a8d29b8
Test Commit
sp6370 Feb 25, 2024
fa167d5
Remove unnecessary word in FAQ
sp6370 Feb 25, 2024
5ae5c47
Merge branch 'lastmile-ai:main' into main
sp6370 Mar 20, 2024
68a875e
chore: fixed formatting issues
sp6370 Mar 20, 2024
2221959
chore: updates the `ModelParser` to not use **kwargs
sp6370 Mar 20, 2024
cc6ee3e
chore: updates the AiConfig runtime to explicitly use run_with_depend…
sp6370 Mar 20, 2024
88d1f50
chore: eliminates the usage of **kwargs in favor of run_with_dependen…
sp6370 Mar 20, 2024
1a4a8c9
chore: fix linting
sp6370 Mar 20, 2024
4b5c936
chore: fix formatting
sp6370 Mar 20, 2024
b495e2d
chore: make all callsites consistent
sp6370 Mar 20, 2024
1ecc940
test: enables the test for prompt with dependencies
sp6370 Mar 20, 2024
d61fa62
chore: fix the typo
sp6370 Mar 20, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ async def run(
aiconfig: "AIConfigRuntime",
options: InferenceOptions,
parameters: Dict[str, Any],
**kwargs,
run_with_dependencies: Optional[bool] = False,
) -> list[Output]:
await aiconfig.callback_manager.run_callbacks(
CallbackEvent(
Expand All @@ -128,6 +128,7 @@ async def run(
"prompt": prompt,
"options": options,
"parameters": parameters,
"run_with_dependencies": run_with_dependencies,
},
)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ async def run(
aiconfig: "AIConfigRuntime",
options: InferenceOptions,
parameters: Dict[str, Any],
**kwargs,
run_with_dependencies: Optional[bool] = False,
) -> list[Output]:
await aiconfig.callback_manager.run_callbacks(
CallbackEvent(
Expand All @@ -152,6 +152,7 @@ async def run(
"prompt": prompt,
"options": options,
"parameters": parameters,
"run_with_dependencies": run_with_dependencies,
},
)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ async def run(
aiconfig: "AIConfigRuntime",
options: InferenceOptions,
parameters: Dict[str, Any],
**kwargs,
run_with_dependencies: Optional[bool] = False,
) -> list[Output]:
"""
Invoked to run a prompt in the .aiconfig. This method should perform
Expand All @@ -263,6 +263,7 @@ async def run(
"prompt": prompt,
"options": options,
"parameters": parameters,
"run_with_dependencies": run_with_dependencies,
},
)
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ async def run(
aiconfig: "AIConfigRuntime",
options: InferenceOptions,
parameters: Dict[str, Any],
**kwargs,
run_with_dependencies: Optional[bool] = False,
) -> list[Output]:
"""
Invoked to run a prompt in the .aiconfig. This method should perform
Expand All @@ -270,6 +270,7 @@ async def run(
"prompt": prompt,
"options": sanitized_options,
"parameters": parameters,
"run_with_dependencies": run_with_dependencies,
},
)
)
Expand Down
10 changes: 3 additions & 7 deletions python/src/aiconfig/Config.py
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,7 @@ async def run(
prompt_name: str,
params: Optional[dict] = None,
options: Optional[InferenceOptions] = None,
**kwargs,
run_with_dependencies: Optional[bool] = False,
):
"""
Executes the AI model with the resolved parameters and returns the API response.
Expand All @@ -309,7 +309,7 @@ async def run(
"prompt_name": prompt_name,
"params": params,
"options": options,
"kwargs": kwargs,
"run_with_dependencies": run_with_dependencies,
sp6370 marked this conversation as resolved.
Show resolved Hide resolved
},
)
await self.callback_manager.run_callbacks(event)
Expand All @@ -330,11 +330,7 @@ async def run(
self.delete_output(prompt_name)

response = await model_provider.run(
prompt_data,
self,
options,
params,
**kwargs, # TODO: We should remove and make argument explicit
prompt_data, self, options, params, run_with_dependencies
)

event = CallbackEvent(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,9 @@ async def run(
aiconfig: AIConfig,
options: Optional[InferenceOptions] = None,
parameters: Dict = {},
**kwargs, # TODO: We should remove and make arguments explicit
run_with_dependencies: Optional[bool] = False,
sp6370 marked this conversation as resolved.
Show resolved Hide resolved
) -> List[Output]:
# maybe use prompt metadata instead of kwargs?
if kwargs.get("run_with_dependencies", False):
if run_with_dependencies:
return await self.run_with_dependencies(
prompt, aiconfig, options, parameters
)
Expand Down
2 changes: 1 addition & 1 deletion python/src/aiconfig/model_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ async def run(
aiconfig: AIConfig,
options: Optional["InferenceOptions"] = None,
parameters: Dict = {},
**kwargs, # TODO: Remove this, just a hack for now to ensure that it doesn't break
sp6370 marked this conversation as resolved.
Show resolved Hide resolved
run_with_dependencies: Optional[bool] = False,
) -> ExecuteResult:
"""
Execute model inference based on completion data to be constructed in deserialize(), which includes the input prompt and
Expand Down
35 changes: 35 additions & 0 deletions python/tests/aiconfigs/travel_gpt_prompts_with_dependency.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "NYC Trip Planner",
"schema_version": "latest",
"description": "Intrepid explorer with ChatGPT and AIConfig",

"metadata": {
"parameters": {},
"models": {
"gpt-3.5-turbo": {
"model": "gpt-3.5-turbo",
"top_p": 1,
"temperature": 1,
"stream": false
}
}
},

"prompts": [
{
"name": "get_activities",
"input": "Tell me 10 fun attractions to do in {{city}}.",
"metadata": {
"model": "gpt-3.5-turbo"
}
},
{
"name": "gen_itinerary",
"input": "Generate an itinerary ordered by {{order_by}} for these activities: {{get_activities.output}}.",
"metadata": {
"model": "gpt-3.5-turbo"
}
}
],
"$schema": "https://json.schemastore.org/aiconfig-1.0"
}
93 changes: 93 additions & 0 deletions python/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,99 @@ def mock_openai_chat_completion(**kwargs):
raise Exception("Unexpected arguments:\n {}".format(kwargs))


def mock_openai_chat_completion_with_dependencies(**kwargs):
sp6370 marked this conversation as resolved.
Show resolved Hide resolved
response_map_list = [
[
{
"model": "gpt-3.5-turbo",
"top_p": 1,
"temperature": 1,
"stream": False,
"messages": [
{
"content": "Tell me 10 fun attractions to do in NYC.",
"role": "user",
}
],
},
ChatCompletion(
**{
"id": "chatcmpl-8khHUHbetNyprE1ftmRu5WyVNP3O3",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": '1. Visit Times Square: Experience the iconic "Crossroads of the World" with its dazzling billboards, Broadway shows, and lively atmosphere.\n2. Explore Central Park: Take a leisurely stroll or rent a bike to discover this sprawling oasis in the heart of Manhattan, complete with picturesque landscapes, walking trails, and various attractions.\n3. Take a ferry to the Statue of Liberty: Visit the renowned Statue of Liberty on Liberty Island and enjoy stunning views of the city skyline from the ferry ride itself.\n4. Visit the Metropolitan Museum of Art: Immerse yourself in world-class art collections spanning thousands of years and diverse cultures, all housed in the magnificent Met museum.\n5. Explore the High Line: Walk along the elevated park built on a historic freight rail line, offering beautiful green spaces, public art installations, and fantastic views of the city.\n6. Enjoy a Broadway show: Watch a live performance of a Broadway musical or play in one of the iconic theaters in the Theater District, offering a memorable experience for theater enthusiasts.\n7. Visit the 9/11 Memorial and Museum: Pay your respects at the site of the former World Trade Center twin towers and learn about the events of September 11, 2001, at the informative museum.\n8. Take a food tour in Greenwich Village: Indulge in a delicious gastronomic adventure, exploring the vibrant food scene in Greenwich Village, renowned for its diverse restaurants and eateries.\n9. Visit the Brooklyn Bridge: Take a walk across this iconic suspension bridge, providing breathtaking views of the Manhattan skyline and the East River.\n10. Explore the Museum of Modern Art (MoMA): Discover a vast collection of modern and contemporary art, including works by artists like Van Gogh, Picasso, Warhol, and many more at this renowned art institution.',
"role": "assistant",
},
}
],
"created": 1706140152,
"model": "gpt-3.5-turbo-0613",
"object": "chat.completion",
"usage": {
"completion_tokens": 363,
"prompt_tokens": 18,
"total_tokens": 381,
},
}
),
],
# Example 2
[
{
"model": "gpt-3.5-turbo",
"temperature": 1,
"top_p": 1,
"stream": False,
"messages": [
{
"content": "Tell me 10 fun attractions to do in NYC.",
"role": "user",
},
{
"content": '1. Visit Times Square: Experience the iconic "Crossroads of the World" with its dazzling billboards, Broadway shows, and lively atmosphere.\n2. Explore Central Park: Take a leisurely stroll or rent a bike to discover this sprawling oasis in the heart of Manhattan, complete with picturesque landscapes, walking trails, and various attractions.\n3. Take a ferry to the Statue of Liberty: Visit the renowned Statue of Liberty on Liberty Island and enjoy stunning views of the city skyline from the ferry ride itself.\n4. Visit the Metropolitan Museum of Art: Immerse yourself in world-class art collections spanning thousands of years and diverse cultures, all housed in the magnificent Met museum.\n5. Explore the High Line: Walk along the elevated park built on a historic freight rail line, offering beautiful green spaces, public art installations, and fantastic views of the city.\n6. Enjoy a Broadway show: Watch a live performance of a Broadway musical or play in one of the iconic theaters in the Theater District, offering a memorable experience for theater enthusiasts.\n7. Visit the 9/11 Memorial and Museum: Pay your respects at the site of the former World Trade Center twin towers and learn about the events of September 11, 2001, at the informative museum.\n8. Take a food tour in Greenwich Village: Indulge in a delicious gastronomic adventure, exploring the vibrant food scene in Greenwich Village, renowned for its diverse restaurants and eateries.\n9. Visit the Brooklyn Bridge: Take a walk across this iconic suspension bridge, providing breathtaking views of the Manhattan skyline and the East River.\n10. Explore the Museum of Modern Art (MoMA): Discover a vast collection of modern and contemporary art, including works by artists like Van Gogh, Picasso, Warhol, and many more at this renowned art institution.',
"role": "assistant",
},
{
"content": "Generate an itinerary ordered by geographic location for these activities: 1. Visit Times Square: Experience the iconic "Crossroads of the World" with its dazzling billboards, Broadway shows, and lively atmosphere.\n2. Explore Central Park: Take a leisurely stroll or rent a bike to discover this sprawling oasis in the heart of Manhattan, complete with picturesque landscapes, walking trails, and various attractions.\n3. Take a ferry to the Statue of Liberty: Visit the renowned Statue of Liberty on Liberty Island and enjoy stunning views of the city skyline from the ferry ride itself.\n4. Visit the Metropolitan Museum of Art: Immerse yourself in world-class art collections spanning thousands of years and diverse cultures, all housed in the magnificent Met museum.\n5. Explore the High Line: Walk along the elevated park built on a historic freight rail line, offering beautiful green spaces, public art installations, and fantastic views of the city.\n6. Enjoy a Broadway show: Watch a live performance of a Broadway musical or play in one of the iconic theaters in the Theater District, offering a memorable experience for theater enthusiasts.\n7. Visit the 9/11 Memorial and Museum: Pay your respects at the site of the former World Trade Center twin towers and learn about the events of September 11, 2001, at the informative museum.\n8. Take a food tour in Greenwich Village: Indulge in a delicious gastronomic adventure, exploring the vibrant food scene in Greenwich Village, renowned for its diverse restaurants and eateries.\n9. Visit the Brooklyn Bridge: Take a walk across this iconic suspension bridge, providing breathtaking views of the Manhattan skyline and the East River.\n10. Explore the Museum of Modern Art (MoMA): Discover a vast collection of modern and contemporary art, including works by artists like Van Gogh, Picasso, Warhol, and many more at this renowned art institution..",
"role": "user",
},
],
},
ChatCompletion(
**{
"id": "chatcmpl-8khHahyYOoH456N6fjXgs2PQjfqDD",
"choices": [
{
"finish_reason": "stop",
"index": 0,
"message": {
"content": "Here's an itinerary ordered by geographic location:\n\n1. Start your day at Times Square.\n2. From there, head south to the 9/11 Memorial and Museum.\n3. After paying your respects, take a walk to the nearby Staten Island Ferry Terminal to catch a ferry to the Statue of Liberty on Liberty Island.\n4. Return from the ferry and head north to the High Line, located in the Chelsea neighborhood.\n5. Continue north to the Museum of Modern Art (MoMA) in Midtown Manhattan.\n6. From MoMA, head east to visit Central Park.\n7. Explore Central Park at your leisure, taking a stroll or renting a bike to fully enjoy the park's attractions.\n8. Afterward, head downtown to the Metropolitan Museum of Art (Met) on the Upper East Side to immerse yourself in its world-class art collections.\n9. From the Met, travel southwest to Greenwich Village for a delightful food tour, exploring the diverse culinary offerings.\n10. Wrap up your day by walking across the Brooklyn Bridge to enjoy stunning views of the Manhattan skyline and the East River.\n\nNote: This itinerary can be adjusted based on personal preferences and time availability.",
"role": "assistant",
},
}
],
"created": 1706140158,
"model": "gpt-3.5-turbo-0613",
"object": "chat.completion",
"usage": {
"completion_tokens": 236,
"prompt_tokens": 767,
"total_tokens": 1003,
},
}
),
],
]

for input_params, response in response_map_list:
if kwargs == input_params:
return response
raise Exception("Unexpected arguments:\n {}".format(kwargs))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Probably shoudl remove now to show that it works now that kwargs is removed



@pytest.fixture
def set_temporary_env_vars():
"""
Expand Down
41 changes: 40 additions & 1 deletion python/tests/test_run_config.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
from unittest.mock import Mock

import openai
import pytest
from aiconfig.Config import AIConfigRuntime
from mock import patch

from .conftest import mock_openai_chat_completion
from .conftest import (
mock_openai_chat_completion,
mock_openai_chat_completion_with_dependencies,
)
from .util.file_path_utils import get_absolute_file_path_from_relative


Expand Down Expand Up @@ -48,3 +53,37 @@ async def test_load_parametrized_data_config(set_temporary_env_vars):
},
],
}


@pytest.mark.asyncio
async def test_running_prompt_with_dependencies(set_temporary_env_vars):
"""Test running a prompt with dependencies with the run_with_dependencies flag set to True"""

mock_openai = Mock(
side_effect=mock_openai_chat_completion_with_dependencies
)

with patch.object(
openai.resources.chat.Completions,
"create",
new=mock_openai,
):
config_relative_path = (
"aiconfigs/travel_gpt_prompts_with_dependency.json"
)
config_absolute_path = get_absolute_file_path_from_relative(
__file__, config_relative_path
)
config = AIConfigRuntime.load(config_absolute_path)

combined_prompt_parameters = {
"city": "NYC",
"order_by": "geographic location",
}
await config.run(
"gen_itinerary",
combined_prompt_parameters,
run_with_dependencies=True,
)

assert mock_openai.call_count == 2
sp6370 marked this conversation as resolved.
Show resolved Hide resolved
Loading