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

Chatgpt Agent #1822

Closed
Closed
Show file tree
Hide file tree
Changes from 69 commits
Commits
Show all changes
98 commits
Select commit Hold shift + click to select a range
540eb5d
Merge branch 'master' of https://github.com/Future-Outlier/flytekit
Aug 12, 2023
984d44a
Merge branch 'master' of https://github.com/Future-Outlier/flytekit
Aug 16, 2023
3d936fc
Merge branch 'master' of https://github.com/Future-Outlier/flytekit
Aug 30, 2023
931533a
Merge branch 'master' of https://github.com/Future-Outlier/flytekit
Sep 7, 2023
8365c53
drafte chatgpt agent
Sep 7, 2023
25d6a5d
others
Sep 7, 2023
970bf3b
sync plugin, DoTask function interface
Sep 7, 2023
b5a74d8
Merge branch 'flyteorg:master' into chatgpt-agent-sync-plugin
Future-Outlier Sep 11, 2023
6087c5f
requester agent base and chatgpt agent
Sep 11, 2023
f8680a1
Merge branch 'chatgpt-agent-sync-plugin' of https://github.com/Future…
Sep 11, 2023
b225310
Add do task interface
Sep 11, 2023
09bc23a
fix lint
Sep 11, 2023
bd5dbd7
Merge branch 'master' of https://github.com/Future-Outlier/flytekit
Sep 13, 2023
aeb5ea1
Merge branch 'master' of https://github.com/Future-Outlier/flytekit
Sep 13, 2023
0717e2c
Merge branch 'chatgpt-agent-sync-plugin' of https://github.com/Future…
Sep 17, 2023
54d2ddf
Merge branch 'flyteorg:master' into master
Future-Outlier Sep 17, 2023
541edc6
Merge branch 'flyteorg:master' into master
Future-Outlier Sep 19, 2023
7c9dcbc
upload data v1
Sep 20, 2023
18a9e5d
base_requester and chatgpt_requester succeed
Sep 23, 2023
75573ab
Merge branch 'flyteorg:master' into master
Future-Outlier Sep 23, 2023
61e0a76
Merge branch 'master' of https://github.com/Future-Outlier/flytekit i…
Sep 23, 2023
8de3fa8
chatgpt requester v2
Sep 26, 2023
be7d22d
output type
Sep 26, 2023
bca202b
dispatcher
Sep 27, 2023
c0139db
Merge pull request #19 from flyteorg/master
Future-Outlier Sep 28, 2023
cf9ff07
move to plugins directory
Sep 30, 2023
3b13b48
do task agent service
Oct 2, 2023
24df7b3
Merge branch 'flyteorg:master' into master
Future-Outlier Oct 3, 2023
563ca22
Merge branch 'flyteorg:master' into master
Future-Outlier Oct 4, 2023
5fa4f18
Merge branch 'flyteorg:master' into master
Future-Outlier Oct 6, 2023
5f1183b
Merge branch 'flyteorg:master' into master
Future-Outlier Oct 6, 2023
203d2d4
Merge branch 'flyteorg:master' into master
Future-Outlier Oct 7, 2023
9366dfb
Merge branch 'flyteorg:master' into master
Future-Outlier Oct 10, 2023
66f5e60
Merge branch 'master' of https://github.com/Future-Outlier/flytekit i…
Oct 10, 2023
3249963
merge master
Oct 10, 2023
558c6bd
Merge branch 'master' of https://github.com/Future-Outlier/flytekit
Oct 11, 2023
9f5dd0a
Merge branch 'master' of https://github.com/Future-Outlier/flytekit
Oct 12, 2023
c91ee4c
refactor
pingsutw Oct 15, 2023
4adf029
refactor
pingsutw Oct 15, 2023
402e1a9
Merge branch 'master' of https://github.com/Future-Outlier/flytekit i…
Oct 15, 2023
2db4de7
Merge branch 'master' into chatgpt-agent-sync-plugin
Oct 15, 2023
420cbf5
chatgpt sync plugin succeed v1
Oct 15, 2023
1208268
chatgpt syncplugin succeed
Oct 16, 2023
a64f6ee
remove unused task metadata
Oct 16, 2023
815dde4
add base_task RuntimeMetadata test and push for gitsha
Oct 16, 2023
9f3072e
fix ExternalApiTask import
Oct 16, 2023
713db18
add for flyteidl version remove for building image
Oct 16, 2023
0ecebdf
ciruclar import
Oct 16, 2023
a058734
add tests and lints
Oct 16, 2023
719ae32
final all tests
Oct 16, 2023
5823cb1
move to flytekit-openai-chatgpt dir and add setup.py python 3.11 test
Oct 17, 2023
c6058fc
delete flytekit-chatgpt
Oct 17, 2023
e6482ae
databricks api bug
Oct 17, 2023
c6343ec
remove output_prefix
Oct 17, 2023
ee0b829
make lint will make logger can't be import
Oct 17, 2023
a9b16c8
improve excutor task
Oct 18, 2023
d2ebf6c
Merge branch 'master' of https://github.com/Future-Outlier/flytekit i…
Oct 20, 2023
a660fc1
FLYTE_OPENAI_ACCESS_TOKEN
Oct 20, 2023
a3b0ecc
add requirements
Oct 28, 2023
bc9fb27
Merge branch 'master' of https://github.com/Future-Outlier/flytekit i…
Oct 31, 2023
6de876b
Merge branch 'master' of https://github.com/Future-Outlier/flytekit i…
Oct 31, 2023
f785a19
use openai async create function and change test
Nov 1, 2023
ff44060
Merge branch 'master' of https://github.com/Future-Outlier/flytekit i…
Nov 3, 2023
8892dee
change the runtime flavor by specifying str value
Nov 3, 2023
1810a7b
add depedencies
Nov 6, 2023
8d5bb61
add timeout seconds in ChatGPT
Nov 7, 2023
fd8dd5d
change await place in async do task function
Nov 8, 2023
36b315e
Merge branch 'master' of https://github.com/Future-Outlier/flytekit i…
Nov 8, 2023
e6b0ba0
fix circular import
Nov 7, 2023
dc87c81
Update flytekit/extend/backend/base_agent.py
Future-Outlier Nov 8, 2023
8ea1a9d
Update tests/flytekit/unit/core/test_task_metadata.py
Future-Outlier Nov 8, 2023
42b8d90
add runtime flavor variavle in all async plugin and sync plugin test
Nov 9, 2023
14a2698
add TaskExecutor comment
Nov 9, 2023
67582fd
change the argument task type used in sensor engine and api_task engi…
Nov 10, 2023
c273689
support more arguments in do task agent
Nov 10, 2023
232c80c
add annotations
Nov 15, 2023
f842fdd
move argument openai_organization to optional
Nov 15, 2023
835c48a
SyncAgentServiceServicer
Nov 17, 2023
d1e99be
make organization as a required arguement back
Nov 20, 2023
b0670d3
use is_sync_plugin varaible
Nov 21, 2023
6e8f30d
Merge branch 'master' of https://github.com/Future-Outlier/flytekit i…
Nov 21, 2023
104ba6f
ruff fmt
Nov 21, 2023
ec35714
add todo
Nov 22, 2023
c463992
use plugin_metadata by default
Nov 24, 2023
9758ce6
Merge branch 'master' of https://github.com/Future-Outlier/flytekit i…
Nov 24, 2023
868f81b
remove print debug
Nov 24, 2023
0068137
Merge branch 'master' of https://github.com/Future-Outlier/flytekit i…
Dec 13, 2023
6d15fdc
move to rich click
Dec 13, 2023
b56c845
Merge branch 'master' of https://github.com/Future-Outlier/flytekit i…
Dec 13, 2023
510711e
change to agentServicer, agentExecutorMixin, and use is_sync attribute
Dec 13, 2023
9d1e5bd
rename async agent service
Dec 19, 2023
b09a627
remove is_sync
Dec 19, 2023
5a0348b
remove is_sync
Dec 19, 2023
ea91dc7
fix pickle error
Dec 19, 2023
7786aca
remove new line
Dec 19, 2023
ca34c61
rename task config
Dec 19, 2023
1d9535d
use SyncAgentBase
Dec 20, 2023
68fd527
remove print
Dec 20, 2023
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
2 changes: 2 additions & 0 deletions flytekit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,8 @@
StructuredDatasetType,
)

from flytekit.extend.backend.task_executor import TaskExecutor # isort:skip. This is for circular import avoidance.

__version__ = "0.0.0+develop"


Expand Down
11 changes: 9 additions & 2 deletions flytekit/core/base_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ class TaskMetadata(object):
retries: int = 0
timeout: Optional[Union[datetime.timedelta, int]] = None
pod_template_name: Optional[str] = None
runtime_flavor: str = "python"
pingsutw marked this conversation as resolved.
Show resolved Hide resolved

def __post_init__(self):
if self.timeout:
Expand All @@ -130,7 +131,9 @@ def to_taskmetadata_model(self) -> _task_model.TaskMetadata:
return _task_model.TaskMetadata(
discoverable=self.cache,
runtime=_task_model.RuntimeMetadata(
_task_model.RuntimeMetadata.RuntimeType.FLYTE_SDK, __version__, "python"
_task_model.RuntimeMetadata.RuntimeType.FLYTE_SDK,
__version__,
self.runtime_flavor,
),
timeout=self.timeout,
retries=self.retry_strategy,
Expand Down Expand Up @@ -170,12 +173,13 @@ def __init__(
task_type_version=0,
security_ctx: Optional[SecurityContext] = None,
docs: Optional[Documentation] = None,
runtime_flavor: str = "python",
**kwargs,
):
self._task_type = task_type
self._name = name
self._interface = interface
self._metadata = metadata if metadata else TaskMetadata()
self._metadata = metadata if metadata else TaskMetadata(runtime_flavor=runtime_flavor)
self._task_type_version = task_type_version
self._security_ctx = security_ctx
self._docs = docs
Expand Down Expand Up @@ -419,6 +423,7 @@ def __init__(
environment: Optional[Dict[str, str]] = None,
disable_deck: Optional[bool] = None,
enable_deck: Optional[bool] = None,
runtime_flavor: str = "python",
**kwargs,
):
"""
Expand All @@ -434,11 +439,13 @@ def __init__(
execution of the task. Supplied as a dictionary of key/value pairs
disable_deck (bool): (deprecated) If true, this task will not output deck html file
enable_deck (bool): If true, this task will output deck html file
runtime_flavor (str): default is "python", we can set it to "sync_plugin" for flytepropeller to execute sync plugin task
"""
super().__init__(
task_type=task_type,
name=name,
interface=transform_interface_to_typed_interface(interface),
runtime_flavor=runtime_flavor,
**kwargs,
)
self._python_interface = interface if interface else Interface()
Expand Down
74 changes: 74 additions & 0 deletions flytekit/core/external_api_task.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import collections
import inspect
from abc import abstractmethod
from typing import Any, Dict, Optional, TypeVar

import jsonpickle
from flyteidl.admin.agent_pb2 import DoTaskResponse
from typing_extensions import get_type_hints

from flytekit.configuration import SerializationSettings
from flytekit.core.base_task import PythonTask
from flytekit.core.interface import Interface
from flytekit.extend.backend.base_agent import AsyncAgentExecutorMixin

T = TypeVar("T")
TASK_MODULE = "task_module"
TASK_NAME = "task_name"
TASK_CONFIG_PKL = "task_config_pkl"
TASK_TYPE = "api_task"
USE_SYNC_PLUGIN = "sync_plugin" # Indicates that the sync plugin in FlytePropeller should be used to run this task


class ExternalApiTask(AsyncAgentExecutorMixin, PythonTask):
"""
Base class for all external API tasks. External API tasks are tasks that are designed to run until they receive a
response from an external service. When the response is received, the task will complete. External API tasks are
designed to be run by the flyte agent.
"""

def __init__(
self,
name: str,
config: Optional[T] = None,
task_type: str = TASK_TYPE,
return_type: Optional[Any] = None,
**kwargs,
):
type_hints = get_type_hints(self.do, include_extras=True)
signature = inspect.signature(self.do)
inputs = collections.OrderedDict()
outputs = collections.OrderedDict({"o0": return_type}) if return_type else collections.OrderedDict()

for k, _ in signature.parameters.items(): # type: ignore
annotation = type_hints.get(k, None)
inputs[k] = annotation

super().__init__(
task_type=task_type,
name=name,
task_config=config,
interface=Interface(inputs=inputs, outputs=outputs),
runtime_flavor=USE_SYNC_PLUGIN,
**kwargs,
)

self._config = config

@abstractmethod
async def do(self, **kwargs) -> DoTaskResponse:
"""
Initiate an HTTP request to an external service such as OpenAI or Vertex AI and retrieve the response.
"""
raise NotImplementedError

def get_custom(self, settings: SerializationSettings = None) -> Dict[str, Any]:
Copy link
Contributor

Choose a reason for hiding this comment

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

why do we have to use pickle?
cc @pingsutw do you know? is this to maintain simply python coversion? This is potentially dangerous as it may break across python versions.

Copy link
Member Author

Choose a reason for hiding this comment

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

pickle is faster, we've talked about this before and Kevin told me that it might be ok.
Will there be multiple python versions usecases?

Copy link
Contributor

Choose a reason for hiding this comment

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

we cannot control backend and flytekit version

Copy link
Member Author

Choose a reason for hiding this comment

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

you are right, I fix it!
Thank you very much for your advice!

cfg = {
TASK_MODULE: type(self).__module__,
TASK_NAME: type(self).__name__,
}

if self._config is not None:
cfg[TASK_CONFIG_PKL] = jsonpickle.encode(self._config)

return cfg
20 changes: 19 additions & 1 deletion flytekit/extend/backend/agent_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
CreateTaskResponse,
DeleteTaskRequest,
DeleteTaskResponse,
DoTaskRequest,
DoTaskResponse,
GetTaskRequest,
GetTaskResponse,
)
Expand All @@ -23,6 +25,7 @@
create_operation = "create"
get_operation = "get"
delete_operation = "delete"
do_operation = "do"

# Follow the naming convention. https://prometheus.io/docs/practices/naming/
request_success_count = Counter(
Expand All @@ -44,7 +47,7 @@
def agent_exception_handler(func):
async def wrapper(
self,
request: typing.Union[CreateTaskRequest, GetTaskRequest, DeleteTaskRequest],
request: typing.Union[CreateTaskRequest, GetTaskRequest, DeleteTaskRequest, DoTaskRequest],
context: grpc.ServicerContext,
*args,
**kwargs,
Expand All @@ -60,6 +63,11 @@ async def wrapper(
elif isinstance(request, DeleteTaskRequest):
task_type = request.task_type
operation = delete_operation
elif isinstance(request, DoTaskRequest):
task_type = request.template.type
operation = do_operation
if request.inputs:
input_literal_size.labels(task_type=task_type).observe(request.inputs.ByteSize())
else:
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details("Method not implemented!")
Expand Down Expand Up @@ -122,3 +130,13 @@ async def DeleteTask(self, request: DeleteTaskRequest, context: grpc.ServicerCon
if agent.asynchronous:
return await agent.async_delete(context=context, resource_meta=request.resource_meta)
return await asyncio.get_running_loop().run_in_executor(None, agent.delete, context, request.resource_meta)

@agent_exception_handler
async def DoTask(self, request: DoTaskRequest, context: grpc.ServicerContext) -> DoTaskResponse:
tmp = TaskTemplate.from_flyte_idl(request.template)
inputs = LiteralMap.from_flyte_idl(request.inputs) if request.inputs else None
agent = AgentRegistry.get_agent(tmp.type)
logger.info(f"{tmp.type} agent start doing the job")
if agent.asynchronous:
return await agent.async_do(context=context, inputs=inputs, task_template=tmp)
return await asyncio.get_running_loop().run_in_executor(None, agent.do, context, "", inputs, tmp)
103 changes: 69 additions & 34 deletions flytekit/extend/backend/base_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from abc import ABC
from collections import OrderedDict
from functools import partial
from types import FrameType
from types import FrameType, coroutine

import grpc
from flyteidl.admin.agent_pb2 import (
Expand All @@ -16,6 +16,7 @@
SUCCEEDED,
CreateTaskResponse,
DeleteTaskResponse,
DoTaskResponse,
GetTaskResponse,
State,
)
Expand Down Expand Up @@ -81,6 +82,17 @@ def delete(self, context: grpc.ServicerContext, resource_meta: bytes) -> DeleteT
"""
raise NotImplementedError

def do(
self,
context: grpc.ServicerContext,
task_template: TaskTemplate,
inputs: typing.Optional[LiteralMap] = None,
) -> DoTaskResponse:
"""
Return the result of executing a task. It should return error code if the task execution failed.
"""
raise NotImplementedError

async def async_create(
self,
context: grpc.ServicerContext,
Expand All @@ -107,6 +119,17 @@ async def async_delete(self, context: grpc.ServicerContext, resource_meta: bytes
"""
raise NotImplementedError

async def async_do(
self,
context: grpc.ServicerContext,
task_template: TaskTemplate,
inputs: typing.Optional[LiteralMap] = None,
) -> DoTaskResponse:
"""
Return the result of executing a task. It should return error code if the task execution failed.
"""
raise NotImplementedError


class AgentRegistry(object):
"""
Expand Down Expand Up @@ -135,7 +158,8 @@ def convert_to_flyte_state(state: str) -> State:
Convert the state from the agent to the state in flyte.
"""
state = state.lower()
if state in ["failed", "timedout", "canceled"]:
# timedout is weird but correct, you can refer here: https://github.com/databricks/databricks-sdk-py/pull/407
Future-Outlier marked this conversation as resolved.
Show resolved Hide resolved
if state in ["failed", "timeout", "timedout", "canceled"]:
return RETRYABLE_FAILURE
elif state in ["done", "succeeded", "success"]:
return SUCCEEDED
Expand All @@ -155,25 +179,38 @@ def get_agent_secret(secret_key: str) -> str:
return flytekit.current_context().secrets.get(secret_key)


def _get_grpc_context() -> grpc.ServicerContext:
from unittest.mock import MagicMock

grpc_ctx = MagicMock(spec=grpc.ServicerContext)
return grpc_ctx


class AsyncAgentExecutorMixin:
"""
This mixin class is used to run the agent task locally, and it's only used for local execution.
Task should inherit from this class if the task can be run in the agent.
"""

_is_canceled = None
_agent = None
_entity = None
_clean_up_task: coroutine = None
_agent: AgentBase = None
_entity: PythonTask = None
_ctx: FlyteContext = FlyteContext.current_context()
_grpc_ctx: grpc.ServicerContext = _get_grpc_context()

def execute(self, **kwargs) -> typing.Any:
from flytekit.extend.backend.task_executor import TaskExecutor
from flytekit.tools.translator import get_serializable

self._entity = typing.cast(PythonTask, self)
task_template = get_serializable(OrderedDict(), SerializationSettings(ImageConfig()), self._entity).template
self._agent = AgentRegistry.get_agent(task_template.type)

res = asyncio.run(self._create(task_template, kwargs))
res = asyncio.run(self._get(resource_meta=res.resource_meta))
if isinstance(self._agent, TaskExecutor):
res = asyncio.run(self._do(task_template, kwargs))
else:
res = asyncio.run(self._create(task_template, kwargs))
res = asyncio.run(self._get(resource_meta=res.resource_meta))

if res.resource.state != SUCCEEDED:
raise FlyteUserException(f"Failed to run the task {self._entity.name}")
Expand All @@ -183,53 +220,51 @@ def execute(self, **kwargs) -> typing.Any:
async def _create(
self, task_template: TaskTemplate, inputs: typing.Dict[str, typing.Any] = None
) -> CreateTaskResponse:
ctx = FlyteContext.current_context()
grpc_ctx = _get_grpc_context()

# Convert python inputs to literals
literals = {}
for k, v in inputs.items():
literals[k] = TypeEngine.to_literal(ctx, v, type(v), self._entity.interface.inputs[k].type)
inputs = LiteralMap(literals) if literals else None
output_prefix = ctx.file_access.get_random_local_directory()
inputs = self.get_input_literal_map(inputs)
output_prefix = self._ctx.file_access.get_random_local_directory()

if self._agent.asynchronous:
res = await self._agent.async_create(grpc_ctx, output_prefix, task_template, inputs)
res = await self._agent.async_create(self._grpc_ctx, output_prefix, task_template, inputs)
else:
res = self._agent.create(grpc_ctx, output_prefix, task_template, inputs)
res = self._agent.create(self._grpc_ctx, output_prefix, task_template, inputs)

signal.signal(signal.SIGINT, partial(self.signal_handler, res.resource_meta)) # type: ignore
return res

async def _get(self, resource_meta: bytes) -> GetTaskResponse:
state = RUNNING
grpc_ctx = _get_grpc_context()

while not is_terminal_state(state):
time.sleep(1)
if self._agent.asynchronous:
res = await self._agent.async_get(grpc_ctx, resource_meta)
if self._is_canceled:
await self._is_canceled
res = await self._agent.async_get(self._grpc_ctx, resource_meta)
if self._clean_up_task:
await self._clean_up_task
sys.exit(1)
else:
res = self._agent.get(grpc_ctx, resource_meta)
res = self._agent.get(self._grpc_ctx, resource_meta)
state = res.resource.state
logger.info(f"Task state: {state}")
return res

async def _do(self, task_template: TaskTemplate, inputs: typing.Dict[str, typing.Any] = None):
inputs = self.get_input_literal_map(inputs)
if self._agent.asynchronous:
res = await self._agent.async_do(self._grpc_ctx, task_template, inputs)
else:
res = self._agent.do(self._grpc_ctx, task_template, inputs)
return res

def signal_handler(self, resource_meta: bytes, signum: int, frame: FrameType) -> typing.Any:
grpc_ctx = _get_grpc_context()
if self._agent.asynchronous:
if self._is_canceled is None:
self._is_canceled = asyncio.create_task(self._agent.async_delete(grpc_ctx, resource_meta))
if self._clean_up_task is None:
self._clean_up_task = asyncio.create_task(self._agent.async_delete(self._grpc_ctx, resource_meta))
else:
self._agent.delete(grpc_ctx, resource_meta)
self._agent.delete(self._grpc_ctx, resource_meta)
sys.exit(1)


def _get_grpc_context():
from unittest.mock import MagicMock

grpc_ctx = MagicMock(spec=grpc.ServicerContext)
return grpc_ctx
def get_input_literal_map(self, inputs: typing.Dict[str, typing.Any] = None) -> typing.Optional[LiteralMap]:
# Convert python inputs to literals
literals = {}
for k, v in inputs.items():
literals[k] = TypeEngine.to_literal(self._ctx, v, type(v), self._entity.interface.inputs[k].type)
return LiteralMap(literals) if literals else None
pingsutw marked this conversation as resolved.
Show resolved Hide resolved
Loading
Loading