aient 1.0.29__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.
- aient-1.0.29/LICENSE +7 -0
- aient-1.0.29/MANIFEST.in +1 -0
- aient-1.0.29/PKG-INFO +119 -0
- aient-1.0.29/README.md +93 -0
- aient-1.0.29/setup.cfg +4 -0
- aient-1.0.29/setup.py +15 -0
- aient-1.0.29/src/aient/__init__.py +1 -0
- aient-1.0.29/src/aient/core/.git +1 -0
- aient-1.0.29/src/aient/core/__init__.py +1 -0
- aient-1.0.29/src/aient/core/log_config.py +6 -0
- aient-1.0.29/src/aient/core/models.py +227 -0
- aient-1.0.29/src/aient/core/request.py +1361 -0
- aient-1.0.29/src/aient/core/response.py +531 -0
- aient-1.0.29/src/aient/core/test/test_base_api.py +17 -0
- aient-1.0.29/src/aient/core/test/test_image.py +15 -0
- aient-1.0.29/src/aient/core/test/test_payload.py +92 -0
- aient-1.0.29/src/aient/core/utils.py +655 -0
- aient-1.0.29/src/aient/models/__init__.py +9 -0
- aient-1.0.29/src/aient/models/audio.py +63 -0
- aient-1.0.29/src/aient/models/base.py +270 -0
- aient-1.0.29/src/aient/models/chatgpt.py +856 -0
- aient-1.0.29/src/aient/models/claude.py +640 -0
- aient-1.0.29/src/aient/models/duckduckgo.py +241 -0
- aient-1.0.29/src/aient/models/gemini.py +357 -0
- aient-1.0.29/src/aient/models/groq.py +268 -0
- aient-1.0.29/src/aient/models/vertex.py +420 -0
- aient-1.0.29/src/aient/plugins/__init__.py +32 -0
- aient-1.0.29/src/aient/plugins/arXiv.py +48 -0
- aient-1.0.29/src/aient/plugins/config.py +178 -0
- aient-1.0.29/src/aient/plugins/image.py +72 -0
- aient-1.0.29/src/aient/plugins/registry.py +116 -0
- aient-1.0.29/src/aient/plugins/run_python.py +156 -0
- aient-1.0.29/src/aient/plugins/today.py +19 -0
- aient-1.0.29/src/aient/plugins/websearch.py +393 -0
- aient-1.0.29/src/aient/utils/__init__.py +0 -0
- aient-1.0.29/src/aient/utils/prompt.py +143 -0
- aient-1.0.29/src/aient/utils/scripts.py +235 -0
- aient-1.0.29/src/aient.egg-info/PKG-INFO +119 -0
- aient-1.0.29/src/aient.egg-info/SOURCES.txt +70 -0
- aient-1.0.29/src/aient.egg-info/dependency_links.txt +1 -0
- aient-1.0.29/src/aient.egg-info/requires.txt +14 -0
- aient-1.0.29/src/aient.egg-info/top_level.txt +1 -0
- aient-1.0.29/test/test.py +2 -0
- aient-1.0.29/test/test_API.py +6 -0
- aient-1.0.29/test/test_Deepbricks.py +20 -0
- aient-1.0.29/test/test_Web_crawler.py +262 -0
- aient-1.0.29/test/test_aiwaves.py +25 -0
- aient-1.0.29/test/test_aiwaves_arxiv.py +19 -0
- aient-1.0.29/test/test_ask_gemini.py +8 -0
- aient-1.0.29/test/test_class.py +17 -0
- aient-1.0.29/test/test_claude.py +23 -0
- aient-1.0.29/test/test_claude_zh_char.py +26 -0
- aient-1.0.29/test/test_ddg_search.py +50 -0
- aient-1.0.29/test/test_download_pdf.py +56 -0
- aient-1.0.29/test/test_gemini.py +97 -0
- aient-1.0.29/test/test_get_token_dict.py +21 -0
- aient-1.0.29/test/test_google_search.py +35 -0
- aient-1.0.29/test/test_jieba.py +32 -0
- aient-1.0.29/test/test_json.py +65 -0
- aient-1.0.29/test/test_langchain_search_old.py +235 -0
- aient-1.0.29/test/test_logging.py +32 -0
- aient-1.0.29/test/test_ollama.py +55 -0
- aient-1.0.29/test/test_plugin.py +16 -0
- aient-1.0.29/test/test_py_run.py +26 -0
- aient-1.0.29/test/test_requests.py +162 -0
- aient-1.0.29/test/test_search.py +18 -0
- aient-1.0.29/test/test_tikitoken.py +19 -0
- aient-1.0.29/test/test_token.py +94 -0
- aient-1.0.29/test/test_url.py +33 -0
- aient-1.0.29/test/test_whisper.py +14 -0
- aient-1.0.29/test/test_wildcard.py +20 -0
- aient-1.0.29/test/test_yjh.py +21 -0
aient-1.0.29/LICENSE
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
Copyright (c) 2024 yym68686
|
2
|
+
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
4
|
+
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
6
|
+
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
aient-1.0.29/MANIFEST.in
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
recursive-include src/aient/core *
|
aient-1.0.29/PKG-INFO
ADDED
@@ -0,0 +1,119 @@
|
|
1
|
+
Metadata-Version: 2.4
|
2
|
+
Name: aient
|
3
|
+
Version: 1.0.29
|
4
|
+
Summary: Aient: The Awakening of Agent.
|
5
|
+
Description-Content-Type: text/markdown
|
6
|
+
License-File: LICENSE
|
7
|
+
Requires-Dist: pytz
|
8
|
+
Requires-Dist: httpx
|
9
|
+
Requires-Dist: pillow
|
10
|
+
Requires-Dist: msgspec
|
11
|
+
Requires-Dist: fastapi
|
12
|
+
Requires-Dist: PyExecJS
|
13
|
+
Requires-Dist: requests
|
14
|
+
Requires-Dist: html2text
|
15
|
+
Requires-Dist: fake-useragent
|
16
|
+
Requires-Dist: beautifulsoup4
|
17
|
+
Requires-Dist: tiktoken==0.6.0
|
18
|
+
Requires-Dist: lxml-html-clean
|
19
|
+
Requires-Dist: pdfminer.six==20240706
|
20
|
+
Requires-Dist: duckduckgo-search==5.3.1
|
21
|
+
Dynamic: description
|
22
|
+
Dynamic: description-content-type
|
23
|
+
Dynamic: license-file
|
24
|
+
Dynamic: requires-dist
|
25
|
+
Dynamic: summary
|
26
|
+
|
27
|
+
# aient
|
28
|
+
|
29
|
+
[English](./README.md) | [Chinese](./README_CN.md)
|
30
|
+
|
31
|
+
aient is a powerful library designed to simplify and unify the use of different large language models, including GPT-3.5/4/4 Turbo/4o, o1-preview/o1-mini, DALL-E 3, Claude2/3/3.5, Gemini1.5 Pro/Flash, Vertex AI (Claude, Gemini), DuckDuckGo, and Groq. The library supports GPT format function calls and has built-in Google search and URL summarization features, greatly enhancing the practicality and flexibility of the models.
|
32
|
+
|
33
|
+
## ✨ Features
|
34
|
+
|
35
|
+
- **Multi-model support**: Integrate various latest large language models.
|
36
|
+
- **Real-time Interaction**: Supports real-time query streams, real-time model response retrieval.
|
37
|
+
- **Function Expansion**: With built-in function calling support, the model's functions can be easily expanded, currently supporting plugins such as DuckDuckGo and Google search, content summarization, Dalle-3 drawing, arXiv paper summaries, current time, code interpreter, and more.
|
38
|
+
- **Simple Interface**: Provides a concise and unified API interface, making it easy to call and manage the model.
|
39
|
+
|
40
|
+
## Quick Start
|
41
|
+
|
42
|
+
The following is a guide on how to quickly integrate and use aient in your Python project.
|
43
|
+
|
44
|
+
### Install
|
45
|
+
|
46
|
+
First, you need to install aient. It can be installed directly via pip:
|
47
|
+
|
48
|
+
```bash
|
49
|
+
pip install aient
|
50
|
+
```
|
51
|
+
|
52
|
+
### Usage example
|
53
|
+
|
54
|
+
The following is a simple example demonstrating how to use aient to request the GPT-4 model and handle the returned streaming data:
|
55
|
+
|
56
|
+
```python
|
57
|
+
from aient import chatgpt
|
58
|
+
|
59
|
+
# Initialize the model, set the API key and the selected model
|
60
|
+
bot = chatgpt(api_key="{YOUR_API_KEY}", engine="gpt-4o")
|
61
|
+
|
62
|
+
# Get response
|
63
|
+
result = bot.ask("python list use")
|
64
|
+
|
65
|
+
# Send request and get streaming response in real-time
|
66
|
+
for text in bot.ask_stream("python list use"):
|
67
|
+
print(text, end="")
|
68
|
+
|
69
|
+
# Disable all plugins
|
70
|
+
bot = chatgpt(api_key="{YOUR_API_KEY}", engine="gpt-4o", use_plugins=False)
|
71
|
+
```
|
72
|
+
|
73
|
+
## 🍃 Environment Variables
|
74
|
+
|
75
|
+
The following is a list of environment variables related to plugin settings:
|
76
|
+
|
77
|
+
| Variable Name | Description | Required? |
|
78
|
+
|---------------|-------------|-----------|
|
79
|
+
| get_search_results | Enable search plugin. Default value is `False`. | No |
|
80
|
+
| get_url_content | Enable URL summary plugin. The default value is `False`. | No |
|
81
|
+
| download_read_arxiv_pdf | Whether to enable the arXiv paper abstract plugin. The default value is `False`. | No |
|
82
|
+
| run_python_script | Whether to enable the code interpreter plugin. The default value is `False`. | No |
|
83
|
+
| generate_image | Whether to enable the image generation plugin. The default value is `False`. | No |
|
84
|
+
| get_date_time_weekday | Whether to enable the date plugin. The default value is `False`. | No |
|
85
|
+
|
86
|
+
## Supported models
|
87
|
+
|
88
|
+
- GPT-3.5/4/4 Turbo/4o
|
89
|
+
- o1-preview/o1-mini
|
90
|
+
- DALL-E 3
|
91
|
+
- Claude2/3/3.5
|
92
|
+
- Gemini1.5 Pro/Flash
|
93
|
+
- Vertex AI (Claude, Gemini)
|
94
|
+
- Groq
|
95
|
+
- DuckDuckGo(gpt-4o-mini, claude-3-haiku, Meta-Llama-3.1-70B, Mixtral-8x7B)
|
96
|
+
|
97
|
+
## 🧩 Plugin
|
98
|
+
|
99
|
+
This project supports multiple plugins, including: DuckDuckGo and Google search, URL summary, ArXiv paper summary, DALLE-3 drawing, and code interpreter, etc. You can enable or disable these plugins by setting environment variables.
|
100
|
+
|
101
|
+
- How to develop a plugin?
|
102
|
+
|
103
|
+
The plugin-related code is all in the aient git submodule of this repository. aient is an independent repository I developed for handling API requests, conversation history management, and other functionality. When you clone this repository with the `--recurse-submodules` parameter, aient will be automatically downloaded. All plugin code is located in the relative path `aient/src/aient/plugins` in this repository. You can add your own plugin code in this directory. The plugin development process is as follows:
|
104
|
+
|
105
|
+
1. Create a new Python file in the `aient/src/aient/plugins` directory, for example, `myplugin.py`. Register the plugin by adding the `@register_tool()` decorator above the function. Import `register_tool` with `from .registry import register_tool`.
|
106
|
+
|
107
|
+
After completing the above steps, your plugin is ready to use. 🎉
|
108
|
+
|
109
|
+
## License
|
110
|
+
|
111
|
+
This project is licensed under the MIT License.
|
112
|
+
|
113
|
+
## Contribution
|
114
|
+
|
115
|
+
Welcome to contribute improvements by submitting issues or pull requests through GitHub.
|
116
|
+
|
117
|
+
## Contact Information
|
118
|
+
|
119
|
+
If you have any questions or need assistance, please contact us at [yym68686@outlook.com](mailto:yym68686@outlook.com).
|
aient-1.0.29/README.md
ADDED
@@ -0,0 +1,93 @@
|
|
1
|
+
# aient
|
2
|
+
|
3
|
+
[English](./README.md) | [Chinese](./README_CN.md)
|
4
|
+
|
5
|
+
aient is a powerful library designed to simplify and unify the use of different large language models, including GPT-3.5/4/4 Turbo/4o, o1-preview/o1-mini, DALL-E 3, Claude2/3/3.5, Gemini1.5 Pro/Flash, Vertex AI (Claude, Gemini), DuckDuckGo, and Groq. The library supports GPT format function calls and has built-in Google search and URL summarization features, greatly enhancing the practicality and flexibility of the models.
|
6
|
+
|
7
|
+
## ✨ Features
|
8
|
+
|
9
|
+
- **Multi-model support**: Integrate various latest large language models.
|
10
|
+
- **Real-time Interaction**: Supports real-time query streams, real-time model response retrieval.
|
11
|
+
- **Function Expansion**: With built-in function calling support, the model's functions can be easily expanded, currently supporting plugins such as DuckDuckGo and Google search, content summarization, Dalle-3 drawing, arXiv paper summaries, current time, code interpreter, and more.
|
12
|
+
- **Simple Interface**: Provides a concise and unified API interface, making it easy to call and manage the model.
|
13
|
+
|
14
|
+
## Quick Start
|
15
|
+
|
16
|
+
The following is a guide on how to quickly integrate and use aient in your Python project.
|
17
|
+
|
18
|
+
### Install
|
19
|
+
|
20
|
+
First, you need to install aient. It can be installed directly via pip:
|
21
|
+
|
22
|
+
```bash
|
23
|
+
pip install aient
|
24
|
+
```
|
25
|
+
|
26
|
+
### Usage example
|
27
|
+
|
28
|
+
The following is a simple example demonstrating how to use aient to request the GPT-4 model and handle the returned streaming data:
|
29
|
+
|
30
|
+
```python
|
31
|
+
from aient import chatgpt
|
32
|
+
|
33
|
+
# Initialize the model, set the API key and the selected model
|
34
|
+
bot = chatgpt(api_key="{YOUR_API_KEY}", engine="gpt-4o")
|
35
|
+
|
36
|
+
# Get response
|
37
|
+
result = bot.ask("python list use")
|
38
|
+
|
39
|
+
# Send request and get streaming response in real-time
|
40
|
+
for text in bot.ask_stream("python list use"):
|
41
|
+
print(text, end="")
|
42
|
+
|
43
|
+
# Disable all plugins
|
44
|
+
bot = chatgpt(api_key="{YOUR_API_KEY}", engine="gpt-4o", use_plugins=False)
|
45
|
+
```
|
46
|
+
|
47
|
+
## 🍃 Environment Variables
|
48
|
+
|
49
|
+
The following is a list of environment variables related to plugin settings:
|
50
|
+
|
51
|
+
| Variable Name | Description | Required? |
|
52
|
+
|---------------|-------------|-----------|
|
53
|
+
| get_search_results | Enable search plugin. Default value is `False`. | No |
|
54
|
+
| get_url_content | Enable URL summary plugin. The default value is `False`. | No |
|
55
|
+
| download_read_arxiv_pdf | Whether to enable the arXiv paper abstract plugin. The default value is `False`. | No |
|
56
|
+
| run_python_script | Whether to enable the code interpreter plugin. The default value is `False`. | No |
|
57
|
+
| generate_image | Whether to enable the image generation plugin. The default value is `False`. | No |
|
58
|
+
| get_date_time_weekday | Whether to enable the date plugin. The default value is `False`. | No |
|
59
|
+
|
60
|
+
## Supported models
|
61
|
+
|
62
|
+
- GPT-3.5/4/4 Turbo/4o
|
63
|
+
- o1-preview/o1-mini
|
64
|
+
- DALL-E 3
|
65
|
+
- Claude2/3/3.5
|
66
|
+
- Gemini1.5 Pro/Flash
|
67
|
+
- Vertex AI (Claude, Gemini)
|
68
|
+
- Groq
|
69
|
+
- DuckDuckGo(gpt-4o-mini, claude-3-haiku, Meta-Llama-3.1-70B, Mixtral-8x7B)
|
70
|
+
|
71
|
+
## 🧩 Plugin
|
72
|
+
|
73
|
+
This project supports multiple plugins, including: DuckDuckGo and Google search, URL summary, ArXiv paper summary, DALLE-3 drawing, and code interpreter, etc. You can enable or disable these plugins by setting environment variables.
|
74
|
+
|
75
|
+
- How to develop a plugin?
|
76
|
+
|
77
|
+
The plugin-related code is all in the aient git submodule of this repository. aient is an independent repository I developed for handling API requests, conversation history management, and other functionality. When you clone this repository with the `--recurse-submodules` parameter, aient will be automatically downloaded. All plugin code is located in the relative path `aient/src/aient/plugins` in this repository. You can add your own plugin code in this directory. The plugin development process is as follows:
|
78
|
+
|
79
|
+
1. Create a new Python file in the `aient/src/aient/plugins` directory, for example, `myplugin.py`. Register the plugin by adding the `@register_tool()` decorator above the function. Import `register_tool` with `from .registry import register_tool`.
|
80
|
+
|
81
|
+
After completing the above steps, your plugin is ready to use. 🎉
|
82
|
+
|
83
|
+
## License
|
84
|
+
|
85
|
+
This project is licensed under the MIT License.
|
86
|
+
|
87
|
+
## Contribution
|
88
|
+
|
89
|
+
Welcome to contribute improvements by submitting issues or pull requests through GitHub.
|
90
|
+
|
91
|
+
## Contact Information
|
92
|
+
|
93
|
+
If you have any questions or need assistance, please contact us at [yym68686@outlook.com](mailto:yym68686@outlook.com).
|
aient-1.0.29/setup.cfg
ADDED
aient-1.0.29/setup.py
ADDED
@@ -0,0 +1,15 @@
|
|
1
|
+
from pathlib import Path
|
2
|
+
|
3
|
+
from setuptools import setup, find_packages
|
4
|
+
|
5
|
+
setup(
|
6
|
+
name="aient",
|
7
|
+
version="1.0.29",
|
8
|
+
description="Aient: The Awakening of Agent.",
|
9
|
+
long_description=Path.open(Path("README.md"), encoding="utf-8").read(),
|
10
|
+
long_description_content_type="text/markdown",
|
11
|
+
packages=find_packages("src"),
|
12
|
+
package_dir={"": "src"},
|
13
|
+
install_requires=Path.open(Path("requirements.txt"), encoding="utf-8").read().splitlines(),
|
14
|
+
include_package_data=True,
|
15
|
+
)
|
@@ -0,0 +1 @@
|
|
1
|
+
from .models import *
|
@@ -0,0 +1 @@
|
|
1
|
+
gitdir: ../../../.git/modules/src/aient/core
|
@@ -0,0 +1 @@
|
|
1
|
+
# core package initialization file
|
@@ -0,0 +1,6 @@
|
|
1
|
+
import logging
|
2
|
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
|
3
|
+
logger = logging.getLogger("uni-api")
|
4
|
+
|
5
|
+
logging.getLogger("httpx").setLevel(logging.CRITICAL)
|
6
|
+
logging.getLogger("watchfiles.main").setLevel(logging.CRITICAL)
|
@@ -0,0 +1,227 @@
|
|
1
|
+
from io import IOBase
|
2
|
+
from pydantic import BaseModel, Field, model_validator, ConfigDict
|
3
|
+
from typing import List, Dict, Optional, Union, Tuple, Literal, Any
|
4
|
+
|
5
|
+
class FunctionParameter(BaseModel):
|
6
|
+
type: str
|
7
|
+
properties: Dict[str, Dict[str, Any]]
|
8
|
+
required: List[str] = None
|
9
|
+
defs: Dict[str, Any] = Field(default=None, alias="$defs")
|
10
|
+
|
11
|
+
class Config:
|
12
|
+
population_by_name = True
|
13
|
+
|
14
|
+
class Function(BaseModel):
|
15
|
+
name: str
|
16
|
+
description: str = Field(default=None)
|
17
|
+
parameters: Optional[FunctionParameter] = Field(default=None, exclude=None)
|
18
|
+
|
19
|
+
class Tool(BaseModel):
|
20
|
+
type: str
|
21
|
+
function: Function
|
22
|
+
|
23
|
+
@classmethod
|
24
|
+
def parse_raw(cls, json_str: str) -> 'Tool':
|
25
|
+
"""从JSON字符串解析Tool对象"""
|
26
|
+
return cls.model_validate_json(json_str)
|
27
|
+
|
28
|
+
class FunctionCall(BaseModel):
|
29
|
+
name: str
|
30
|
+
arguments: str
|
31
|
+
|
32
|
+
class ToolCall(BaseModel):
|
33
|
+
id: str
|
34
|
+
type: str
|
35
|
+
function: FunctionCall
|
36
|
+
|
37
|
+
class ImageUrl(BaseModel):
|
38
|
+
url: str
|
39
|
+
|
40
|
+
class ContentItem(BaseModel):
|
41
|
+
type: str
|
42
|
+
text: Optional[str] = None
|
43
|
+
image_url: Optional[ImageUrl] = None
|
44
|
+
|
45
|
+
class Message(BaseModel):
|
46
|
+
role: str
|
47
|
+
name: Optional[str] = None
|
48
|
+
arguments: Optional[str] = None
|
49
|
+
content: Optional[Union[str, List[ContentItem]]] = None
|
50
|
+
tool_calls: Optional[List[ToolCall]] = None
|
51
|
+
|
52
|
+
class Message(BaseModel):
|
53
|
+
role: str
|
54
|
+
name: Optional[str] = None
|
55
|
+
content: Optional[Union[str, List[ContentItem]]] = None
|
56
|
+
tool_calls: Optional[List[ToolCall]] = None
|
57
|
+
tool_call_id: Optional[str] = None
|
58
|
+
|
59
|
+
class Config:
|
60
|
+
extra = "allow" # 允许额外的字段
|
61
|
+
|
62
|
+
class FunctionChoice(BaseModel):
|
63
|
+
name: str
|
64
|
+
|
65
|
+
class ToolChoice(BaseModel):
|
66
|
+
type: str
|
67
|
+
function: Optional[FunctionChoice] = None
|
68
|
+
|
69
|
+
class BaseRequest(BaseModel):
|
70
|
+
request_type: Optional[Literal["chat", "image", "audio", "moderation"]] = Field(default=None, exclude=True)
|
71
|
+
|
72
|
+
import warnings
|
73
|
+
warnings.filterwarnings("ignore", category=UserWarning, message=".*shadows an attribute.*")
|
74
|
+
|
75
|
+
class JsonSchema(BaseModel):
|
76
|
+
name: str
|
77
|
+
schema: Dict[str, Any] = Field(validation_alias='schema')
|
78
|
+
|
79
|
+
model_config = ConfigDict(protected_namespaces=())
|
80
|
+
|
81
|
+
class ResponseFormat(BaseModel):
|
82
|
+
type: Literal["text", "json_object", "json_schema"]
|
83
|
+
json_schema: Optional[JsonSchema] = None
|
84
|
+
|
85
|
+
class Thinking(BaseModel):
|
86
|
+
budget_tokens: Optional[int] = None
|
87
|
+
type: Optional[Literal["enabled", "disabled"]] = None
|
88
|
+
|
89
|
+
class RequestModel(BaseRequest):
|
90
|
+
model: str
|
91
|
+
messages: List[Message]
|
92
|
+
logprobs: Optional[bool] = None
|
93
|
+
top_logprobs: Optional[int] = None
|
94
|
+
stream: Optional[bool] = None
|
95
|
+
include_usage: Optional[bool] = None
|
96
|
+
temperature: Optional[float] = 0.5
|
97
|
+
top_p: Optional[float] = 1.0
|
98
|
+
max_tokens: Optional[int] = None
|
99
|
+
max_completion_tokens: Optional[int] = None
|
100
|
+
presence_penalty: Optional[float] = 0.0
|
101
|
+
frequency_penalty: Optional[float] = 0.0
|
102
|
+
n: Optional[int] = 1
|
103
|
+
user: Optional[str] = None
|
104
|
+
tool_choice: Optional[Union[str, ToolChoice]] = None
|
105
|
+
tools: Optional[List[Tool]] = None
|
106
|
+
response_format: Optional[ResponseFormat] = None
|
107
|
+
thinking: Optional[Thinking] = None
|
108
|
+
|
109
|
+
def get_last_text_message(self) -> Optional[str]:
|
110
|
+
for message in reversed(self.messages):
|
111
|
+
if message.content:
|
112
|
+
if isinstance(message.content, str):
|
113
|
+
return message.content
|
114
|
+
elif isinstance(message.content, list):
|
115
|
+
for item in reversed(message.content):
|
116
|
+
if item.type == "text" and item.text:
|
117
|
+
return item.text
|
118
|
+
return ""
|
119
|
+
|
120
|
+
def model_dump(self, **kwargs):
|
121
|
+
data = super().model_dump(**kwargs)
|
122
|
+
|
123
|
+
# 检查并处理 tools 字段
|
124
|
+
if 'tools' in data and data['tools']:
|
125
|
+
for tool in data['tools']:
|
126
|
+
if 'function' in tool:
|
127
|
+
function_data = tool['function']
|
128
|
+
# 如果 parameters 为空或没有 properties,则移除
|
129
|
+
if 'parameters' in function_data and (
|
130
|
+
function_data['parameters'] is None or
|
131
|
+
not function_data['parameters'].get('properties')
|
132
|
+
):
|
133
|
+
function_data.pop('parameters', None)
|
134
|
+
|
135
|
+
return data
|
136
|
+
|
137
|
+
class ImageGenerationRequest(BaseRequest):
|
138
|
+
prompt: str
|
139
|
+
model: Optional[str] = "dall-e-3"
|
140
|
+
n: Optional[int] = 1
|
141
|
+
response_format: Optional[str] = "url"
|
142
|
+
size: Optional[str] = "1024x1024"
|
143
|
+
stream: bool = False
|
144
|
+
|
145
|
+
class EmbeddingRequest(BaseRequest):
|
146
|
+
input: Union[str, List[Union[str, int, List[int]]]] # 支持字符串或数组
|
147
|
+
model: str
|
148
|
+
encoding_format: Optional[str] = "float"
|
149
|
+
dimensions: Optional[int] = None
|
150
|
+
user: Optional[str] = None
|
151
|
+
stream: bool = False
|
152
|
+
|
153
|
+
class AudioTranscriptionRequest(BaseRequest):
|
154
|
+
file: Tuple[str, IOBase, str]
|
155
|
+
model: str
|
156
|
+
language: Optional[str] = None
|
157
|
+
prompt: Optional[str] = None
|
158
|
+
response_format: Optional[str] = None
|
159
|
+
temperature: Optional[float] = None
|
160
|
+
stream: bool = False
|
161
|
+
|
162
|
+
class Config:
|
163
|
+
arbitrary_types_allowed = True
|
164
|
+
|
165
|
+
class ModerationRequest(BaseRequest):
|
166
|
+
input: Union[str, List[str]]
|
167
|
+
model: Optional[str] = "text-moderation-latest"
|
168
|
+
stream: bool = False
|
169
|
+
|
170
|
+
class TextToSpeechRequest(BaseRequest):
|
171
|
+
model: str
|
172
|
+
input: str
|
173
|
+
voice: str
|
174
|
+
response_format: Optional[str] = "mp3"
|
175
|
+
speed: Optional[float] = 1.0
|
176
|
+
stream: Optional[bool] = False # Add this line
|
177
|
+
|
178
|
+
class UnifiedRequest(BaseModel):
|
179
|
+
data: Union[RequestModel, ImageGenerationRequest, AudioTranscriptionRequest, ModerationRequest, EmbeddingRequest, TextToSpeechRequest]
|
180
|
+
|
181
|
+
@model_validator(mode='before')
|
182
|
+
@classmethod
|
183
|
+
def set_request_type(cls, values):
|
184
|
+
if isinstance(values, dict):
|
185
|
+
if "messages" in values:
|
186
|
+
values["data"] = RequestModel(**values)
|
187
|
+
values["data"].request_type = "chat"
|
188
|
+
elif "prompt" in values:
|
189
|
+
values["data"] = ImageGenerationRequest(**values)
|
190
|
+
values["data"].request_type = "image"
|
191
|
+
elif "file" in values:
|
192
|
+
values["data"] = AudioTranscriptionRequest(**values)
|
193
|
+
values["data"].request_type = "audio"
|
194
|
+
elif "tts" in values.get("model", ""):
|
195
|
+
values["data"] = TextToSpeechRequest(**values)
|
196
|
+
values["data"].request_type = "tts"
|
197
|
+
elif "text-embedding" in values.get("model", ""):
|
198
|
+
values["data"] = EmbeddingRequest(**values)
|
199
|
+
values["data"].request_type = "embedding"
|
200
|
+
elif "input" in values:
|
201
|
+
values["data"] = ModerationRequest(**values)
|
202
|
+
values["data"].request_type = "moderation"
|
203
|
+
else:
|
204
|
+
raise ValueError("无法确定请求类型")
|
205
|
+
return values
|
206
|
+
|
207
|
+
if __name__ == "__main__":
|
208
|
+
# 示例JSON字符串
|
209
|
+
json_str = '''
|
210
|
+
{
|
211
|
+
"type": "function",
|
212
|
+
"function": {
|
213
|
+
"name": "clock-time____getCurrentTime____standalone",
|
214
|
+
"description": "获取当前时间",
|
215
|
+
"parameters": {
|
216
|
+
"type": "object",
|
217
|
+
"properties": {}
|
218
|
+
}
|
219
|
+
}
|
220
|
+
}
|
221
|
+
'''
|
222
|
+
|
223
|
+
# 解析JSON字符串为Tool对象
|
224
|
+
tool = Tool.parse_raw(json_str)
|
225
|
+
|
226
|
+
# parameters 字段将被自动排除
|
227
|
+
print(tool.model_dump(exclude_unset=True))
|