microsoft-agents-hosting-fastapi 0.7.0.dev0__tar.gz → 0.7.0.dev4__tar.gz

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.
Files changed (26) hide show
  1. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/PKG-INFO +2 -2
  2. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/microsoft_agents/hosting/fastapi/__init__.py +3 -1
  3. microsoft_agents_hosting_fastapi-0.7.0.dev4/microsoft_agents/hosting/fastapi/channel_service_route_table.py +148 -0
  4. microsoft_agents_hosting_fastapi-0.7.0.dev4/microsoft_agents/hosting/fastapi/cloud_adapter.py +94 -0
  5. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/microsoft_agents_hosting_fastapi.egg-info/PKG-INFO +2 -2
  6. microsoft_agents_hosting_fastapi-0.7.0.dev4/microsoft_agents_hosting_fastapi.egg-info/requires.txt +2 -0
  7. microsoft_agents_hosting_fastapi-0.7.0.dev4/setup.py +18 -0
  8. microsoft_agents_hosting_fastapi-0.7.0.dev0/microsoft_agents/hosting/fastapi/channel_service_route_table.py +0 -205
  9. microsoft_agents_hosting_fastapi-0.7.0.dev0/microsoft_agents/hosting/fastapi/cloud_adapter.py +0 -113
  10. microsoft_agents_hosting_fastapi-0.7.0.dev0/microsoft_agents_hosting_fastapi.egg-info/requires.txt +0 -2
  11. microsoft_agents_hosting_fastapi-0.7.0.dev0/setup.py +0 -12
  12. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/LICENSE +0 -0
  13. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/microsoft_agents/hosting/fastapi/_start_agent_process.py +0 -0
  14. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/microsoft_agents/hosting/fastapi/agent_http_adapter.py +0 -0
  15. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/microsoft_agents/hosting/fastapi/app/__init__.py +0 -0
  16. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/microsoft_agents/hosting/fastapi/app/streaming/__init__.py +0 -0
  17. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/microsoft_agents/hosting/fastapi/app/streaming/citation.py +0 -0
  18. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/microsoft_agents/hosting/fastapi/app/streaming/citation_util.py +0 -0
  19. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/microsoft_agents/hosting/fastapi/app/streaming/streaming_response.py +0 -0
  20. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/microsoft_agents/hosting/fastapi/jwt_authorization_middleware.py +0 -0
  21. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/microsoft_agents_hosting_fastapi.egg-info/SOURCES.txt +0 -0
  22. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/microsoft_agents_hosting_fastapi.egg-info/dependency_links.txt +0 -0
  23. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/microsoft_agents_hosting_fastapi.egg-info/top_level.txt +0 -0
  24. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/pyproject.toml +0 -0
  25. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/readme.md +0 -0
  26. {microsoft_agents_hosting_fastapi-0.7.0.dev0 → microsoft_agents_hosting_fastapi-0.7.0.dev4}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: microsoft-agents-hosting-fastapi
3
- Version: 0.7.0.dev0
3
+ Version: 0.7.0.dev4
4
4
  Summary: Integration library for Microsoft Agents with FastAPI
5
5
  Author: Microsoft Corporation
6
6
  License-Expression: MIT
@@ -10,7 +10,7 @@ Classifier: Operating System :: OS Independent
10
10
  Requires-Python: >=3.10
11
11
  Description-Content-Type: text/markdown
12
12
  License-File: LICENSE
13
- Requires-Dist: microsoft-agents-hosting-core==0.7.0.dev0
13
+ Requires-Dist: microsoft-agents-hosting-core==0.7.0.dev4
14
14
  Requires-Dist: fastapi>=0.104.0
15
15
  Dynamic: license-file
16
16
  Dynamic: requires-dist
@@ -5,7 +5,9 @@ from .cloud_adapter import CloudAdapter
5
5
  from .jwt_authorization_middleware import (
6
6
  JwtAuthorizationMiddleware,
7
7
  )
8
- from .app.streaming import (
8
+
9
+ # Import streaming utilities from core for backward compatibility
10
+ from microsoft_agents.hosting.core.app.streaming import (
9
11
  Citation,
10
12
  CitationUtil,
11
13
  StreamingResponse,
@@ -0,0 +1,148 @@
1
+ # Copyright (c) Microsoft Corporation. All rights reserved.
2
+ # Licensed under the MIT License.
3
+
4
+ from fastapi import APIRouter, Request, Response
5
+ from fastapi.responses import JSONResponse
6
+
7
+ from microsoft_agents.hosting.core import ChannelApiHandlerProtocol
8
+ from microsoft_agents.hosting.core.http import ChannelServiceRoutes
9
+
10
+
11
+ class FastApiRequestAdapter:
12
+ """Adapter for FastAPI requests to use with ChannelServiceRoutes."""
13
+
14
+ def __init__(self, request: Request):
15
+ self._request = request
16
+
17
+ @property
18
+ def method(self) -> str:
19
+ return self._request.method
20
+
21
+ @property
22
+ def headers(self):
23
+ return self._request.headers
24
+
25
+ async def json(self):
26
+ return await self._request.json()
27
+
28
+ def get_claims_identity(self):
29
+ return getattr(self._request.state, "claims_identity", None)
30
+
31
+ def get_path_param(self, name: str) -> str:
32
+ return self._request.path_params.get(name, "")
33
+
34
+
35
+ def channel_service_route_table(
36
+ handler: ChannelApiHandlerProtocol, base_url: str = ""
37
+ ) -> APIRouter:
38
+ """Create FastAPI router for Channel Service API.
39
+
40
+ Args:
41
+ handler: The handler that implements the Channel API protocol.
42
+ base_url: Optional base URL prefix for all routes.
43
+
44
+ Returns:
45
+ APIRouter with all channel service routes.
46
+ """
47
+ router = APIRouter()
48
+ service_routes = ChannelServiceRoutes(handler, base_url)
49
+
50
+ @router.post(base_url + "/v3/conversations/{conversation_id}/activities")
51
+ async def send_to_conversation(conversation_id: str, request: Request):
52
+ result = await service_routes.send_to_conversation(
53
+ FastApiRequestAdapter(request)
54
+ )
55
+ return JSONResponse(content=result)
56
+
57
+ @router.post(
58
+ base_url + "/v3/conversations/{conversation_id}/activities/{activity_id}"
59
+ )
60
+ async def reply_to_activity(
61
+ conversation_id: str, activity_id: str, request: Request
62
+ ):
63
+ result = await service_routes.reply_to_activity(FastApiRequestAdapter(request))
64
+ return JSONResponse(content=result)
65
+
66
+ @router.put(
67
+ base_url + "/v3/conversations/{conversation_id}/activities/{activity_id}"
68
+ )
69
+ async def update_activity(conversation_id: str, activity_id: str, request: Request):
70
+ result = await service_routes.update_activity(FastApiRequestAdapter(request))
71
+ return JSONResponse(content=result)
72
+
73
+ @router.delete(
74
+ base_url + "/v3/conversations/{conversation_id}/activities/{activity_id}"
75
+ )
76
+ async def delete_activity(conversation_id: str, activity_id: str, request: Request):
77
+ await service_routes.delete_activity(FastApiRequestAdapter(request))
78
+ return Response(status_code=200)
79
+
80
+ @router.get(
81
+ base_url
82
+ + "/v3/conversations/{conversation_id}/activities/{activity_id}/members"
83
+ )
84
+ async def get_activity_members(
85
+ conversation_id: str, activity_id: str, request: Request
86
+ ):
87
+ result = await service_routes.get_activity_members(
88
+ FastApiRequestAdapter(request)
89
+ )
90
+ return JSONResponse(content=result)
91
+
92
+ @router.post(base_url + "/")
93
+ async def create_conversation(request: Request):
94
+ result = await service_routes.create_conversation(
95
+ FastApiRequestAdapter(request)
96
+ )
97
+ return JSONResponse(content=result)
98
+
99
+ @router.get(base_url + "/")
100
+ async def get_conversation(request: Request):
101
+ result = await service_routes.get_conversations(FastApiRequestAdapter(request))
102
+ return JSONResponse(content=result)
103
+
104
+ @router.get(base_url + "/v3/conversations/{conversation_id}/members")
105
+ async def get_conversation_members(conversation_id: str, request: Request):
106
+ result = await service_routes.get_conversation_members(
107
+ FastApiRequestAdapter(request)
108
+ )
109
+ return JSONResponse(content=result)
110
+
111
+ @router.get(base_url + "/v3/conversations/{conversation_id}/members/{member_id}")
112
+ async def get_conversation_member(
113
+ conversation_id: str, member_id: str, request: Request
114
+ ):
115
+ result = await service_routes.get_conversation_member(
116
+ FastApiRequestAdapter(request)
117
+ )
118
+ return JSONResponse(content=result)
119
+
120
+ @router.get(base_url + "/v3/conversations/{conversation_id}/pagedmembers")
121
+ async def get_conversation_paged_members(conversation_id: str, request: Request):
122
+ result = await service_routes.get_conversation_paged_members(
123
+ FastApiRequestAdapter(request)
124
+ )
125
+ return JSONResponse(content=result)
126
+
127
+ @router.delete(base_url + "/v3/conversations/{conversation_id}/members/{member_id}")
128
+ async def delete_conversation_member(
129
+ conversation_id: str, member_id: str, request: Request
130
+ ):
131
+ result = await service_routes.delete_conversation_member(
132
+ FastApiRequestAdapter(request)
133
+ )
134
+ return JSONResponse(content=result)
135
+
136
+ @router.post(base_url + "/v3/conversations/{conversation_id}/activities/history")
137
+ async def send_conversation_history(conversation_id: str, request: Request):
138
+ result = await service_routes.send_conversation_history(
139
+ FastApiRequestAdapter(request)
140
+ )
141
+ return JSONResponse(content=result)
142
+
143
+ @router.post(base_url + "/v3/conversations/{conversation_id}/attachments")
144
+ async def upload_attachment(conversation_id: str, request: Request):
145
+ result = await service_routes.upload_attachment(FastApiRequestAdapter(request))
146
+ return JSONResponse(content=result)
147
+
148
+ return router
@@ -0,0 +1,94 @@
1
+ # Copyright (c) Microsoft Corporation. All rights reserved.
2
+ # Licensed under the MIT License.
3
+ from typing import Optional
4
+
5
+ from fastapi import Request, Response
6
+ from fastapi.responses import JSONResponse
7
+
8
+ from microsoft_agents.hosting.core import Agent
9
+ from microsoft_agents.hosting.core.authorization import Connections
10
+ from microsoft_agents.hosting.core.http import (
11
+ HttpAdapterBase,
12
+ HttpResponse,
13
+ )
14
+ from microsoft_agents.hosting.core import ChannelServiceClientFactoryBase
15
+
16
+ from .agent_http_adapter import AgentHttpAdapter
17
+
18
+
19
+ class FastApiRequestAdapter:
20
+ """Adapter to make FastAPI Request compatible with HttpRequestProtocol."""
21
+
22
+ def __init__(self, request: Request):
23
+ self._request = request
24
+
25
+ @property
26
+ def method(self) -> str:
27
+ return self._request.method
28
+
29
+ @property
30
+ def headers(self):
31
+ return self._request.headers
32
+
33
+ async def json(self):
34
+ return await self._request.json()
35
+
36
+ def get_claims_identity(self):
37
+ return getattr(self._request.state, "claims_identity", None)
38
+
39
+ def get_path_param(self, name: str) -> str:
40
+ return self._request.path_params.get(name, "")
41
+
42
+
43
+ class CloudAdapter(HttpAdapterBase, AgentHttpAdapter):
44
+ """CloudAdapter for FastAPI web framework."""
45
+
46
+ def __init__(
47
+ self,
48
+ *,
49
+ connection_manager: Connections = None,
50
+ channel_service_client_factory: ChannelServiceClientFactoryBase = None,
51
+ ):
52
+ """
53
+ Initializes a new instance of the CloudAdapter class.
54
+
55
+ :param connection_manager: Optional connection manager for OAuth.
56
+ :param channel_service_client_factory: The factory to use to create the channel service client.
57
+ """
58
+ super().__init__(
59
+ connection_manager=connection_manager,
60
+ channel_service_client_factory=channel_service_client_factory,
61
+ )
62
+
63
+ async def process(self, request: Request, agent: Agent) -> Optional[Response]:
64
+ """Process a FastAPI request.
65
+
66
+ Args:
67
+ request: The FastAPI request.
68
+ agent: The agent to handle the request.
69
+
70
+ Returns:
71
+ FastAPI Response object.
72
+ """
73
+ # Adapt request to protocol
74
+ adapted_request = FastApiRequestAdapter(request)
75
+
76
+ # Process using base implementation
77
+ http_response: HttpResponse = await self.process_request(adapted_request, agent)
78
+
79
+ # Convert HttpResponse to FastAPI Response
80
+ return self._to_fastapi_response(http_response)
81
+
82
+ @staticmethod
83
+ def _to_fastapi_response(http_response: HttpResponse) -> Response:
84
+ """Convert HttpResponse to FastAPI Response."""
85
+ if http_response.body is not None:
86
+ return JSONResponse(
87
+ content=http_response.body,
88
+ status_code=http_response.status_code,
89
+ headers=http_response.headers,
90
+ )
91
+ return Response(
92
+ status_code=http_response.status_code,
93
+ headers=http_response.headers,
94
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: microsoft-agents-hosting-fastapi
3
- Version: 0.7.0.dev0
3
+ Version: 0.7.0.dev4
4
4
  Summary: Integration library for Microsoft Agents with FastAPI
5
5
  Author: Microsoft Corporation
6
6
  License-Expression: MIT
@@ -10,7 +10,7 @@ Classifier: Operating System :: OS Independent
10
10
  Requires-Python: >=3.10
11
11
  Description-Content-Type: text/markdown
12
12
  License-File: LICENSE
13
- Requires-Dist: microsoft-agents-hosting-core==0.7.0.dev0
13
+ Requires-Dist: microsoft-agents-hosting-core==0.7.0.dev4
14
14
  Requires-Dist: fastapi>=0.104.0
15
15
  Dynamic: license-file
16
16
  Dynamic: requires-dist
@@ -0,0 +1,2 @@
1
+ microsoft-agents-hosting-core==0.7.0.dev4
2
+ fastapi>=0.104.0
@@ -0,0 +1,18 @@
1
+ from os import environ, path
2
+ from setuptools import setup
3
+
4
+ # Try to read from VERSION.txt file first, fall back to environment variable
5
+ version_file = path.join(path.dirname(__file__), "VERSION.txt")
6
+ if path.exists(version_file):
7
+ with open(version_file, "r", encoding="utf-8") as f:
8
+ package_version = f.read().strip()
9
+ else:
10
+ package_version = environ.get("PackageVersion", "0.0.0")
11
+
12
+ setup(
13
+ version=package_version,
14
+ install_requires=[
15
+ f"microsoft-agents-hosting-core=={package_version}",
16
+ "fastapi>=0.104.0",
17
+ ],
18
+ )
@@ -1,205 +0,0 @@
1
- # Copyright (c) Microsoft Corporation. All rights reserved.
2
- # Licensed under the MIT License.
3
- import json
4
- from typing import List, Union, Type
5
-
6
- from fastapi import APIRouter, Request, Response, HTTPException, Depends
7
- from fastapi.responses import JSONResponse
8
-
9
- from microsoft_agents.activity import (
10
- AgentsModel,
11
- Activity,
12
- AttachmentData,
13
- ConversationParameters,
14
- Transcript,
15
- )
16
- from microsoft_agents.hosting.core import ChannelApiHandlerProtocol
17
-
18
-
19
- async def deserialize_from_body(
20
- request: Request, target_model: Type[AgentsModel]
21
- ) -> AgentsModel:
22
- content_type = request.headers.get("Content-Type", "")
23
- if "application/json" in content_type:
24
- body = await request.json()
25
- else:
26
- raise HTTPException(status_code=415, detail="Unsupported Media Type")
27
-
28
- return target_model.model_validate(body)
29
-
30
-
31
- def get_serialized_response(
32
- model_or_list: Union[AgentsModel, List[AgentsModel]],
33
- ) -> JSONResponse:
34
- if isinstance(model_or_list, AgentsModel):
35
- json_obj = model_or_list.model_dump(
36
- mode="json", exclude_unset=True, by_alias=True
37
- )
38
- else:
39
- json_obj = [
40
- model.model_dump(mode="json", exclude_unset=True, by_alias=True)
41
- for model in model_or_list
42
- ]
43
-
44
- return JSONResponse(content=json_obj)
45
-
46
-
47
- def channel_service_route_table(
48
- handler: ChannelApiHandlerProtocol, base_url: str = ""
49
- ) -> APIRouter:
50
- router = APIRouter()
51
-
52
- @router.post(base_url + "/v3/conversations/{conversation_id}/activities")
53
- async def send_to_conversation(conversation_id: str, request: Request):
54
- activity = await deserialize_from_body(request, Activity)
55
- result = await handler.on_send_to_conversation(
56
- getattr(request.state, "claims_identity", None),
57
- conversation_id,
58
- activity,
59
- )
60
-
61
- return get_serialized_response(result)
62
-
63
- @router.post(
64
- base_url + "/v3/conversations/{conversation_id}/activities/{activity_id}"
65
- )
66
- async def reply_to_activity(
67
- conversation_id: str, activity_id: str, request: Request
68
- ):
69
- activity = await deserialize_from_body(request, Activity)
70
- result = await handler.on_reply_to_activity(
71
- getattr(request.state, "claims_identity", None),
72
- conversation_id,
73
- activity_id,
74
- activity,
75
- )
76
-
77
- return get_serialized_response(result)
78
-
79
- @router.put(
80
- base_url + "/v3/conversations/{conversation_id}/activities/{activity_id}"
81
- )
82
- async def update_activity(conversation_id: str, activity_id: str, request: Request):
83
- activity = await deserialize_from_body(request, Activity)
84
- result = await handler.on_update_activity(
85
- getattr(request.state, "claims_identity", None),
86
- conversation_id,
87
- activity_id,
88
- activity,
89
- )
90
-
91
- return get_serialized_response(result)
92
-
93
- @router.delete(
94
- base_url + "/v3/conversations/{conversation_id}/activities/{activity_id}"
95
- )
96
- async def delete_activity(conversation_id: str, activity_id: str, request: Request):
97
- await handler.on_delete_activity(
98
- getattr(request.state, "claims_identity", None),
99
- conversation_id,
100
- activity_id,
101
- )
102
-
103
- return Response(status_code=200)
104
-
105
- @router.get(
106
- base_url
107
- + "/v3/conversations/{conversation_id}/activities/{activity_id}/members"
108
- )
109
- async def get_activity_members(
110
- conversation_id: str, activity_id: str, request: Request
111
- ):
112
- result = await handler.on_get_activity_members(
113
- getattr(request.state, "claims_identity", None),
114
- conversation_id,
115
- activity_id,
116
- )
117
-
118
- return get_serialized_response(result)
119
-
120
- @router.post(base_url + "/")
121
- async def create_conversation(request: Request):
122
- conversation_parameters = await deserialize_from_body(
123
- request, ConversationParameters
124
- )
125
- result = await handler.on_create_conversation(
126
- getattr(request.state, "claims_identity", None), conversation_parameters
127
- )
128
-
129
- return get_serialized_response(result)
130
-
131
- @router.get(base_url + "/")
132
- async def get_conversation(request: Request):
133
- # TODO: continuation token? conversation_id?
134
- result = await handler.on_get_conversations(
135
- getattr(request.state, "claims_identity", None), None
136
- )
137
-
138
- return get_serialized_response(result)
139
-
140
- @router.get(base_url + "/v3/conversations/{conversation_id}/members")
141
- async def get_conversation_members(conversation_id: str, request: Request):
142
- result = await handler.on_get_conversation_members(
143
- getattr(request.state, "claims_identity", None),
144
- conversation_id,
145
- )
146
-
147
- return get_serialized_response(result)
148
-
149
- @router.get(base_url + "/v3/conversations/{conversation_id}/members/{member_id}")
150
- async def get_conversation_member(
151
- conversation_id: str, member_id: str, request: Request
152
- ):
153
- result = await handler.on_get_conversation_member(
154
- getattr(request.state, "claims_identity", None),
155
- member_id,
156
- conversation_id,
157
- )
158
-
159
- return get_serialized_response(result)
160
-
161
- @router.get(base_url + "/v3/conversations/{conversation_id}/pagedmembers")
162
- async def get_conversation_paged_members(conversation_id: str, request: Request):
163
- # TODO: continuation token? page size?
164
- result = await handler.on_get_conversation_paged_members(
165
- getattr(request.state, "claims_identity", None),
166
- conversation_id,
167
- )
168
-
169
- return get_serialized_response(result)
170
-
171
- @router.delete(base_url + "/v3/conversations/{conversation_id}/members/{member_id}")
172
- async def delete_conversation_member(
173
- conversation_id: str, member_id: str, request: Request
174
- ):
175
- result = await handler.on_delete_conversation_member(
176
- getattr(request.state, "claims_identity", None),
177
- conversation_id,
178
- member_id,
179
- )
180
-
181
- return get_serialized_response(result)
182
-
183
- @router.post(base_url + "/v3/conversations/{conversation_id}/activities/history")
184
- async def send_conversation_history(conversation_id: str, request: Request):
185
- transcript = await deserialize_from_body(request, Transcript)
186
- result = await handler.on_send_conversation_history(
187
- getattr(request.state, "claims_identity", None),
188
- conversation_id,
189
- transcript,
190
- )
191
-
192
- return get_serialized_response(result)
193
-
194
- @router.post(base_url + "/v3/conversations/{conversation_id}/attachments")
195
- async def upload_attachment(conversation_id: str, request: Request):
196
- attachment_data = await deserialize_from_body(request, AttachmentData)
197
- result = await handler.on_upload_attachment(
198
- getattr(request.state, "claims_identity", None),
199
- conversation_id,
200
- attachment_data,
201
- )
202
-
203
- return get_serialized_response(result)
204
-
205
- return router
@@ -1,113 +0,0 @@
1
- # Copyright (c) Microsoft Corporation. All rights reserved.
2
- # Licensed under the MIT License.
3
- from traceback import format_exc
4
- from typing import Optional
5
-
6
- from fastapi import Request, Response, HTTPException
7
- from fastapi.responses import JSONResponse
8
- from microsoft_agents.hosting.core import error_resources
9
- from microsoft_agents.hosting.core.authorization import (
10
- ClaimsIdentity,
11
- Connections,
12
- )
13
- from microsoft_agents.activity import (
14
- Activity,
15
- DeliveryModes,
16
- )
17
- from microsoft_agents.hosting.core import (
18
- Agent,
19
- ChannelServiceAdapter,
20
- ChannelServiceClientFactoryBase,
21
- MessageFactory,
22
- RestChannelServiceClientFactory,
23
- TurnContext,
24
- )
25
-
26
- from .agent_http_adapter import AgentHttpAdapter
27
-
28
-
29
- class CloudAdapter(ChannelServiceAdapter, AgentHttpAdapter):
30
- def __init__(
31
- self,
32
- *,
33
- connection_manager: Connections = None,
34
- channel_service_client_factory: ChannelServiceClientFactoryBase = None,
35
- ):
36
- """
37
- Initializes a new instance of the CloudAdapter class.
38
-
39
- :param channel_service_client_factory: The factory to use to create the channel service client.
40
- """
41
-
42
- async def on_turn_error(context: TurnContext, error: Exception):
43
- error_message = f"Exception caught : {error}"
44
- print(format_exc())
45
-
46
- await context.send_activity(MessageFactory.text(error_message))
47
-
48
- # Send a trace activity
49
- await context.send_trace_activity(
50
- "OnTurnError Trace",
51
- error_message,
52
- "https://www.botframework.com/schemas/error",
53
- "TurnError",
54
- )
55
-
56
- self.on_turn_error = on_turn_error
57
-
58
- channel_service_client_factory = (
59
- channel_service_client_factory
60
- or RestChannelServiceClientFactory(connection_manager)
61
- )
62
-
63
- super().__init__(channel_service_client_factory)
64
-
65
- async def process(self, request: Request, agent: Agent) -> Optional[Response]:
66
- if not request:
67
- raise TypeError(str(error_resources.RequestRequired))
68
- if not agent:
69
- raise TypeError(str(error_resources.AgentRequired))
70
-
71
- if request.method == "POST":
72
- # Deserialize the incoming Activity
73
- content_type = request.headers.get("Content-Type", "")
74
- if "application/json" in content_type:
75
- body = await request.json()
76
- else:
77
- raise HTTPException(status_code=415, detail="Unsupported Media Type")
78
-
79
- activity: Activity = Activity.model_validate(body)
80
-
81
- # default to anonymous identity with no claims
82
- claims_identity: ClaimsIdentity = getattr(
83
- request.state, "claims_identity", ClaimsIdentity({}, False)
84
- )
85
-
86
- # A POST request must contain an Activity
87
- if (
88
- not activity.type
89
- or not activity.conversation
90
- or not activity.conversation.id
91
- ):
92
- raise HTTPException(status_code=400, detail="Bad Request")
93
-
94
- try:
95
- # Process the inbound activity with the agent
96
- invoke_response = await self.process_activity(
97
- claims_identity, activity, agent.on_turn
98
- )
99
-
100
- if (
101
- activity.type == "invoke"
102
- or activity.delivery_mode == DeliveryModes.expect_replies
103
- ):
104
- # Invoke and ExpectReplies cannot be performed async, the response must be written before the calling thread is released.
105
- return JSONResponse(
106
- content=invoke_response.body, status_code=invoke_response.status
107
- )
108
-
109
- return Response(status_code=202)
110
- except PermissionError:
111
- raise HTTPException(status_code=401, detail="Unauthorized")
112
- else:
113
- raise HTTPException(status_code=405, detail="Method Not Allowed")
@@ -1,2 +0,0 @@
1
- microsoft-agents-hosting-core==0.7.0.dev0
2
- fastapi>=0.104.0
@@ -1,12 +0,0 @@
1
- from os import environ
2
- from setuptools import setup
3
-
4
- package_version = environ.get("PackageVersion", "0.0.0")
5
-
6
- setup(
7
- version=package_version,
8
- install_requires=[
9
- f"microsoft-agents-hosting-core=={package_version}",
10
- "fastapi>=0.104.0",
11
- ],
12
- )