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 86 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
8 changes: 6 additions & 2 deletions flytekit/clis/sdk_in_container/serve.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from concurrent import futures

import click
from flyteidl.service.agent_pb2_grpc import add_AsyncAgentServiceServicer_to_server
from flyteidl.service.agent_pb2_grpc import (
add_AsyncAgentServiceServicer_to_server,
add_SyncAgentServiceServicer_to_server,
)
from grpc import aio

_serve_help = """Start a grpc server for the agent service."""
Expand Down Expand Up @@ -42,7 +45,7 @@ def serve(_: click.Context, port, worker, timeout):

async def _start_grpc_server(port: int, worker: int, timeout: int):
click.secho("Starting up the server to expose the prometheus metrics...", fg="blue")
from flytekit.extend.backend.agent_service import AsyncAgentService
from flytekit.extend.backend.agent_service import AsyncAgentService, SyncAgentService

try:
from prometheus_client import start_http_server
Expand All @@ -54,6 +57,7 @@ async def _start_grpc_server(port: int, worker: int, timeout: int):
server = aio.server(futures.ThreadPoolExecutor(max_workers=worker))

add_AsyncAgentServiceServicer_to_server(AsyncAgentService(), server)
add_SyncAgentServiceServicer_to_server(SyncAgentService(), server)

server.add_insecure_port(f"[::]:{port}")
await server.start()
Expand Down
2 changes: 2 additions & 0 deletions flytekit/core/base_sql_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ def __init__(
inputs: Optional[Dict[str, Tuple[Type, Any]]] = None,
metadata: Optional[TaskMetadata] = None,
outputs: Optional[Dict[str, Type]] = None,
is_sync_plugin: Optional[bool] = None,
**kwargs,
):
"""
Expand All @@ -39,6 +40,7 @@ def __init__(
interface=Interface(inputs=inputs or {}, outputs=outputs or {}),
metadata=metadata,
task_config=task_config,
is_sync_plugin=is_sync_plugin,
**kwargs,
)
self._query_template = re.sub(r"\s+", " ", query_template.replace("\n", " ").replace("\t", " ")).strip()
Expand Down
14 changes: 12 additions & 2 deletions flytekit/core/base_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from typing import Any, Coroutine, Dict, Generic, List, Optional, OrderedDict, Tuple, Type, TypeVar, Union, cast

from flyteidl.core import tasks_pb2
from flyteidl.core.tasks_pb2 import PluginMetadata

from flytekit.configuration import SerializationSettings
from flytekit.core.context_manager import (
Expand Down Expand Up @@ -106,6 +107,7 @@ class TaskMetadata(object):
retries: int = 0
timeout: Optional[Union[datetime.timedelta, int]] = None
pod_template_name: Optional[str] = None
plugin_metadata: Optional[PluginMetadata] = None

def __post_init__(self):
if self.timeout:
Expand All @@ -131,7 +133,10 @@ 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__,
"python",
self.plugin_metadata,
),
timeout=self.timeout,
retries=self.retry_strategy,
Expand Down Expand Up @@ -171,12 +176,14 @@ def __init__(
task_type_version=0,
security_ctx: Optional[SecurityContext] = None,
docs: Optional[Documentation] = None,
is_sync_plugin: Optional[bool] = None,
**kwargs,
):
self._task_type = task_type
self._name = name
self._interface = interface
self._metadata = metadata if metadata else TaskMetadata()
plugin_metadata = PluginMetadata(is_sync_plugin=is_sync_plugin) if is_sync_plugin is not None else None
self._metadata = metadata if metadata else TaskMetadata(plugin_metadata=plugin_metadata)
self._task_type_version = task_type_version
self._security_ctx = security_ctx
self._docs = docs
Expand Down Expand Up @@ -420,6 +427,7 @@ def __init__(
environment: Optional[Dict[str, str]] = None,
disable_deck: Optional[bool] = None,
enable_deck: Optional[bool] = None,
is_sync_plugin: Optional[bool] = None,
**kwargs,
):
"""
Expand All @@ -435,11 +443,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
is_sync_plugin (bool): If true, plugin task will execute synchronously.
"""
super().__init__(
task_type=task_type,
name=name,
interface=transform_interface_to_typed_interface(interface),
is_sync_plugin=is_sync_plugin,
**kwargs,
)
self._python_interface = interface if interface else Interface()
Expand Down
73 changes: 73 additions & 0 deletions flytekit/core/external_api_task.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
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 SyncAgentExecutorMixin

T = TypeVar("T")
TASK_MODULE = "task_module"
TASK_NAME = "task_name"
TASK_CONFIG_PKL = "task_config_pkl"
TASK_TYPE = "api_task"


class ExternalApiTask(SyncAgentExecutorMixin, 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),
is_sync_plugin=True,
**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
2 changes: 2 additions & 0 deletions flytekit/core/python_auto_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ def __init__(
pod_template: Optional[PodTemplate] = None,
pod_template_name: Optional[str] = None,
accelerator: Optional[BaseAccelerator] = None,
is_sync_plugin: Optional[bool] = None,
**kwargs,
):
"""
Expand Down Expand Up @@ -92,6 +93,7 @@ def __init__(
name=name,
task_config=task_config,
security_ctx=sec_ctx,
is_sync_plugin=is_sync_plugin,
**kwargs,
)
self._container_image = container_image
Expand Down
2 changes: 2 additions & 0 deletions flytekit/core/python_function_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ def __init__(
ignore_input_vars: Optional[List[str]] = None,
execution_mode: ExecutionBehavior = ExecutionBehavior.DEFAULT,
task_resolver: Optional[TaskResolverMixin] = None,
is_sync_plugin: Optional[bool] = None,
**kwargs,
):
"""
Expand All @@ -124,6 +125,7 @@ def __init__(
interface=mutated_interface,
task_config=task_config,
task_resolver=task_resolver,
is_sync_plugin=is_sync_plugin,
**kwargs,
)

Expand Down
34 changes: 32 additions & 2 deletions flytekit/extend/backend/agent_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
CreateTaskResponse,
DeleteTaskRequest,
DeleteTaskResponse,
DoTaskRequest,
DoTaskResponse,
GetTaskRequest,
GetTaskResponse,
)
from flyteidl.service.agent_pb2_grpc import AsyncAgentServiceServicer
from flyteidl.service.agent_pb2_grpc import AsyncAgentServiceServicer, SyncAgentServiceServicer
from prometheus_client import Counter, Summary

from flytekit import logger
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,25 @@ 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)


class SyncAgentService(SyncAgentServiceServicer):
@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, output_prefix=request.output_prefix, task_template=tmp
)
return await asyncio.get_running_loop().run_in_executor(
None,
agent.do,
context,
request.output_prefix,
tmp,
inputs,
)
Loading
Loading