clarifai 11.4.2__py3-none-any.whl → 11.4.3rc1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- clarifai/__init__.py +1 -1
- clarifai/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/__pycache__/errors.cpython-312.pyc +0 -0
- clarifai/__pycache__/errors.cpython-39.pyc +0 -0
- clarifai/__pycache__/versions.cpython-312.pyc +0 -0
- clarifai/__pycache__/versions.cpython-39.pyc +0 -0
- clarifai/cli/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/cli/__pycache__/base.cpython-312.pyc +0 -0
- clarifai/cli/__pycache__/compute_cluster.cpython-312.pyc +0 -0
- clarifai/cli/__pycache__/deployment.cpython-312.pyc +0 -0
- clarifai/cli/__pycache__/model.cpython-312.pyc +0 -0
- clarifai/cli/__pycache__/nodepool.cpython-312.pyc +0 -0
- clarifai/cli/base.py +8 -0
- clarifai/cli/model.py +6 -6
- clarifai/client/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/app.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/app.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/base.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/base.cpython-39.pyc +0 -0
- clarifai/client/__pycache__/compute_cluster.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/dataset.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/deployment.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/input.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/lister.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/model.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/model_client.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/module.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/nodepool.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/runner.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/search.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/user.cpython-312.pyc +0 -0
- clarifai/client/__pycache__/workflow.cpython-312.pyc +0 -0
- clarifai/client/auth/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/client/auth/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/client/auth/__pycache__/helper.cpython-312.pyc +0 -0
- clarifai/client/auth/__pycache__/helper.cpython-39.pyc +0 -0
- clarifai/client/auth/__pycache__/register.cpython-312.pyc +0 -0
- clarifai/client/auth/__pycache__/register.cpython-39.pyc +0 -0
- clarifai/client/auth/__pycache__/stub.cpython-312.pyc +0 -0
- clarifai/client/auth/__pycache__/stub.cpython-39.pyc +0 -0
- clarifai/constants/__pycache__/base.cpython-312.pyc +0 -0
- clarifai/constants/__pycache__/base.cpython-39.pyc +0 -0
- clarifai/constants/__pycache__/dataset.cpython-312.pyc +0 -0
- clarifai/constants/__pycache__/input.cpython-312.pyc +0 -0
- clarifai/constants/__pycache__/model.cpython-312.pyc +0 -0
- clarifai/constants/__pycache__/rag.cpython-312.pyc +0 -0
- clarifai/constants/__pycache__/search.cpython-312.pyc +0 -0
- clarifai/constants/__pycache__/workflow.cpython-312.pyc +0 -0
- clarifai/datasets/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/datasets/export/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/datasets/export/__pycache__/inputs_annotations.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/base.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/features.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/image.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/multimodal.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/text.cpython-312.pyc +0 -0
- clarifai/datasets/upload/__pycache__/utils.cpython-312.pyc +0 -0
- clarifai/datasets/upload/loaders/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/datasets/upload/loaders/__pycache__/coco_detection.cpython-312.pyc +0 -0
- clarifai/datasets/upload/loaders/__pycache__/imagenet_classification.cpython-312.pyc +0 -0
- clarifai/modules/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/modules/__pycache__/css.cpython-312.pyc +0 -0
- clarifai/rag/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/rag/__pycache__/rag.cpython-312.pyc +0 -0
- clarifai/rag/__pycache__/utils.cpython-312.pyc +0 -0
- clarifai/runners/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/runners/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/runners/__pycache__/server.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/runners/models/__pycache__/base_typed_model.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/mcp_class.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/model_builder.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/model_builder.cpython-39.pyc +0 -0
- clarifai/runners/models/__pycache__/model_class.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/model_run_locally.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/model_runner.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/model_servicer.cpython-312.pyc +0 -0
- clarifai/runners/models/__pycache__/test_model_builder.cpython-312-pytest-8.3.5.pyc +0 -0
- clarifai/runners/models/base_typed_model.py +238 -0
- clarifai/runners/models/example_mcp_server.py +44 -0
- clarifai/runners/models/mcp_class.py +143 -0
- clarifai/runners/models/mcp_class.py~ +149 -0
- clarifai/runners/models/model_builder.py +37 -12
- clarifai/runners/models/test_model_builder.py +89 -0
- clarifai/runners/utils/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/code_script.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/const.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/data_handler.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/data_types.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/data_utils.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/loader.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/method_signatures.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/serializers.cpython-312.pyc +0 -0
- clarifai/runners/utils/__pycache__/url_fetcher.cpython-312.pyc +0 -0
- clarifai/runners/utils/data_handler.py +231 -0
- clarifai/runners/utils/data_types/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/runners/utils/data_types/__pycache__/data_types.cpython-312.pyc +0 -0
- clarifai/schema/__pycache__/search.cpython-312.pyc +0 -0
- clarifai/urls/__pycache__/helper.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/__init__.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/cli.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/config.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/constants.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/constants.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/logging.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/logging.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/misc.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/misc.cpython-39.pyc +0 -0
- clarifai/utils/__pycache__/model_train.cpython-312.pyc +0 -0
- clarifai/utils/__pycache__/protobuf.cpython-312.pyc +0 -0
- clarifai/utils/config.py +19 -0
- clarifai/utils/config.py~ +145 -0
- clarifai/utils/evaluation/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/utils/evaluation/__pycache__/helpers.cpython-312.pyc +0 -0
- clarifai/utils/evaluation/__pycache__/main.cpython-312.pyc +0 -0
- clarifai/workflows/__pycache__/__init__.cpython-312.pyc +0 -0
- clarifai/workflows/__pycache__/export.cpython-312.pyc +0 -0
- clarifai/workflows/__pycache__/utils.cpython-312.pyc +0 -0
- clarifai/workflows/__pycache__/validate.cpython-312.pyc +0 -0
- {clarifai-11.4.2.dist-info → clarifai-11.4.3rc1.dist-info}/METADATA +2 -13
- clarifai-11.4.3rc1.dist-info/RECORD +230 -0
- {clarifai-11.4.2.dist-info → clarifai-11.4.3rc1.dist-info}/WHEEL +1 -1
- clarifai-11.4.2.dist-info/RECORD +0 -111
- {clarifai-11.4.2.dist-info/licenses → clarifai-11.4.3rc1.dist-info}/LICENSE +0 -0
- {clarifai-11.4.2.dist-info → clarifai-11.4.3rc1.dist-info}/entry_points.txt +0 -0
- {clarifai-11.4.2.dist-info → clarifai-11.4.3rc1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,143 @@
|
|
1
|
+
"""Base class for creating Model Context Protocol (MCP) servers."""
|
2
|
+
|
3
|
+
import asyncio
|
4
|
+
import json
|
5
|
+
from typing import Any
|
6
|
+
|
7
|
+
from fastmcp import Client, FastMCP # use fastmcp v2 not the built in mcp
|
8
|
+
from mcp import types
|
9
|
+
from mcp.shared.exceptions import McpError
|
10
|
+
|
11
|
+
from clarifai.runners.models.model_class import ModelClass
|
12
|
+
|
13
|
+
# class MCPServerProvider(abc.ABC):
|
14
|
+
# """
|
15
|
+
# Base class for creating Model Context Protocol (MCP) servers.
|
16
|
+
|
17
|
+
# This class provides a base implementation of the MCP server, including
|
18
|
+
# methods for handling requests and responses, as well as error handling and
|
19
|
+
# logging.
|
20
|
+
|
21
|
+
# Attributes:
|
22
|
+
# _server: The FastMCP server instance.
|
23
|
+
# _tools: List of tools available in the server.
|
24
|
+
# _resources: List of resources available in the server.
|
25
|
+
# _prompts: List of prompts available in the server.
|
26
|
+
|
27
|
+
# Methods:
|
28
|
+
# get_server(): Returns the FastMCP server instance.
|
29
|
+
# mcp_transport(msg): Handles incoming messages and sends them to the FastMCP server.
|
30
|
+
# """
|
31
|
+
|
32
|
+
# @abc.abstractmethod
|
33
|
+
# def get_server(self) -> FastMCP:
|
34
|
+
# """Required method for each subclass to implement to return the FastMCP server to use."""
|
35
|
+
# if self._server is None:
|
36
|
+
# raise ValueError("Server not initialized")
|
37
|
+
# return self._server
|
38
|
+
|
39
|
+
|
40
|
+
class MCPModelClass(ModelClass):
|
41
|
+
"""Base class for wrapping FastMCP servers as a model running in Clarfai. This handles
|
42
|
+
all the transport between the API and the MCP server here. Simply subclass this and implement
|
43
|
+
the get_server() method to return the FastMCP server instance. The server is then used to
|
44
|
+
handle all the requests and responses.
|
45
|
+
"""
|
46
|
+
|
47
|
+
def load_model(self):
|
48
|
+
# in memory transport provided in fastmcp v2 so we can easily use the client functions.
|
49
|
+
self.client = Client(self.get_server())
|
50
|
+
|
51
|
+
def get_server(self) -> FastMCP:
|
52
|
+
"""Required method for each subclass to implement to return the FastMCP server to use."""
|
53
|
+
raise NotImplementedError("Subclasses must implement get_server() method")
|
54
|
+
|
55
|
+
@ModelClass.method
|
56
|
+
def mcp_transport(self, msg: str) -> str:
|
57
|
+
"""The single model method to get the jsonrpc message and send it to the FastMCP server then
|
58
|
+
return it's response.
|
59
|
+
|
60
|
+
"""
|
61
|
+
|
62
|
+
async def send_notification(client_message: types.ClientNotification) -> None:
|
63
|
+
async with self.client:
|
64
|
+
# Strip the jsonrpc field since send_notification will also pass it in for some reason.
|
65
|
+
client_message = types.ClientNotification.model_validate(
|
66
|
+
client_message.model_dump(
|
67
|
+
by_alias=True, mode="json", exclude_none=True, exclude={"jsonrpc"}
|
68
|
+
)
|
69
|
+
)
|
70
|
+
try:
|
71
|
+
return await self.client.session.send_notification(client_message)
|
72
|
+
except McpError as e:
|
73
|
+
return types.JSONRPCError(jsonrpc="2.0", error=e.error)
|
74
|
+
|
75
|
+
async def send_request(client_message: types.ClientRequest, id: str) -> Any:
|
76
|
+
async with self.client:
|
77
|
+
# Strip the jsonrpc and id fields as send_request sets them again too.
|
78
|
+
client_message = types.ClientRequest.model_validate(
|
79
|
+
client_message.model_dump(
|
80
|
+
by_alias=True, mode="json", exclude_none=True, exclude={"jsonrpc", "id"}
|
81
|
+
)
|
82
|
+
)
|
83
|
+
|
84
|
+
result_type = None
|
85
|
+
print("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
|
86
|
+
print(types.PingRequest)
|
87
|
+
if isinstance(client_message.root, types.PingRequest):
|
88
|
+
result_type = types.EmptyResult
|
89
|
+
elif isinstance(client_message.root, types.InitializeRequest):
|
90
|
+
return await self.client.session.initialize()
|
91
|
+
elif isinstance(client_message.root, types.SetLevelRequest):
|
92
|
+
result_type = types.EmptyResult
|
93
|
+
elif isinstance(client_message.root, types.ListResourcesRequest):
|
94
|
+
result_type = types.ListResourcesResult
|
95
|
+
elif isinstance(client_message.root, types.ListResourceTemplatesRequest):
|
96
|
+
result_type = types.ListResourceTemplatesResult
|
97
|
+
elif isinstance(client_message.root, types.ReadResourceRequest):
|
98
|
+
result_type = types.ReadResourceResult
|
99
|
+
elif isinstance(client_message.root, types.SubscribeRequest):
|
100
|
+
result_type = types.EmptyResult
|
101
|
+
elif isinstance(client_message.root, types.UnsubscribeRequest):
|
102
|
+
result_type = types.EmptyResult
|
103
|
+
elif isinstance(client_message.root, types.ListPromptsRequest):
|
104
|
+
result_type = types.ListPromptsResult
|
105
|
+
elif isinstance(client_message.root, types.GetPromptRequest):
|
106
|
+
result_type = types.GetPromptResult
|
107
|
+
elif isinstance(client_message.root, types.CompleteRequest):
|
108
|
+
result_type = types.CompleteResult
|
109
|
+
elif isinstance(client_message.root, types.ListToolsRequest):
|
110
|
+
result_type = types.ListToolsResult
|
111
|
+
elif isinstance(client_message.root, types.CallToolRequest):
|
112
|
+
result_type = types.CallToolResult
|
113
|
+
else:
|
114
|
+
# this is a special case where we need to return the list of tools.
|
115
|
+
raise NotImplementedError(f"Method {client_message.method} not implemented")
|
116
|
+
# Call the mcp server using send_request() or send_notification() depending on the method.
|
117
|
+
try:
|
118
|
+
return await self.client.session.send_request(client_message, result_type)
|
119
|
+
except McpError as e:
|
120
|
+
return types.JSONRPCError(jsonrpc="2.0", id=id, error=e.error)
|
121
|
+
|
122
|
+
# The message coming here is the generic request. We look at it's .method
|
123
|
+
# to determine which client function to call and to further subparse the params.
|
124
|
+
# Note(zeiler): unfortunately the pydantic types in mcp/types.py are not consistent.
|
125
|
+
# The JSONRPCRequest are supposed to have an id but the InitializeRequest
|
126
|
+
# does not have it.
|
127
|
+
d = json.loads(msg)
|
128
|
+
|
129
|
+
# If we have an id it's a JSONRPCRequest
|
130
|
+
if not d.get('method', None).startswith("notifications/"):
|
131
|
+
# rpc_message2 = types.JSONRPCRequest.model_validate(rpc_message)
|
132
|
+
# underlying: types.JSONRPCRequest = rpc_message.root
|
133
|
+
client_message = types.ClientRequest.model_validate(d)
|
134
|
+
response = asyncio.run(
|
135
|
+
send_request(client_message, id=d.get('id', ""))
|
136
|
+
) # underlying.id))
|
137
|
+
else: # JSONRPCRequest
|
138
|
+
client_message = types.ClientNotification.model_validate(d)
|
139
|
+
response = asyncio.run(send_notification(client_message))
|
140
|
+
if response is None:
|
141
|
+
return ""
|
142
|
+
# return as a serialized json string
|
143
|
+
return response.model_dump_json(by_alias=True, exclude_none=True)
|
@@ -0,0 +1,149 @@
|
|
1
|
+
"""Base class for creating Model Context Protocol (MCP) servers."""
|
2
|
+
|
3
|
+
import asyncio
|
4
|
+
import json
|
5
|
+
from typing import Any
|
6
|
+
|
7
|
+
from fastmcp import Client, FastMCP # use fastmcp v2 not the built in mcp
|
8
|
+
from mcp import types
|
9
|
+
from mcp.shared.exceptions import McpError
|
10
|
+
|
11
|
+
from clarifai.runners.models.model_class import ModelClass
|
12
|
+
|
13
|
+
# class MCPServerProvider(abc.ABC):
|
14
|
+
# """
|
15
|
+
# Base class for creating Model Context Protocol (MCP) servers.
|
16
|
+
|
17
|
+
# This class provides a base implementation of the MCP server, including
|
18
|
+
# methods for handling requests and responses, as well as error handling and
|
19
|
+
# logging.
|
20
|
+
|
21
|
+
# Attributes:
|
22
|
+
# _server: The FastMCP server instance.
|
23
|
+
# _tools: List of tools available in the server.
|
24
|
+
# _resources: List of resources available in the server.
|
25
|
+
# _prompts: List of prompts available in the server.
|
26
|
+
|
27
|
+
# Methods:
|
28
|
+
# get_server(): Returns the FastMCP server instance.
|
29
|
+
# mcp_transport(msg): Handles incoming messages and sends them to the FastMCP server.
|
30
|
+
# """
|
31
|
+
|
32
|
+
# @abc.abstractmethod
|
33
|
+
# def get_server(self) -> FastMCP:
|
34
|
+
# """Required method for each subclass to implement to return the FastMCP server to use."""
|
35
|
+
# if self._server is None:
|
36
|
+
# raise ValueError("Server not initialized")
|
37
|
+
# return self._server
|
38
|
+
|
39
|
+
|
40
|
+
class MCPModelClass(ModelClass, MCPServerProvider):
|
41
|
+
"""Base class for wrapping FastMCP servers as a model running in Clarfai. This handles
|
42
|
+
all the transport between the API and the MCP server here. Simply subclass this and implement
|
43
|
+
the get_server() method to return the FastMCP server instance. The server is then used to
|
44
|
+
handle all the requests and responses.
|
45
|
+
"""
|
46
|
+
|
47
|
+
def load_model(self):
|
48
|
+
# in memory transport provided in fastmcp v2 so we can easily use the client functions.
|
49
|
+
self.client = Client(self.get_server())
|
50
|
+
|
51
|
+
def get_server(self) -> FastMCP:
|
52
|
+
"""Required method for each subclass to implement to return the FastMCP server to use."""
|
53
|
+
if self._server is None:
|
54
|
+
raise ValueError("Server not initialized")
|
55
|
+
return self._server
|
56
|
+
|
57
|
+
@ModelClass.method
|
58
|
+
def mcp_transport(self, msg: str) -> str:
|
59
|
+
"""The single model method to get the jsonrpc message and send it to the FastMCP server then
|
60
|
+
return it's response.
|
61
|
+
|
62
|
+
Arguments:
|
63
|
+
msg: The incoming message to be handled in serialized JSONRPC format from an MCP client.
|
64
|
+
Returns:
|
65
|
+
str: The response to the incoming message in serialized JSONRPC format
|
66
|
+
"""
|
67
|
+
|
68
|
+
async def send_notification(client_message: types.ClientNotification) -> None:
|
69
|
+
async with self.client:
|
70
|
+
# Strip the jsonrpc field since send_notification will also pass it in for some reason.
|
71
|
+
client_message = types.ClientNotification.model_validate(
|
72
|
+
client_message.model_dump(
|
73
|
+
by_alias=True, mode="json", exclude_none=True, exclude={"jsonrpc"}
|
74
|
+
)
|
75
|
+
)
|
76
|
+
try:
|
77
|
+
return await self.client.session.send_notification(client_message)
|
78
|
+
except McpError as e:
|
79
|
+
return types.JSONRPCError(jsonrpc="2.0", error=e.error)
|
80
|
+
|
81
|
+
async def send_request(client_message: types.ClientRequest, id: str) -> Any:
|
82
|
+
async with self.client:
|
83
|
+
# Strip the jsonrpc and id fields as send_request sets them again too.
|
84
|
+
client_message = types.ClientRequest.model_validate(
|
85
|
+
client_message.model_dump(
|
86
|
+
by_alias=True, mode="json", exclude_none=True, exclude={"jsonrpc", "id"}
|
87
|
+
)
|
88
|
+
)
|
89
|
+
|
90
|
+
result_type = None
|
91
|
+
print("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")
|
92
|
+
print(types.PingRequest)
|
93
|
+
if isinstance(client_message.root, types.PingRequest):
|
94
|
+
result_type = types.EmptyResult
|
95
|
+
elif isinstance(client_message.root, types.InitializeRequest):
|
96
|
+
return await self.client.session.initialize()
|
97
|
+
elif isinstance(client_message.root, types.SetLevelRequest):
|
98
|
+
result_type = types.EmptyResult
|
99
|
+
elif isinstance(client_message.root, types.ListResourcesRequest):
|
100
|
+
result_type = types.ListResourcesResult
|
101
|
+
elif isinstance(client_message.root, types.ListResourceTemplatesRequest):
|
102
|
+
result_type = types.ListResourceTemplatesResult
|
103
|
+
elif isinstance(client_message.root, types.ReadResourceRequest):
|
104
|
+
result_type = types.ReadResourceResult
|
105
|
+
elif isinstance(client_message.root, types.SubscribeRequest):
|
106
|
+
result_type = types.EmptyResult
|
107
|
+
elif isinstance(client_message.root, types.UnsubscribeRequest):
|
108
|
+
result_type = types.EmptyResult
|
109
|
+
elif isinstance(client_message.root, types.ListPromptsRequest):
|
110
|
+
result_type = types.ListPromptsResult
|
111
|
+
elif isinstance(client_message.root, types.GetPromptRequest):
|
112
|
+
result_type = types.GetPromptResult
|
113
|
+
elif isinstance(client_message.root, types.CompleteRequest):
|
114
|
+
result_type = types.CompleteResult
|
115
|
+
elif isinstance(client_message.root, types.ListToolsRequest):
|
116
|
+
result_type = types.ListToolsResult
|
117
|
+
elif isinstance(client_message.root, types.CallToolRequest):
|
118
|
+
result_type = types.CallToolResult
|
119
|
+
else:
|
120
|
+
# this is a special case where we need to return the list of tools.
|
121
|
+
raise NotImplementedError(f"Method {client_message.method} not implemented")
|
122
|
+
# Call the mcp server using send_request() or send_notification() depending on the method.
|
123
|
+
try:
|
124
|
+
return await self.client.session.send_request(client_message, result_type)
|
125
|
+
except McpError as e:
|
126
|
+
return types.JSONRPCError(jsonrpc="2.0", id=id, error=e.error)
|
127
|
+
|
128
|
+
# The message coming here is the generic request. We look at it's .method
|
129
|
+
# to determine which client function to call and to further subparse the params.
|
130
|
+
# Note(zeiler): unfortunately the pydantic types in mcp/types.py are not consistent.
|
131
|
+
# The JSONRPCRequest are supposed to have an id but the InitializeRequest
|
132
|
+
# does not have it.
|
133
|
+
d = json.loads(msg)
|
134
|
+
|
135
|
+
# If we have an id it's a JSONRPCRequest
|
136
|
+
if not d.get('method', None).startswith("notifications/"):
|
137
|
+
# rpc_message2 = types.JSONRPCRequest.model_validate(rpc_message)
|
138
|
+
# underlying: types.JSONRPCRequest = rpc_message.root
|
139
|
+
client_message = types.ClientRequest.model_validate(d)
|
140
|
+
response = asyncio.run(
|
141
|
+
send_request(client_message, id=d.get('id', ""))
|
142
|
+
) # underlying.id))
|
143
|
+
else: # JSONRPCRequest
|
144
|
+
client_message = types.ClientNotification.model_validate(d)
|
145
|
+
response = asyncio.run(send_notification(client_message))
|
146
|
+
if response is None:
|
147
|
+
return ""
|
148
|
+
# return as a serialized json string
|
149
|
+
return response.model_dump_json(by_alias=True, exclude_none=True)
|
@@ -410,11 +410,11 @@ class ModelBuilder:
|
|
410
410
|
signatures = {method.name: method.signature for method in method_info.values()}
|
411
411
|
return signatures_to_yaml(signatures)
|
412
412
|
|
413
|
-
def get_method_signatures(self):
|
413
|
+
def get_method_signatures(self, mocking=True):
|
414
414
|
"""
|
415
415
|
Returns the method signatures for the model class.
|
416
416
|
"""
|
417
|
-
model_class = self.load_model_class(mocking=
|
417
|
+
model_class = self.load_model_class(mocking=mocking)
|
418
418
|
method_info = model_class._get_method_info()
|
419
419
|
signatures = [method.signature for method in method_info.values()]
|
420
420
|
return signatures
|
@@ -934,18 +934,43 @@ class ModelBuilder:
|
|
934
934
|
try:
|
935
935
|
is_uploaded = self.monitor_model_build()
|
936
936
|
if is_uploaded:
|
937
|
-
|
938
|
-
|
939
|
-
|
940
|
-
|
941
|
-
|
942
|
-
|
943
|
-
|
944
|
-
|
945
|
-
|
937
|
+
# Provide an mcp client config
|
938
|
+
if model_type_id == "mcp":
|
939
|
+
snippet = (
|
940
|
+
"""
|
941
|
+
import asyncio
|
942
|
+
import os
|
943
|
+
from fastmcp import Client
|
944
|
+
from fastmcp.client.transports import StreamableHttpTransport
|
945
|
+
|
946
|
+
transport = StreamableHttpTransport(url="%s/mcp",
|
947
|
+
headers={"Authorization": "Bearer " + os.environ["CLARIFAI_PAT"]})
|
948
|
+
|
949
|
+
async def main():
|
950
|
+
async with Client(transport) as client:
|
951
|
+
tools = await client.list_tools()
|
952
|
+
print(f"Available tools: {tools}")
|
953
|
+
result = await client.call_tool(tools[0].name, {"a": 5, "b": 3})
|
954
|
+
print(f"Result: {result[0].text}")
|
955
|
+
|
956
|
+
if __name__ == "__main__":
|
957
|
+
asyncio.run(main())
|
958
|
+
"""
|
959
|
+
% self.model_url
|
960
|
+
)
|
961
|
+
else: # python code to run the model.
|
962
|
+
from clarifai.runners.utils import code_script
|
963
|
+
|
964
|
+
method_signatures = self.get_method_signatures()
|
965
|
+
snippet = code_script.generate_client_script(
|
966
|
+
method_signatures,
|
967
|
+
user_id=self.client.user_app_id.user_id,
|
968
|
+
app_id=self.client.user_app_id.app_id,
|
969
|
+
model_id=self.model_proto.id,
|
970
|
+
)
|
946
971
|
logger.info("""\n
|
947
972
|
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
948
|
-
# Here is a code snippet to
|
973
|
+
# Here is a code snippet to use this model:
|
949
974
|
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
950
975
|
""")
|
951
976
|
logger.info(snippet)
|
@@ -0,0 +1,89 @@
|
|
1
|
+
import unittest
|
2
|
+
from unittest.mock import patch, mock_open
|
3
|
+
from clarifai.runners.models.model_builder import (
|
4
|
+
ModelBuilder,
|
5
|
+
DEFAULT_DOWNLOAD_CHECKPOINT_WHEN,
|
6
|
+
)
|
7
|
+
|
8
|
+
mock_data = """
|
9
|
+
checkpoints:
|
10
|
+
type: huggingface
|
11
|
+
repo_id: test_repo
|
12
|
+
model:
|
13
|
+
user_id: test_user
|
14
|
+
app_id: test_app
|
15
|
+
id: test_model
|
16
|
+
model_type_id: test_type
|
17
|
+
inference_compute_info:
|
18
|
+
cpu_limit: "2"
|
19
|
+
cpu_memory: "4Gi"
|
20
|
+
num_accelerators: 0
|
21
|
+
"""
|
22
|
+
|
23
|
+
|
24
|
+
class TestModelBuilder(unittest.TestCase):
|
25
|
+
@patch("builtins.open", new_callable=mock_open, read_data=mock_data)
|
26
|
+
@patch("os.path.exists")
|
27
|
+
@patch("os.listdir")
|
28
|
+
def test_validate_folder(self, mock_listdir, mock_exists, mock_open_file):
|
29
|
+
mock_exists.return_value = True
|
30
|
+
mock_listdir.return_value = ["config.yaml", "1", "requirements.txt"]
|
31
|
+
|
32
|
+
builder = ModelBuilder(folder="test_folder", validate_api_ids=False)
|
33
|
+
validated_folder = builder._validate_folder("test_folder")
|
34
|
+
self.assertIn("test_folder", validated_folder)
|
35
|
+
|
36
|
+
def test_default_download_checkpoint_when(self):
|
37
|
+
self.assertEqual(DEFAULT_DOWNLOAD_CHECKPOINT_WHEN, "runtime")
|
38
|
+
|
39
|
+
@patch(
|
40
|
+
"builtins.open",
|
41
|
+
new_callable=mock_open,
|
42
|
+
read_data="checkpoints:\n type: huggingface\n repo_id: test_repo\n",
|
43
|
+
)
|
44
|
+
@patch("os.path.exists")
|
45
|
+
@patch("yaml.safe_load")
|
46
|
+
def test_load_config(self, mock_yaml_load, mock_exists, mock_open_file):
|
47
|
+
mock_exists.return_value = True
|
48
|
+
mock_yaml_load.return_value = {
|
49
|
+
"checkpoints": {"type": "huggingface", "repo_id": "test_repo"}
|
50
|
+
}
|
51
|
+
config = ModelBuilder._load_config("config.yaml")
|
52
|
+
self.assertIn("checkpoints", config)
|
53
|
+
self.assertEqual(config["checkpoints"]["type"], "huggingface")
|
54
|
+
|
55
|
+
@patch("shutil.copy")
|
56
|
+
@patch("os.path.exists")
|
57
|
+
def test_backup_config(self, mock_exists, mock_copy):
|
58
|
+
mock_exists.side_effect = [True, False] # config exists, backup does not
|
59
|
+
ModelBuilder._backup_config("config.yaml")
|
60
|
+
mock_copy.assert_called_once_with("config.yaml", "config.yaml.bak")
|
61
|
+
|
62
|
+
@patch("builtins.open", new_callable=mock_open)
|
63
|
+
@patch("yaml.safe_dump")
|
64
|
+
def test_save_config(self, mock_yaml_dump, mock_open_file):
|
65
|
+
config = {"key": "value"}
|
66
|
+
ModelBuilder._save_config("config.yaml", config)
|
67
|
+
mock_yaml_dump.assert_called_once_with(config, mock_open_file())
|
68
|
+
|
69
|
+
def test_validate_config_model(self):
|
70
|
+
builder = ModelBuilder(folder="test_folder", validate_api_ids=False)
|
71
|
+
builder.config = {"model": {}}
|
72
|
+
try:
|
73
|
+
builder._validate_config_model()
|
74
|
+
except AssertionError:
|
75
|
+
self.fail("_validate_config_model raised AssertionError unexpectedly!")
|
76
|
+
|
77
|
+
@patch("os.path.exists")
|
78
|
+
@patch("os.listdir")
|
79
|
+
def test_validate_folder_missing_config(self, mock_listdir, mock_exists):
|
80
|
+
mock_exists.return_value = True
|
81
|
+
mock_listdir.return_value = ["1", "requirements.txt"]
|
82
|
+
|
83
|
+
builder = ModelBuilder(folder="test_folder", validate_api_ids=False)
|
84
|
+
with self.assertRaises(AssertionError):
|
85
|
+
builder._validate_folder("test_folder")
|
86
|
+
|
87
|
+
|
88
|
+
if __name__ == "__main__":
|
89
|
+
unittest.main()
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|
Binary file
|