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 24 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions flytekit/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@
from flytekit.models.literals import Blob, BlobMetadata, Literal, Scalar
from flytekit.models.types import LiteralType
from flytekit.sensor.sensor_engine import SensorEngine
from flytekit.dispatcher.dispatcher_engine import DispatcherEngine
from flytekit.types import directory, file, iterator
from flytekit.types.structured.structured_dataset import (
StructuredDataset,
Expand Down
3 changes: 3 additions & 0 deletions flytekit/dispatcher/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .base_dispatcher import BaseDispatcher
from .chatgpt_dispatcher import ChatGPTDispatcher
from .dispatcher_engine import DispatcherEngine
64 changes: 64 additions & 0 deletions flytekit/dispatcher/base_dispatcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
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")
DISPATCHER_MODULE = "dispatcher_module"
DISPATCHER_NAME = "dispatcher_name"
DISPATCHER_CONFIG_PKL = "dispatcher_config_pkl"
INPUTS = "inputs"


class BaseDispatcher(AsyncAgentExecutorMixin, PythonTask):
"""
TODO: Write the docstring
"""

def __init__(
self,
name: str,
dispatcher_config: Optional[T] = None,
task_type: str = "dispatcher",
return_type: Optional[T] = 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})

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=None,
interface=Interface(inputs=inputs, outputs=outputs),
**kwargs,
)
self._dispatcher_config = dispatcher_config

@abstractmethod
async def async_do(self, **kwargs) -> DoTaskResponse:
raise NotImplementedError

def get_custom(self, settings: SerializationSettings = None) -> Dict[str, Any]:
cfg = {
DISPATCHER_MODULE: type(self).__module__,
DISPATCHER_NAME: type(self).__name__,
}
if self._dispatcher_config is not None:
cfg[DISPATCHER_CONFIG_PKL] = jsonpickle.encode(self._dispatcher_config)
return cfg
70 changes: 70 additions & 0 deletions flytekit/dispatcher/chatgpt_dispatcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import json
from typing import Any, Dict

import aiohttp
from flyteidl.admin.agent_pb2 import SUCCEEDED, DoTaskResponse, Resource

from flytekit import FlyteContextManager
from flytekit.core import utils
from flytekit.core.type_engine import TypeEngine
from flytekit.extend.backend.base_agent import get_secret
from flytekit.models.literals import LiteralMap
from flytekit.dispatcher.base_dispatcher import BaseDispatcher


class ChatGPTDispatcher(BaseDispatcher):
"""
TODO: Write the docstring
"""

_openai_organization: str = None
_chatgpt_conf: Dict[str, Any] = None

# TODO, Add Value Error
def __init__(self, name: str, config: Dict[str, Any], **kwargs):
super().__init__(name=name, dispatcher_config=config, return_type=str, **kwargs)
self._openai_organization = config["openai_organization"]
self._chatgpt_conf = config["chatgpt_conf"]

async def do(
self,
message: str = None,
) -> DoTaskResponse:
self._chatgpt_conf["messages"] = [{"role": "user", "content": message}]
openai_url = "https://api.openai.com/v1/chat/completions"
data = json.dumps(self._chatgpt_conf)

message = "TEST SYNC PLUGIN"

# async with aiohttp.ClientSession() as session:
# async with session.post(
# openai_url, headers=get_header(openai_organization=self._openai_organization), data=data
# ) as resp:
# if resp.status != 200:
# raise Exception(f"Failed to execute chatgpt job with error: {resp.reason}")
# response = await resp.json()

# message = response["choices"][0]["message"]["content"]

ctx = FlyteContextManager.current_context()
outputs = LiteralMap(
{
"o0": TypeEngine.to_literal(
ctx,
message,
type(message),
TypeEngine.to_literal_type(type(message)),
)
}
).to_flyte_idl()

return DoTaskResponse(resource=Resource(state=SUCCEEDED, outputs=outputs))


def get_header(openai_organization: str):
token = get_secret(secret_key="OPENAI_ACCESS_TOKEN")
return {
"OpenAI-Organization": openai_organization,
"Authorization": f"Bearer {token}",
"content-type": "application/json",
}
46 changes: 46 additions & 0 deletions flytekit/dispatcher/dispatcher_engine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import importlib
import typing
from typing import Optional

import grpc
import jsonpickle
from flyteidl.admin.agent_pb2 import DoTaskResponse

from flytekit import FlyteContextManager
from flytekit.core.type_engine import TypeEngine
from flytekit.extend.backend.base_agent import AgentRegistry, DispatcherAgent
from flytekit.models.literals import LiteralMap
from flytekit.models.task import TaskTemplate
from flytekit.dispatcher.base_dispatcher import INPUTS, DISPATCHER_CONFIG_PKL, DISPATCHER_MODULE, DISPATCHER_NAME

T = typing.TypeVar("T")


class DispatcherEngine(DispatcherAgent):
async def async_do(
self,
context: grpc.ServicerContext,
task_template: TaskTemplate,
inputs: Optional[LiteralMap] = None,
output_prefix: Optional[str] = None,
) -> DoTaskResponse:
python_interface_inputs = {
name: TypeEngine.guess_python_type(lt.type) for name, lt in task_template.interface.inputs.items()
}
ctx = FlyteContextManager.current_context()
if inputs:
native_inputs = TypeEngine.literal_map_to_kwargs(ctx, inputs, python_interface_inputs)
task_template.custom[INPUTS] = native_inputs
else:
raise ValueError("Dispatcher needs a input!")

meta = task_template.custom

dispatcher_module = importlib.import_module(name=meta[DISPATCHER_MODULE])
dispatcher_def = getattr(dispatcher_module, meta[DISPATCHER_NAME])
dispatcher_config = jsonpickle.decode(meta[DISPATCHER_CONFIG_PKL]) if meta.get(DISPATCHER_CONFIG_PKL) else None
inputs = meta.get(INPUTS, {})
return await dispatcher_def("dispatcher", config=dispatcher_config).do(**inputs)


AgentRegistry.register(DispatcherEngine())
38 changes: 37 additions & 1 deletion flytekit/extend/backend/agent_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
CreateTaskResponse,
DeleteTaskRequest,
DeleteTaskResponse,
DoTaskRequest,
DoTaskResponse,
GetTaskRequest,
GetTaskResponse,
)
Expand All @@ -21,6 +23,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 Down Expand Up @@ -114,7 +117,7 @@ async def DeleteTask(self, request: DeleteTaskRequest, context: grpc.ServicerCon
logger.error(f"failed to run async delete with error {e}")
raise
try:
res = asyncio.to_thread(agent.delete, context=context, resource_meta=request.resource_meta)
res = await asyncio.to_thread(agent.delete, context=context, resource_meta=request.resource_meta)
request_success_count.labels(task_type=request.task_type, operation=delete_operation).inc()
return res
except Exception as e:
Expand All @@ -124,3 +127,36 @@ async def DeleteTask(self, request: DeleteTaskRequest, context: grpc.ServicerCon
context.set_code(grpc.StatusCode.INTERNAL)
context.set_details(f"failed to delete task with error {e}")
request_failure_count.labels(task_type=request.task_type, operation=delete_operation).inc()

async def DoTask(self, request: DoTaskRequest, context: grpc.ServicerContext) -> DoTaskResponse:
try:
with request_latency.labels(task_type=request.template.type, operation=do_operation).time():
tmp = TaskTemplate.from_flyte_idl(request.template)
inputs = LiteralMap.from_flyte_idl(request.inputs) if request.inputs else None
input_literal_size.labels(task_type=tmp.type).observe(request.inputs.ByteSize())
agent = AgentRegistry.get_agent(tmp.type)
logger.info(f"{agent.task_type} agent start doing the job")
if agent.asynchronous:
try:
res = await agent.async_do(
context=context, inputs=inputs, task_template=tmp
)
request_success_count.labels(task_type=tmp.type, operation=do_operation).inc()
return res
except Exception as e:
logger.error(f"failed to run async do with error {e}")
raise e
try:
res = await asyncio.to_thread(
agent.do, context=context, inputs=inputs, task_template=tmp
)
request_success_count.labels(task_type=tmp.type, operation=do_operation).inc()
return res
except Exception as e:
logger.error(f"failed to run sync do with error {e}")
raise
except Exception as e:
logger.error(f"failed to do task with error {e}")
context.set_code(grpc.StatusCode.INTERNAL)
context.set_details(f"failed to do task with error {e}")
request_failure_count.labels(task_type=request.task_type, operation=do_operation).inc()
69 changes: 66 additions & 3 deletions flytekit/extend/backend/base_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,19 @@
SUCCEEDED,
CreateTaskResponse,
DeleteTaskResponse,
DoTaskResponse,
GetTaskResponse,
Resource,
State,
)
from flyteidl.core import literals_pb2
from flyteidl.core.tasks_pb2 import TaskTemplate
from rich.progress import Progress

import flytekit
from flytekit import FlyteContext, logger
from flytekit.configuration import ImageConfig, SerializationSettings
from flytekit.core import utils
from flytekit.core.base_task import PythonTask
from flytekit.core.type_engine import TypeEngine
from flytekit.models.literals import LiteralMap
Expand Down Expand Up @@ -79,6 +84,18 @@ def delete(self, context: grpc.ServicerContext, resource_meta: bytes) -> DeleteT
"""
raise NotImplementedError

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

async def async_create(
self,
context: grpc.ServicerContext,
Expand All @@ -105,6 +122,45 @@ 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,
output_prefix: typing.Optional[str] = None,
) -> DoTaskResponse:
"""
Return the result of executing a task. It should return error code if the task creation failed.
"""
raise NotImplementedError


class DispatcherAgent(AgentBase):
def __init__(self):
super().__init__(task_type="dispatcher")

async def _do(
self,
entity: PythonTask,
task_template: TaskTemplate,
agent: AgentBase,
inputs: typing.Dict[str, typing.Any] = None,
) -> DoTaskResponse:
ctx = FlyteContext.current_context()
grpc_ctx = _get_grpc_context()

literals = {}
for k, v in inputs.items():
literals[k] = TypeEngine.to_literal(ctx, v, type(v), entity.interface.inputs[k].type)
inputs = LiteralMap(literals) if literals else None
output_prefix = ctx.file_access.get_random_local_directory()

progress = Progress(transient=True)
task = progress.add_task(f"[cyan]Running Task {entity.name}...", total=None)
with progress:
progress.start_task(task)
return await agent.async_do(context=grpc_ctx, output_prefix=output_prefix, task_template=task_template, inputs=inputs)


class AgentRegistry(object):
"""
Expand Down Expand Up @@ -149,6 +205,10 @@ def is_terminal_state(state: State) -> bool:
return state in [SUCCEEDED, RETRYABLE_FAILURE, PERMANENT_FAILURE]


def get_secret(secret_key: str) -> str:
return flytekit.current_context().secrets.get("flyteagent", secret_key)


class AsyncAgentExecutorMixin:
"""
This mixin class is used to run the agent task locally, and it's only used for local execution.
Expand All @@ -166,8 +226,11 @@ def execute(self, **kwargs) -> typing.Any:
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, DispatcherAgent):
res = asyncio.run(self._agent._do(self._entity, task_template, self._agent, 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 Exception(f"Failed to run the task {self._entity.name}")
Expand Down Expand Up @@ -226,7 +289,7 @@ def signal_handler(self, resource_meta: bytes, signum: int, frame: FrameType) ->
sys.exit(1)


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

grpc_ctx = MagicMock(spec=grpc.ServicerContext)
Expand Down
2 changes: 1 addition & 1 deletion flytekit/sensor/base_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def __init__(
type_hints = get_type_hints(self.poke, include_extras=True)
signature = inspect.signature(self.poke)
inputs = collections.OrderedDict()
for k, v in signature.parameters.items(): # type: ignore
for k, _ in signature.parameters.items(): # type: ignore
annotation = type_hints.get(k, None)
inputs[k] = annotation

Expand Down