autowing 0.1.0__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.
- autowing-0.1.0/LICENSE +201 -0
- autowing-0.1.0/PKG-INFO +37 -0
- autowing-0.1.0/README.md +20 -0
- autowing-0.1.0/autowing/__init__.py +0 -0
- autowing-0.1.0/autowing/core/__init__.py +0 -0
- autowing-0.1.0/autowing/core/ai_context.py +46 -0
- autowing-0.1.0/autowing/core/llm/__init__.py +0 -0
- autowing-0.1.0/autowing/core/llm/base.py +53 -0
- autowing-0.1.0/autowing/core/llm/deepseek_client.py +151 -0
- autowing-0.1.0/autowing/core/llm/factory.py +48 -0
- autowing-0.1.0/autowing/core/llm/openai_client.py +85 -0
- autowing-0.1.0/autowing/core/llm/qwen_client.py +152 -0
- autowing-0.1.0/autowing/playwright/fixture.py +248 -0
- autowing-0.1.0/autowing/selenium/fixture.py +262 -0
- autowing-0.1.0/pyproject.toml +18 -0
autowing-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
autowing-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: autowing
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: auto-wing is a tool that uses LLM to assist automated testing.
|
|
5
|
+
Author: defnngj
|
|
6
|
+
Author-email: defnngj@gmail.com
|
|
7
|
+
Requires-Python: >=3.12,<4.0
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
10
|
+
Requires-Dist: dashscope (>=1.22.1,<2.0.0)
|
|
11
|
+
Requires-Dist: openai (>=1.60.1,<2.0.0)
|
|
12
|
+
Requires-Dist: pytest-playwright (>=0.6.2,<0.7.0)
|
|
13
|
+
Requires-Dist: python-dotenv (>=1.0.1,<2.0.0)
|
|
14
|
+
Requires-Dist: selenium (>=4.28.1,<5.0.0)
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# auto-wing
|
|
18
|
+
|
|
19
|
+

|
|
20
|
+
|
|
21
|
+
> auto-wing is a tool that uses LLM to assist automated testing, give your automated testing wings.
|
|
22
|
+
|
|
23
|
+
auto-wing是一个利用LLM辅助自动化测试的工具, 为你的自动化测试插上翅膀。
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
### Features
|
|
27
|
+
|
|
28
|
+
⭐ 支持多种操作:`ai_action`、`ai_query`、`ai_assert`等。
|
|
29
|
+
|
|
30
|
+
⭐ 支持多模型:`openai`、`qwen` 和 `deepseek`。
|
|
31
|
+
|
|
32
|
+
⭐ 支持 `playwright`、`selenium`等。
|
|
33
|
+
|
|
34
|
+
⭐ 方便的和现有自动化项目集成。
|
|
35
|
+
|
|
36
|
+
### 安装
|
|
37
|
+
|
autowing-0.1.0/README.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# auto-wing
|
|
2
|
+
|
|
3
|
+

|
|
4
|
+
|
|
5
|
+
> auto-wing is a tool that uses LLM to assist automated testing, give your automated testing wings.
|
|
6
|
+
|
|
7
|
+
auto-wing是一个利用LLM辅助自动化测试的工具, 为你的自动化测试插上翅膀。
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
### Features
|
|
11
|
+
|
|
12
|
+
⭐ 支持多种操作:`ai_action`、`ai_query`、`ai_assert`等。
|
|
13
|
+
|
|
14
|
+
⭐ 支持多模型:`openai`、`qwen` 和 `deepseek`。
|
|
15
|
+
|
|
16
|
+
⭐ 支持 `playwright`、`selenium`等。
|
|
17
|
+
|
|
18
|
+
⭐ 方便的和现有自动化项目集成。
|
|
19
|
+
|
|
20
|
+
### 安装
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from typing import Any, Dict, Optional
|
|
2
|
+
import json
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class AiContext:
|
|
6
|
+
"""
|
|
7
|
+
A class for managing AI context data.
|
|
8
|
+
Provides storage and retrieval of context information used in AI operations.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
def __init__(self):
|
|
12
|
+
"""
|
|
13
|
+
Initialize an empty context storage.
|
|
14
|
+
"""
|
|
15
|
+
self._context: Dict[str, Any] = {}
|
|
16
|
+
|
|
17
|
+
def set_context(self, key: str, value: Any) -> None:
|
|
18
|
+
"""
|
|
19
|
+
Store a value in the context.
|
|
20
|
+
|
|
21
|
+
Args:
|
|
22
|
+
key (str): The key under which to store the value
|
|
23
|
+
value (Any): The value to store
|
|
24
|
+
"""
|
|
25
|
+
self._context[key] = value
|
|
26
|
+
|
|
27
|
+
def get_context(self, key: str) -> Optional[Any]:
|
|
28
|
+
"""
|
|
29
|
+
Retrieve a value from the context.
|
|
30
|
+
|
|
31
|
+
Args:
|
|
32
|
+
key (str): The key of the value to retrieve
|
|
33
|
+
|
|
34
|
+
Returns:
|
|
35
|
+
Optional[Any]: The stored value, or None if the key doesn't exist
|
|
36
|
+
"""
|
|
37
|
+
return self._context.get(key)
|
|
38
|
+
|
|
39
|
+
def to_json(self) -> str:
|
|
40
|
+
"""
|
|
41
|
+
Convert the context to a JSON string.
|
|
42
|
+
|
|
43
|
+
Returns:
|
|
44
|
+
str: JSON string representation of the context
|
|
45
|
+
"""
|
|
46
|
+
return json.dumps(self._context)
|
|
File without changes
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
from abc import ABC, abstractmethod
|
|
2
|
+
from typing import Dict, Any, Optional
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class BaseLLMClient(ABC):
|
|
6
|
+
"""
|
|
7
|
+
Abstract base class for Language Model clients.
|
|
8
|
+
Defines the interface that all LLM clients must implement.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
@abstractmethod
|
|
12
|
+
def complete(self, prompt: str, context: Optional[Dict[str, Any]] = None) -> str:
|
|
13
|
+
"""
|
|
14
|
+
Generate a completion for the given prompt with optional context.
|
|
15
|
+
|
|
16
|
+
Args:
|
|
17
|
+
prompt (str): The input text to generate completion for
|
|
18
|
+
context (Optional[Dict[str, Any]]): Additional context information for the completion
|
|
19
|
+
|
|
20
|
+
Returns:
|
|
21
|
+
str: The generated completion text
|
|
22
|
+
|
|
23
|
+
Raises:
|
|
24
|
+
NotImplementedError: If the subclass doesn't implement this method
|
|
25
|
+
"""
|
|
26
|
+
pass
|
|
27
|
+
|
|
28
|
+
@abstractmethod
|
|
29
|
+
def complete_with_vision(self, prompt: Dict[str, Any]) -> str:
|
|
30
|
+
"""
|
|
31
|
+
Generate a completion for vision-based tasks.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
prompt (Dict[str, Any]): A dictionary containing the prompt and image data
|
|
35
|
+
in the format required by the specific model
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
str: The generated completion text
|
|
39
|
+
|
|
40
|
+
Raises:
|
|
41
|
+
NotImplementedError: If the subclass doesn't implement this method
|
|
42
|
+
"""
|
|
43
|
+
pass
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def get_model_name(cls) -> str:
|
|
47
|
+
"""
|
|
48
|
+
Get the standardized name of the model.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
str: The model name in lowercase, with 'client' suffix removed
|
|
52
|
+
"""
|
|
53
|
+
return cls.__name__.lower().replace('client', '')
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Optional, Dict, Any, List
|
|
3
|
+
import json
|
|
4
|
+
from openai import OpenAI
|
|
5
|
+
from autowing.core.llm.base import BaseLLMClient
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class DeepSeekClient(BaseLLMClient):
|
|
9
|
+
"""
|
|
10
|
+
A client for interacting with the DeepSeek AI model.
|
|
11
|
+
Implements the BaseLLMClient interface for text completion and vision tasks.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self, api_key: Optional[str] = None):
|
|
15
|
+
"""
|
|
16
|
+
Initialize the DeepSeek client.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
api_key (Optional[str]): The API key for DeepSeek. If not provided,
|
|
20
|
+
will try to get from DEEPSEEK_API_KEY environment variable.
|
|
21
|
+
|
|
22
|
+
Raises:
|
|
23
|
+
ValueError: If no API key is provided or found in environment variables.
|
|
24
|
+
"""
|
|
25
|
+
self.api_key = api_key or os.getenv("DEEPSEEK_API_KEY")
|
|
26
|
+
if not self.api_key:
|
|
27
|
+
raise ValueError("DeepSeek API key is required")
|
|
28
|
+
|
|
29
|
+
self.base_url = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com")
|
|
30
|
+
self.model_name = os.getenv("DEEPSEEK_MODEL_NAME", "deepseek-chat")
|
|
31
|
+
|
|
32
|
+
self.client = OpenAI(
|
|
33
|
+
api_key=self.api_key,
|
|
34
|
+
base_url=self.base_url
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
def _truncate_text(self, text: str, max_length: int = 30000) -> str:
|
|
38
|
+
"""
|
|
39
|
+
Truncate text to fit within model's length limits.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
text (str): The input text to truncate
|
|
43
|
+
max_length (int): Maximum allowed length for the text. Defaults to 30000.
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
str: Truncated text with ellipsis if needed
|
|
47
|
+
"""
|
|
48
|
+
if len(text) > max_length:
|
|
49
|
+
return text[:max_length] + "..."
|
|
50
|
+
return text
|
|
51
|
+
|
|
52
|
+
def _format_messages(self, prompt: str, context: Optional[Dict[str, Any]] = None) -> List[Dict[str, str]]:
|
|
53
|
+
"""
|
|
54
|
+
Format messages for the DeepSeek API.
|
|
55
|
+
|
|
56
|
+
Args:
|
|
57
|
+
prompt (str): The main prompt text
|
|
58
|
+
context (Optional[Dict[str, Any]]): Additional context information
|
|
59
|
+
|
|
60
|
+
Returns:
|
|
61
|
+
List[Dict[str, str]]: Formatted messages list ready for API submission
|
|
62
|
+
"""
|
|
63
|
+
# Add system message
|
|
64
|
+
messages = [{
|
|
65
|
+
"role": "system",
|
|
66
|
+
"content": (
|
|
67
|
+
"You are a web automation assistant. "
|
|
68
|
+
"Analyze the page structure and provide precise element locators. "
|
|
69
|
+
"Return responses in the requested format."
|
|
70
|
+
)
|
|
71
|
+
}]
|
|
72
|
+
|
|
73
|
+
# Add context (if any)
|
|
74
|
+
if context:
|
|
75
|
+
context_str = json.dumps(context, ensure_ascii=False)
|
|
76
|
+
messages.append({
|
|
77
|
+
"role": "user",
|
|
78
|
+
"content": f"Page context: {self._truncate_text(context_str)}"
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
# Add main prompt
|
|
82
|
+
messages.append({
|
|
83
|
+
"role": "user",
|
|
84
|
+
"content": self._truncate_text(prompt)
|
|
85
|
+
})
|
|
86
|
+
|
|
87
|
+
return messages
|
|
88
|
+
|
|
89
|
+
def complete(self, prompt: str, context: Optional[Dict[str, Any]] = None) -> str:
|
|
90
|
+
"""
|
|
91
|
+
Send a completion request to the DeepSeek API.
|
|
92
|
+
|
|
93
|
+
Args:
|
|
94
|
+
prompt (str): The text prompt to complete
|
|
95
|
+
context (Optional[Dict[str, Any]]): Additional context for the completion
|
|
96
|
+
|
|
97
|
+
Returns:
|
|
98
|
+
str: The model's response text
|
|
99
|
+
|
|
100
|
+
Raises:
|
|
101
|
+
Exception: If there's an error communicating with the DeepSeek API
|
|
102
|
+
"""
|
|
103
|
+
try:
|
|
104
|
+
messages = self._format_messages(prompt, context)
|
|
105
|
+
|
|
106
|
+
response = self.client.chat.completions.create(
|
|
107
|
+
model=self.model_name,
|
|
108
|
+
messages=messages,
|
|
109
|
+
temperature=0.7,
|
|
110
|
+
max_tokens=2000
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
return response.choices[0].message.content
|
|
114
|
+
except Exception as e:
|
|
115
|
+
raise Exception(f"DeepSeek API error: {str(e)}")
|
|
116
|
+
|
|
117
|
+
def complete_with_vision(self, prompt: Dict[str, Any]) -> str:
|
|
118
|
+
"""
|
|
119
|
+
Send a vision-based completion request to the DeepSeek API.
|
|
120
|
+
|
|
121
|
+
Args:
|
|
122
|
+
prompt (Dict[str, Any]): A dictionary containing messages and image data
|
|
123
|
+
in the format expected by the API
|
|
124
|
+
|
|
125
|
+
Returns:
|
|
126
|
+
str: The model's response text
|
|
127
|
+
|
|
128
|
+
Raises:
|
|
129
|
+
Exception: If there's an error communicating with the DeepSeek API
|
|
130
|
+
"""
|
|
131
|
+
try:
|
|
132
|
+
# Make sure the message length is within the limit
|
|
133
|
+
messages = prompt["messages"]
|
|
134
|
+
for msg in messages:
|
|
135
|
+
if isinstance(msg.get("content"), str):
|
|
136
|
+
msg["content"] = self._truncate_text(msg["content"])
|
|
137
|
+
elif isinstance(msg.get("content"), list):
|
|
138
|
+
for item in msg["content"]:
|
|
139
|
+
if isinstance(item.get("text"), str):
|
|
140
|
+
item["text"] = self._truncate_text(item["text"])
|
|
141
|
+
|
|
142
|
+
response = self.client.chat.completions.create(
|
|
143
|
+
model=self.model_name,
|
|
144
|
+
messages=messages,
|
|
145
|
+
temperature=0.7,
|
|
146
|
+
max_tokens=2000
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
return response.choices[0].message.content
|
|
150
|
+
except Exception as e:
|
|
151
|
+
raise Exception(f"DeepSeek API error: {str(e)}")
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Type
|
|
3
|
+
from autowing.core.llm.base import BaseLLMClient
|
|
4
|
+
from autowing.core.llm.openai_client import OpenAIClient
|
|
5
|
+
from autowing.core.llm.qwen_client import QwenClient
|
|
6
|
+
from autowing.core.llm.deepseek_client import DeepSeekClient
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class LLMFactory:
|
|
10
|
+
"""
|
|
11
|
+
Factory class for creating Language Model clients.
|
|
12
|
+
Provides centralized management of different LLM implementations.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
_models = {
|
|
16
|
+
'openai': OpenAIClient,
|
|
17
|
+
'qwen': QwenClient,
|
|
18
|
+
'deepseek': DeepSeekClient
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
def create(cls) -> BaseLLMClient:
|
|
23
|
+
"""
|
|
24
|
+
Create an instance of the configured LLM client.
|
|
25
|
+
|
|
26
|
+
Returns:
|
|
27
|
+
BaseLLMClient: An instance of the specified LLM client
|
|
28
|
+
|
|
29
|
+
Raises:
|
|
30
|
+
ValueError: If the specified model provider is not supported
|
|
31
|
+
"""
|
|
32
|
+
model_name = os.getenv("AUTOWING_MODEL_PROVIDER", "deepseek").lower()
|
|
33
|
+
if model_name not in cls._models:
|
|
34
|
+
raise ValueError(f"Unsupported model provider: {model_name}")
|
|
35
|
+
|
|
36
|
+
model_class = cls._models[model_name]
|
|
37
|
+
return model_class()
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def register_model(cls, name: str, model_class: Type[BaseLLMClient]) -> None:
|
|
41
|
+
"""
|
|
42
|
+
Register a new LLM client implementation.
|
|
43
|
+
|
|
44
|
+
Args:
|
|
45
|
+
name (str): The name to register the model under
|
|
46
|
+
model_class (Type[BaseLLMClient]): The class implementing the BaseLLMClient interface
|
|
47
|
+
"""
|
|
48
|
+
cls._models[name.lower()] = model_class
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from typing import Optional, Dict, Any
|
|
3
|
+
from openai import OpenAI
|
|
4
|
+
from autowing.core.llm.base import BaseLLMClient
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class OpenAIClient(BaseLLMClient):
|
|
8
|
+
"""
|
|
9
|
+
OpenAI API client implementation.
|
|
10
|
+
Provides access to OpenAI's GPT and vision models.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None):
|
|
14
|
+
"""
|
|
15
|
+
Initialize the OpenAI client.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
api_key (Optional[str]): OpenAI API key. If not provided, will try to get from OPENAI_API_KEY env var
|
|
19
|
+
base_url (Optional[str]): Custom base URL for API requests
|
|
20
|
+
|
|
21
|
+
Raises:
|
|
22
|
+
ValueError: If no API key is provided or found in environment variables
|
|
23
|
+
"""
|
|
24
|
+
self.api_key = api_key or os.getenv("OPENAI_API_KEY")
|
|
25
|
+
if not self.api_key:
|
|
26
|
+
raise ValueError("OpenAI API key is required")
|
|
27
|
+
|
|
28
|
+
self.base_url = base_url or os.getenv("OPENAI_BASE_URL")
|
|
29
|
+
self.model_name = os.getenv("MIDSCENE_MODEL_NAME", "gpt-4-vision-preview")
|
|
30
|
+
|
|
31
|
+
client_kwargs = {"api_key": self.api_key}
|
|
32
|
+
if self.base_url:
|
|
33
|
+
client_kwargs["base_url"] = self.base_url
|
|
34
|
+
|
|
35
|
+
self.client = OpenAI(**client_kwargs)
|
|
36
|
+
|
|
37
|
+
def complete(self, prompt: str, context: Optional[Dict[str, Any]] = None) -> str:
|
|
38
|
+
"""
|
|
39
|
+
Generate a completion using GPT-4.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
prompt (str): The text prompt to complete
|
|
43
|
+
context (Optional[Dict[str, Any]]): Additional context for the completion
|
|
44
|
+
|
|
45
|
+
Returns:
|
|
46
|
+
str: The model's response text
|
|
47
|
+
|
|
48
|
+
Raises:
|
|
49
|
+
Exception: If there's an error communicating with the OpenAI API
|
|
50
|
+
"""
|
|
51
|
+
try:
|
|
52
|
+
response = self.client.chat.completions.create(
|
|
53
|
+
model="gpt-4",
|
|
54
|
+
messages=[
|
|
55
|
+
{"role": "system", "content": "You are a helpful AI assistant for web automation."},
|
|
56
|
+
{"role": "user", "content": prompt}
|
|
57
|
+
]
|
|
58
|
+
)
|
|
59
|
+
return response.choices[0].message.content
|
|
60
|
+
except Exception as e:
|
|
61
|
+
raise Exception(f"OpenAI API error: {str(e)}")
|
|
62
|
+
|
|
63
|
+
def complete_with_vision(self, prompt: Dict[str, Any]) -> str:
|
|
64
|
+
"""
|
|
65
|
+
Generate a completion for vision tasks using GPT-4 Vision.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
prompt (Dict[str, Any]): A dictionary containing messages and image data
|
|
69
|
+
in the format required by the GPT-4 Vision API
|
|
70
|
+
|
|
71
|
+
Returns:
|
|
72
|
+
str: The model's response text
|
|
73
|
+
|
|
74
|
+
Raises:
|
|
75
|
+
Exception: If there's an error communicating with the OpenAI Vision API
|
|
76
|
+
"""
|
|
77
|
+
try:
|
|
78
|
+
response = self.client.chat.completions.create(
|
|
79
|
+
model=self.model_name,
|
|
80
|
+
messages=prompt["messages"],
|
|
81
|
+
max_tokens=1000
|
|
82
|
+
)
|
|
83
|
+
return response.choices[0].message.content
|
|
84
|
+
except Exception as e:
|
|
85
|
+
raise Exception(f"OpenAI Vision API error: {str(e)}")
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import json
|
|
3
|
+
from typing import Optional, Dict, Any, List
|
|
4
|
+
from openai import OpenAI
|
|
5
|
+
from autowing.core.llm.base import BaseLLMClient
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class QwenClient(BaseLLMClient):
|
|
9
|
+
"""
|
|
10
|
+
Qwen (DashScope) API client implementation.
|
|
11
|
+
Provides access to Alibaba Cloud's Qwen language model through OpenAI-compatible interface.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
def __init__(self, api_key: Optional[str] = None):
|
|
15
|
+
"""
|
|
16
|
+
Initialize the Qwen client.
|
|
17
|
+
|
|
18
|
+
Args:
|
|
19
|
+
api_key (Optional[str]): DashScope API key. If not provided, will try to get from DASHSCOPE_API_KEY env var
|
|
20
|
+
|
|
21
|
+
Raises:
|
|
22
|
+
ValueError: If no API key is provided or found in environment variables
|
|
23
|
+
"""
|
|
24
|
+
self.api_key = api_key or os.getenv("DASHSCOPE_API_KEY")
|
|
25
|
+
if not self.api_key:
|
|
26
|
+
raise ValueError("DashScope API key is required")
|
|
27
|
+
|
|
28
|
+
# 使用兼容模式的 URL
|
|
29
|
+
self.base_url = os.getenv("OPENAI_BASE_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1")
|
|
30
|
+
self.model_name = os.getenv("MIDSCENE_MODEL_NAME", "qwen-vl-max-latest")
|
|
31
|
+
|
|
32
|
+
# 使用 OpenAI 客户端,但配置为千问的 URL
|
|
33
|
+
self.client = OpenAI(
|
|
34
|
+
api_key=self.api_key,
|
|
35
|
+
base_url=self.base_url
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
def _truncate_text(self, text: str, max_length: int = 30000) -> str:
|
|
39
|
+
"""
|
|
40
|
+
Truncate text to fit within model's length limits.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
text (str): The input text to truncate
|
|
44
|
+
max_length (int): Maximum allowed length for the text. Defaults to 30000
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
str: Truncated text with ellipsis if needed
|
|
48
|
+
"""
|
|
49
|
+
if len(text) > max_length:
|
|
50
|
+
return text[:max_length] + "..."
|
|
51
|
+
return text
|
|
52
|
+
|
|
53
|
+
def _format_messages(self, prompt: str, context: Optional[Dict[str, Any]] = None) -> List[Dict[str, str]]:
|
|
54
|
+
"""
|
|
55
|
+
Format messages for the Qwen API.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
prompt (str): The main prompt text
|
|
59
|
+
context (Optional[Dict[str, Any]]): Additional context information
|
|
60
|
+
|
|
61
|
+
Returns:
|
|
62
|
+
List[Dict[str, str]]: Formatted messages list ready for API submission
|
|
63
|
+
"""
|
|
64
|
+
# Add system message
|
|
65
|
+
messages = [{
|
|
66
|
+
"role": "system",
|
|
67
|
+
"content": (
|
|
68
|
+
"You are a web automation assistant. "
|
|
69
|
+
"Analyze the page structure and provide precise element locators. "
|
|
70
|
+
"Return responses in the requested format."
|
|
71
|
+
)
|
|
72
|
+
}]
|
|
73
|
+
|
|
74
|
+
# Add context (if any)
|
|
75
|
+
if context:
|
|
76
|
+
context_str = json.dumps(context, ensure_ascii=False)
|
|
77
|
+
messages.append({
|
|
78
|
+
"role": "user",
|
|
79
|
+
"content": f"Page context: {self._truncate_text(context_str)}"
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
# Add main prompt
|
|
83
|
+
messages.append({
|
|
84
|
+
"role": "user",
|
|
85
|
+
"content": self._truncate_text(prompt)
|
|
86
|
+
})
|
|
87
|
+
|
|
88
|
+
return messages
|
|
89
|
+
|
|
90
|
+
def complete(self, prompt: str, context: Optional[Dict[str, Any]] = None) -> str:
|
|
91
|
+
"""
|
|
92
|
+
Generate a completion using Qwen model.
|
|
93
|
+
|
|
94
|
+
Args:
|
|
95
|
+
prompt (str): The text prompt to complete
|
|
96
|
+
context (Optional[Dict[str, Any]]): Additional context for the completion
|
|
97
|
+
|
|
98
|
+
Returns:
|
|
99
|
+
str: The model's response text
|
|
100
|
+
|
|
101
|
+
Raises:
|
|
102
|
+
Exception: If there's an error communicating with the Qwen API
|
|
103
|
+
"""
|
|
104
|
+
try:
|
|
105
|
+
messages = self._format_messages(prompt, context)
|
|
106
|
+
|
|
107
|
+
response = self.client.chat.completions.create(
|
|
108
|
+
model=self.model_name,
|
|
109
|
+
messages=messages,
|
|
110
|
+
temperature=0.7,
|
|
111
|
+
max_tokens=2000
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
return response.choices[0].message.content
|
|
115
|
+
except Exception as e:
|
|
116
|
+
raise Exception(f"Qwen API error: {str(e)}")
|
|
117
|
+
|
|
118
|
+
def complete_with_vision(self, prompt: Dict[str, Any]) -> str:
|
|
119
|
+
"""
|
|
120
|
+
Generate a completion for vision tasks using Qwen-VL model.
|
|
121
|
+
|
|
122
|
+
Args:
|
|
123
|
+
prompt (Dict[str, Any]): A dictionary containing messages and image data
|
|
124
|
+
in the format required by the Qwen-VL API
|
|
125
|
+
|
|
126
|
+
Returns:
|
|
127
|
+
str: The model's response text
|
|
128
|
+
|
|
129
|
+
Raises:
|
|
130
|
+
Exception: If there's an error communicating with the Qwen API
|
|
131
|
+
"""
|
|
132
|
+
try:
|
|
133
|
+
# Make sure the message length is within the limit
|
|
134
|
+
messages = prompt["messages"]
|
|
135
|
+
for msg in messages:
|
|
136
|
+
if isinstance(msg.get("content"), str):
|
|
137
|
+
msg["content"] = self._truncate_text(msg["content"])
|
|
138
|
+
elif isinstance(msg.get("content"), list):
|
|
139
|
+
for item in msg["content"]:
|
|
140
|
+
if isinstance(item.get("text"), str):
|
|
141
|
+
item["text"] = self._truncate_text(item["text"])
|
|
142
|
+
|
|
143
|
+
response = self.client.chat.completions.create(
|
|
144
|
+
model=self.model_name,
|
|
145
|
+
messages=messages,
|
|
146
|
+
temperature=0.7,
|
|
147
|
+
max_tokens=2000
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
return response.choices[0].message.content
|
|
151
|
+
except Exception as e:
|
|
152
|
+
raise Exception(f"Qwen API error: {str(e)}")
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
from typing import Any, Dict
|
|
2
|
+
import json
|
|
3
|
+
from playwright.sync_api import Page
|
|
4
|
+
from autowing.core.llm.factory import LLMFactory
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class PlaywrightAiFixture:
|
|
8
|
+
"""
|
|
9
|
+
A fixture class that combines Playwright with AI capabilities for web automation.
|
|
10
|
+
Provides AI-driven interaction with web pages using various LLM providers.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
def __init__(self, page: Page):
|
|
14
|
+
"""
|
|
15
|
+
Initialize the AI-powered Playwright fixture.
|
|
16
|
+
|
|
17
|
+
Args:
|
|
18
|
+
page (Page): The Playwright page object to automate
|
|
19
|
+
"""
|
|
20
|
+
self.page = page
|
|
21
|
+
self.llm_client = LLMFactory.create()
|
|
22
|
+
|
|
23
|
+
def _get_page_context(self) -> Dict[str, Any]:
|
|
24
|
+
"""
|
|
25
|
+
Extract context information from the current page.
|
|
26
|
+
Collects information about visible elements and page metadata.
|
|
27
|
+
|
|
28
|
+
Returns:
|
|
29
|
+
Dict[str, Any]: A dictionary containing page URL, title, and information about
|
|
30
|
+
visible interactive elements
|
|
31
|
+
"""
|
|
32
|
+
# 获取页面基本信息
|
|
33
|
+
basic_info = {
|
|
34
|
+
"url": self.page.url,
|
|
35
|
+
"title": self.page.title()
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
# 获取关键元素信息
|
|
39
|
+
elements_info = self.page.evaluate("""() => {
|
|
40
|
+
const getVisibleElements = () => {
|
|
41
|
+
const elements = [];
|
|
42
|
+
const selectors = [
|
|
43
|
+
'input', 'button', 'a', '[role="button"]',
|
|
44
|
+
'[role="link"]', '[role="searchbox"]', 'textarea'
|
|
45
|
+
];
|
|
46
|
+
|
|
47
|
+
for (const selector of selectors) {
|
|
48
|
+
document.querySelectorAll(selector).forEach(el => {
|
|
49
|
+
if (el.offsetWidth > 0 && el.offsetHeight > 0) {
|
|
50
|
+
elements.push({
|
|
51
|
+
tag: el.tagName.toLowerCase(),
|
|
52
|
+
type: el.getAttribute('type'),
|
|
53
|
+
placeholder: el.getAttribute('placeholder'),
|
|
54
|
+
value: el.value,
|
|
55
|
+
text: el.textContent?.trim(),
|
|
56
|
+
aria: el.getAttribute('aria-label'),
|
|
57
|
+
id: el.id,
|
|
58
|
+
name: el.getAttribute('name'),
|
|
59
|
+
class: el.className
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
return elements;
|
|
65
|
+
};
|
|
66
|
+
return getVisibleElements();
|
|
67
|
+
}""")
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
**basic_info,
|
|
71
|
+
"elements": elements_info
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
def ai_action(self, prompt: str) -> None:
|
|
75
|
+
"""
|
|
76
|
+
Execute an AI-driven action on the page based on the given prompt.
|
|
77
|
+
The AI will analyze the page context and perform the requested action.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
prompt (str): Natural language description of the action to perform
|
|
81
|
+
|
|
82
|
+
Raises:
|
|
83
|
+
ValueError: If the AI response cannot be parsed or contains invalid instructions
|
|
84
|
+
Exception: If the requested action cannot be performed
|
|
85
|
+
"""
|
|
86
|
+
context = self._get_page_context()
|
|
87
|
+
|
|
88
|
+
# 构建提示,明确要求JSON格式的响应
|
|
89
|
+
action_prompt = f"""
|
|
90
|
+
You are a web automation assistant. Based on the following page context, provide instructions for the requested action.
|
|
91
|
+
|
|
92
|
+
Current page context:
|
|
93
|
+
URL: {context['url']}
|
|
94
|
+
Title: {context['title']}
|
|
95
|
+
|
|
96
|
+
Available elements:
|
|
97
|
+
{json.dumps(context['elements'], indent=2)}
|
|
98
|
+
|
|
99
|
+
User request: {prompt}
|
|
100
|
+
|
|
101
|
+
Return ONLY a JSON object with the following structure, no other text:
|
|
102
|
+
{{
|
|
103
|
+
"selector": "CSS selector or XPath to locate the element",
|
|
104
|
+
"action": "fill",
|
|
105
|
+
"value": "text to input",
|
|
106
|
+
"key": "key to press if needed"
|
|
107
|
+
}}
|
|
108
|
+
|
|
109
|
+
Example response:
|
|
110
|
+
{{
|
|
111
|
+
"selector": "#search-input",
|
|
112
|
+
"action": "fill",
|
|
113
|
+
"value": "search text",
|
|
114
|
+
"key": "Enter"
|
|
115
|
+
}}
|
|
116
|
+
"""
|
|
117
|
+
|
|
118
|
+
response = self.llm_client.complete(action_prompt)
|
|
119
|
+
|
|
120
|
+
try:
|
|
121
|
+
# 尝试提取JSON部分
|
|
122
|
+
json_str = response
|
|
123
|
+
if '```json' in response:
|
|
124
|
+
json_str = response.split('```json')[1].split('```')[0].strip()
|
|
125
|
+
elif '```' in response:
|
|
126
|
+
json_str = response.split('```')[1].split('```')[0].strip()
|
|
127
|
+
|
|
128
|
+
instruction = json.loads(json_str)
|
|
129
|
+
selector = instruction.get('selector')
|
|
130
|
+
action = instruction.get('action')
|
|
131
|
+
|
|
132
|
+
if not selector or not action:
|
|
133
|
+
raise ValueError("Invalid instruction format")
|
|
134
|
+
|
|
135
|
+
# 执行操作
|
|
136
|
+
element = self.page.locator(selector)
|
|
137
|
+
if action == 'click':
|
|
138
|
+
element.click()
|
|
139
|
+
elif action == 'fill':
|
|
140
|
+
element.fill(instruction.get('value', ''))
|
|
141
|
+
if instruction.get('key'):
|
|
142
|
+
element.press(instruction.get('key'))
|
|
143
|
+
elif action == 'press':
|
|
144
|
+
element.press(instruction.get('key', 'Enter'))
|
|
145
|
+
else:
|
|
146
|
+
raise ValueError(f"Unsupported action: {action}")
|
|
147
|
+
|
|
148
|
+
except json.JSONDecodeError:
|
|
149
|
+
raise ValueError(f"Failed to parse instruction: {response}")
|
|
150
|
+
|
|
151
|
+
def ai_query(self, prompt: str) -> Any:
|
|
152
|
+
"""
|
|
153
|
+
Query information from the page using AI analysis.
|
|
154
|
+
|
|
155
|
+
Args:
|
|
156
|
+
prompt (str): Natural language query about the page content
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
Any: The query results as parsed from the AI response
|
|
160
|
+
|
|
161
|
+
Raises:
|
|
162
|
+
ValueError: If the AI response cannot be parsed into valid JSON
|
|
163
|
+
"""
|
|
164
|
+
context = self._get_page_context()
|
|
165
|
+
|
|
166
|
+
query_prompt = f"""
|
|
167
|
+
You are a web automation assistant. Based on the following page context, answer the query.
|
|
168
|
+
|
|
169
|
+
Current page context:
|
|
170
|
+
URL: {context['url']}
|
|
171
|
+
Title: {context['title']}
|
|
172
|
+
|
|
173
|
+
Available elements:
|
|
174
|
+
{json.dumps(context['elements'], indent=2)}
|
|
175
|
+
|
|
176
|
+
Query: {prompt}
|
|
177
|
+
|
|
178
|
+
Return ONLY a JSON array of results, no other text.
|
|
179
|
+
"""
|
|
180
|
+
|
|
181
|
+
response = self.llm_client.complete(query_prompt)
|
|
182
|
+
|
|
183
|
+
try:
|
|
184
|
+
# 尝试提取JSON部分
|
|
185
|
+
json_str = response
|
|
186
|
+
if '```json' in response:
|
|
187
|
+
json_str = response.split('```json')[1].split('```')[0].strip()
|
|
188
|
+
elif '```' in response:
|
|
189
|
+
json_str = response.split('```')[1].split('```')[0].strip()
|
|
190
|
+
|
|
191
|
+
return json.loads(json_str)
|
|
192
|
+
except json.JSONDecodeError:
|
|
193
|
+
raise ValueError(f"Failed to parse query results: {response}")
|
|
194
|
+
|
|
195
|
+
def ai_assert(self, prompt: str) -> bool:
|
|
196
|
+
"""
|
|
197
|
+
Verify a condition on the page using AI analysis.
|
|
198
|
+
|
|
199
|
+
Args:
|
|
200
|
+
prompt (str): Natural language description of the condition to verify
|
|
201
|
+
|
|
202
|
+
Returns:
|
|
203
|
+
bool: True if the condition is met, False otherwise
|
|
204
|
+
|
|
205
|
+
Raises:
|
|
206
|
+
ValueError: If the AI response cannot be parsed as a boolean value
|
|
207
|
+
"""
|
|
208
|
+
context = self._get_page_context()
|
|
209
|
+
|
|
210
|
+
assert_prompt = f"""
|
|
211
|
+
You are a web automation assistant. Based on the following page context, verify the assertion.
|
|
212
|
+
|
|
213
|
+
Current page context:
|
|
214
|
+
URL: {context['url']}
|
|
215
|
+
Title: {context['title']}
|
|
216
|
+
|
|
217
|
+
Available elements:
|
|
218
|
+
{json.dumps(context['elements'], indent=2)}
|
|
219
|
+
|
|
220
|
+
Assertion to verify: {prompt}
|
|
221
|
+
|
|
222
|
+
Return ONLY true or false as a JSON boolean, no other text.
|
|
223
|
+
Example: true
|
|
224
|
+
"""
|
|
225
|
+
|
|
226
|
+
response = self.llm_client.complete(assert_prompt)
|
|
227
|
+
|
|
228
|
+
try:
|
|
229
|
+
# 尝试提取JSON部分
|
|
230
|
+
json_str = response.lower().strip()
|
|
231
|
+
if 'true' in json_str:
|
|
232
|
+
return True
|
|
233
|
+
if 'false' in json_str:
|
|
234
|
+
return False
|
|
235
|
+
raise ValueError("Invalid assertion response")
|
|
236
|
+
except Exception:
|
|
237
|
+
raise ValueError(f"Failed to parse assertion result: {response}")
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def create_fixture():
|
|
241
|
+
"""
|
|
242
|
+
Create a PlaywrightAiFixture factory.
|
|
243
|
+
|
|
244
|
+
Returns:
|
|
245
|
+
Callable[[Page], PlaywrightAiFixture]: A factory function that creates
|
|
246
|
+
PlaywrightAiFixture instances
|
|
247
|
+
"""
|
|
248
|
+
return PlaywrightAiFixture
|
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
from typing import Any, Dict
|
|
2
|
+
import json
|
|
3
|
+
from selenium.webdriver.remote.webdriver import WebDriver
|
|
4
|
+
from selenium.webdriver.common.by import By
|
|
5
|
+
from selenium.webdriver.support.ui import WebDriverWait
|
|
6
|
+
from selenium.webdriver.support import expected_conditions as EC
|
|
7
|
+
from selenium.webdriver.common.keys import Keys
|
|
8
|
+
from selenium.common.exceptions import TimeoutException
|
|
9
|
+
from autowing.core.llm.factory import LLMFactory
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SeleniumAiFixture:
|
|
13
|
+
"""
|
|
14
|
+
A fixture class that combines Selenium with AI capabilities for web automation.
|
|
15
|
+
Provides AI-driven interaction with web pages using various LLM providers.
|
|
16
|
+
Maintains API compatibility with PlaywrightAiFixture.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
def __init__(self, driver: WebDriver):
|
|
20
|
+
"""
|
|
21
|
+
Initialize the AI-powered Selenium fixture.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
driver (WebDriver): The Selenium WebDriver instance to automate
|
|
25
|
+
"""
|
|
26
|
+
self.driver = driver
|
|
27
|
+
self.llm_client = LLMFactory.create()
|
|
28
|
+
self.wait = WebDriverWait(self.driver, 10) # Default timeout of 10 seconds
|
|
29
|
+
|
|
30
|
+
def _get_page_context(self) -> Dict[str, Any]:
|
|
31
|
+
"""
|
|
32
|
+
Extract context information from the current page.
|
|
33
|
+
Collects information about visible elements and page metadata.
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
Dict[str, Any]: A dictionary containing page URL, title, and information about
|
|
37
|
+
visible interactive elements
|
|
38
|
+
"""
|
|
39
|
+
# Get basic page info
|
|
40
|
+
basic_info = {
|
|
41
|
+
"url": self.driver.current_url,
|
|
42
|
+
"title": self.driver.title
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
# Get key elements info using JavaScript
|
|
46
|
+
elements_info = self.driver.execute_script("""
|
|
47
|
+
const getVisibleElements = () => {
|
|
48
|
+
const elements = [];
|
|
49
|
+
const selectors = [
|
|
50
|
+
'input', 'button', 'a', '[role="button"]',
|
|
51
|
+
'[role="link"]', '[role="searchbox"]', 'textarea'
|
|
52
|
+
];
|
|
53
|
+
|
|
54
|
+
for (const selector of selectors) {
|
|
55
|
+
document.querySelectorAll(selector).forEach(el => {
|
|
56
|
+
if (el.offsetWidth > 0 && el.offsetHeight > 0) {
|
|
57
|
+
elements.push({
|
|
58
|
+
tag: el.tagName.toLowerCase(),
|
|
59
|
+
type: el.getAttribute('type'),
|
|
60
|
+
placeholder: el.getAttribute('placeholder'),
|
|
61
|
+
value: el.value,
|
|
62
|
+
text: el.textContent?.trim(),
|
|
63
|
+
aria: el.getAttribute('aria-label'),
|
|
64
|
+
id: el.id,
|
|
65
|
+
name: el.getAttribute('name'),
|
|
66
|
+
class: el.className
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
return elements;
|
|
72
|
+
};
|
|
73
|
+
return getVisibleElements();
|
|
74
|
+
""")
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
**basic_info,
|
|
78
|
+
"elements": elements_info
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
def ai_action(self, prompt: str) -> None:
|
|
82
|
+
"""
|
|
83
|
+
Execute an AI-driven action on the page based on the given prompt.
|
|
84
|
+
The AI will analyze the page context and perform the requested action.
|
|
85
|
+
|
|
86
|
+
Args:
|
|
87
|
+
prompt (str): Natural language description of the action to perform
|
|
88
|
+
|
|
89
|
+
Raises:
|
|
90
|
+
ValueError: If the AI response cannot be parsed or contains invalid instructions
|
|
91
|
+
TimeoutException: If the element cannot be found or interacted with
|
|
92
|
+
Exception: If the requested action cannot be performed
|
|
93
|
+
"""
|
|
94
|
+
context = self._get_page_context()
|
|
95
|
+
|
|
96
|
+
action_prompt = f"""
|
|
97
|
+
You are a web automation assistant. Based on the following page context, provide instructions for the requested action.
|
|
98
|
+
|
|
99
|
+
Current page context:
|
|
100
|
+
URL: {context['url']}
|
|
101
|
+
Title: {context['title']}
|
|
102
|
+
|
|
103
|
+
Available elements:
|
|
104
|
+
{json.dumps(context['elements'], indent=2)}
|
|
105
|
+
|
|
106
|
+
User request: {prompt}
|
|
107
|
+
|
|
108
|
+
Return ONLY a JSON object with the following structure, no other text:
|
|
109
|
+
{{
|
|
110
|
+
"selector": "CSS selector or XPath to locate the element",
|
|
111
|
+
"action": "fill",
|
|
112
|
+
"value": "text to input",
|
|
113
|
+
"key": "key to press if needed"
|
|
114
|
+
}}
|
|
115
|
+
|
|
116
|
+
Example response:
|
|
117
|
+
{{
|
|
118
|
+
"selector": "#search-input",
|
|
119
|
+
"action": "fill",
|
|
120
|
+
"value": "search text",
|
|
121
|
+
"key": "Enter"
|
|
122
|
+
}}
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
response = self.llm_client.complete(action_prompt)
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
# Try to extract JSON part
|
|
129
|
+
json_str = response
|
|
130
|
+
if '```json' in response:
|
|
131
|
+
json_str = response.split('```json')[1].split('```')[0].strip()
|
|
132
|
+
elif '```' in response:
|
|
133
|
+
json_str = response.split('```')[1].split('```')[0].strip()
|
|
134
|
+
|
|
135
|
+
instruction = json.loads(json_str)
|
|
136
|
+
selector = instruction.get('selector')
|
|
137
|
+
action = instruction.get('action')
|
|
138
|
+
|
|
139
|
+
if not selector or not action:
|
|
140
|
+
raise ValueError("Invalid instruction format")
|
|
141
|
+
|
|
142
|
+
# Execute the action
|
|
143
|
+
element = self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
|
|
144
|
+
|
|
145
|
+
if action == 'click':
|
|
146
|
+
element.click()
|
|
147
|
+
elif action == 'fill':
|
|
148
|
+
element.clear()
|
|
149
|
+
element.send_keys(instruction.get('value', ''))
|
|
150
|
+
if instruction.get('key'):
|
|
151
|
+
key_attr = getattr(Keys, instruction['key'].upper(), None)
|
|
152
|
+
if key_attr:
|
|
153
|
+
element.send_keys(key_attr)
|
|
154
|
+
elif action == 'press':
|
|
155
|
+
key_attr = getattr(Keys, instruction.get('key', 'ENTER').upper())
|
|
156
|
+
element.send_keys(key_attr)
|
|
157
|
+
else:
|
|
158
|
+
raise ValueError(f"Unsupported action: {action}")
|
|
159
|
+
|
|
160
|
+
except json.JSONDecodeError:
|
|
161
|
+
raise ValueError(f"Failed to parse instruction: {response}")
|
|
162
|
+
except TimeoutException:
|
|
163
|
+
raise TimeoutException(f"Element not found: {selector}")
|
|
164
|
+
|
|
165
|
+
def ai_query(self, prompt: str) -> Any:
|
|
166
|
+
"""
|
|
167
|
+
Query information from the page using AI analysis.
|
|
168
|
+
|
|
169
|
+
Args:
|
|
170
|
+
prompt (str): Natural language query about the page content
|
|
171
|
+
|
|
172
|
+
Returns:
|
|
173
|
+
Any: The query results as parsed from the AI response
|
|
174
|
+
|
|
175
|
+
Raises:
|
|
176
|
+
ValueError: If the AI response cannot be parsed into valid JSON
|
|
177
|
+
"""
|
|
178
|
+
context = self._get_page_context()
|
|
179
|
+
|
|
180
|
+
query_prompt = f"""
|
|
181
|
+
You are a web automation assistant. Based on the following page context, answer the query.
|
|
182
|
+
|
|
183
|
+
Current page context:
|
|
184
|
+
URL: {context['url']}
|
|
185
|
+
Title: {context['title']}
|
|
186
|
+
|
|
187
|
+
Available elements:
|
|
188
|
+
{json.dumps(context['elements'], indent=2)}
|
|
189
|
+
|
|
190
|
+
Query: {prompt}
|
|
191
|
+
|
|
192
|
+
Return ONLY a JSON array of results, no other text.
|
|
193
|
+
"""
|
|
194
|
+
|
|
195
|
+
response = self.llm_client.complete(query_prompt)
|
|
196
|
+
|
|
197
|
+
try:
|
|
198
|
+
# Try to extract JSON part
|
|
199
|
+
json_str = response
|
|
200
|
+
if '```json' in response:
|
|
201
|
+
json_str = response.split('```json')[1].split('```')[0].strip()
|
|
202
|
+
elif '```' in response:
|
|
203
|
+
json_str = response.split('```')[1].split('```')[0].strip()
|
|
204
|
+
|
|
205
|
+
return json.loads(json_str)
|
|
206
|
+
except json.JSONDecodeError:
|
|
207
|
+
raise ValueError(f"Failed to parse query results: {response}")
|
|
208
|
+
|
|
209
|
+
def ai_assert(self, prompt: str) -> bool:
|
|
210
|
+
"""
|
|
211
|
+
Verify a condition on the page using AI analysis.
|
|
212
|
+
|
|
213
|
+
Args:
|
|
214
|
+
prompt (str): Natural language description of the condition to verify
|
|
215
|
+
|
|
216
|
+
Returns:
|
|
217
|
+
bool: True if the condition is met, False otherwise
|
|
218
|
+
|
|
219
|
+
Raises:
|
|
220
|
+
ValueError: If the AI response cannot be parsed as a boolean value
|
|
221
|
+
"""
|
|
222
|
+
context = self._get_page_context()
|
|
223
|
+
|
|
224
|
+
assert_prompt = f"""
|
|
225
|
+
You are a web automation assistant. Based on the following page context, verify the assertion.
|
|
226
|
+
|
|
227
|
+
Current page context:
|
|
228
|
+
URL: {context['url']}
|
|
229
|
+
Title: {context['title']}
|
|
230
|
+
|
|
231
|
+
Available elements:
|
|
232
|
+
{json.dumps(context['elements'], indent=2)}
|
|
233
|
+
|
|
234
|
+
Assertion to verify: {prompt}
|
|
235
|
+
|
|
236
|
+
Return ONLY true or false as a JSON boolean, no other text.
|
|
237
|
+
Example: true
|
|
238
|
+
"""
|
|
239
|
+
|
|
240
|
+
response = self.llm_client.complete(assert_prompt)
|
|
241
|
+
|
|
242
|
+
try:
|
|
243
|
+
# Try to extract JSON part
|
|
244
|
+
json_str = response.lower().strip()
|
|
245
|
+
if 'true' in json_str:
|
|
246
|
+
return True
|
|
247
|
+
if 'false' in json_str:
|
|
248
|
+
return False
|
|
249
|
+
raise ValueError("Invalid assertion response")
|
|
250
|
+
except Exception:
|
|
251
|
+
raise ValueError(f"Failed to parse assertion result: {response}")
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def create_fixture():
|
|
255
|
+
"""
|
|
256
|
+
Create a SeleniumAiFixture factory.
|
|
257
|
+
|
|
258
|
+
Returns:
|
|
259
|
+
Callable[[WebDriver], SeleniumAiFixture]: A factory function that creates
|
|
260
|
+
SeleniumAiFixture instances
|
|
261
|
+
"""
|
|
262
|
+
return SeleniumAiFixture
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
[tool.poetry]
|
|
2
|
+
name = "autowing"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "auto-wing is a tool that uses LLM to assist automated testing."
|
|
5
|
+
authors = ["defnngj <defnngj@gmail.com>"]
|
|
6
|
+
readme = "README.md"
|
|
7
|
+
|
|
8
|
+
[tool.poetry.dependencies]
|
|
9
|
+
python = "^3.12"
|
|
10
|
+
openai = "^1.60.1"
|
|
11
|
+
dashscope = "^1.22.1"
|
|
12
|
+
pytest-playwright = "^0.6.2"
|
|
13
|
+
selenium = "^4.28.1"
|
|
14
|
+
python-dotenv = "^1.0.1"
|
|
15
|
+
|
|
16
|
+
[build-system]
|
|
17
|
+
requires = ["poetry-core"]
|
|
18
|
+
build-backend = "poetry.core.masonry.api"
|