uss-aigent 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.
- uss_aigent-0.1.0/.gitignore +3 -0
- uss_aigent-0.1.0/CLAUDE.md +119 -0
- uss_aigent-0.1.0/LICENSE +201 -0
- uss_aigent-0.1.0/NOTICE +4 -0
- uss_aigent-0.1.0/PKG-INFO +12 -0
- uss_aigent-0.1.0/README-zh.md +172 -0
- uss_aigent-0.1.0/README.md +172 -0
- uss_aigent-0.1.0/doc/design.md +474 -0
- uss_aigent-0.1.0/doc/framework.md +353 -0
- uss_aigent-0.1.0/pyproject.toml +19 -0
- uss_aigent-0.1.0/samples/sample_0.py +61 -0
- uss_aigent-0.1.0/samples/sample_1.py +40 -0
- uss_aigent-0.1.0/samples/sample_chat.py +31 -0
- uss_aigent-0.1.0/src/aigent/__init__.py +68 -0
- uss_aigent-0.1.0/src/aigent/agent.py +192 -0
- uss_aigent-0.1.0/src/aigent/backends/__init__.py +33 -0
- uss_aigent-0.1.0/src/aigent/backends/anthropic.py +190 -0
- uss_aigent-0.1.0/src/aigent/backends/base.py +55 -0
- uss_aigent-0.1.0/src/aigent/backends/openai.py +147 -0
- uss_aigent-0.1.0/src/aigent/exceptions.py +50 -0
- uss_aigent-0.1.0/src/aigent/message.py +48 -0
- uss_aigent-0.1.0/src/aigent/response.py +37 -0
- uss_aigent-0.1.0/src/aigent/session.py +326 -0
- uss_aigent-0.1.0/src/aigent/tool.py +158 -0
- uss_aigent-0.1.0/test.py +678 -0
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# CLAUDE.md
|
|
2
|
+
|
|
3
|
+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
|
4
|
+
|
|
5
|
+
## Project Overview
|
|
6
|
+
|
|
7
|
+
**Aigent** (`aigent`) — a progressive-disclosure Python library for LLM APIs. Classic import: `from aigent import Aigent`.
|
|
8
|
+
|
|
9
|
+
Supports OpenAI and Anthropic API formats via `api_type` switch. Licensed under Apache 2.0.
|
|
10
|
+
|
|
11
|
+
## Design Philosophy
|
|
12
|
+
|
|
13
|
+
From `doc/design.md`:
|
|
14
|
+
|
|
15
|
+
1. **Convention over configuration** — reads env vars, defaults, zero-config to start
|
|
16
|
+
2. **Progressive disclosure** — simple users don't need to know about Message/Tool/Session internals
|
|
17
|
+
3. **Express in Python** — `with` statement for conversation lifecycle, decorators for tools, type hints instead of JSON Schema
|
|
18
|
+
|
|
19
|
+
## Four Core Concepts
|
|
20
|
+
|
|
21
|
+
| Concept | Purpose |
|
|
22
|
+
|---------|---------|
|
|
23
|
+
| **Aigent** | Entry point — holds api_type, api_key, model, timeout. Created once. |
|
|
24
|
+
| **Session** | A conversation — created via `with agent.session() as s:`, auto-closes on exit |
|
|
25
|
+
| **Role** | Who is speaking — `s.user`, `s.assistant`, `s.system`; each has `chat()`, `insert()` |
|
|
26
|
+
| **Tool** | Functions the model can call — created via `@tool` decorator |
|
|
27
|
+
|
|
28
|
+
## Three-Tier API
|
|
29
|
+
|
|
30
|
+
| Tier | API | Use Case |
|
|
31
|
+
|------|-----|----------|
|
|
32
|
+
| 1 | `with agent.session() as s:` → `s.chat(...)` / `s.user.chat(...)` / `s.insert(...)` | Stateful conversation with roles |
|
|
33
|
+
| 2 | `@tool` + `agent.session(tools=[...])` | Model calls Python functions |
|
|
34
|
+
| 3 | `agent.raw(...)`, `s.chat(..., stream=True)`, custom headers, manual history orchestration | Full control |
|
|
35
|
+
|
|
36
|
+
## Session & Role API
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
with agent.session() as s:
|
|
40
|
+
# session-level chat (default role="user")
|
|
41
|
+
s.chat("hello") # add user message + send → returns str
|
|
42
|
+
s.chat("hello", role="assistant") # specify role
|
|
43
|
+
s.chat("tell me a story", stream=True) # returns Iterator[str]
|
|
44
|
+
s.chat() # no new message, just send history → returns str
|
|
45
|
+
|
|
46
|
+
# insert — add to history without sending
|
|
47
|
+
s.insert("message") # default role="user"
|
|
48
|
+
s.insert("message", role="assistant")
|
|
49
|
+
|
|
50
|
+
# role objects
|
|
51
|
+
s.user.chat("hello") # ≡ s.chat("hello")
|
|
52
|
+
s.user.chat("hello", stream=True) # streaming as user
|
|
53
|
+
s.user.insert("message") # ≡ s.insert("message")
|
|
54
|
+
s.assistant.chat("response") # chat as assistant
|
|
55
|
+
s.assistant.insert("response") # insert as assistant
|
|
56
|
+
s.system.insert("You are helpful") # insert system instruction
|
|
57
|
+
s.role("tool").insert(result, tool_call_id="call_123") # custom role
|
|
58
|
+
|
|
59
|
+
# history
|
|
60
|
+
s.clear() # reset conversation
|
|
61
|
+
s.history # read-only message list
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
**Key semantics:**
|
|
65
|
+
- `chat(text)` = insert(text) + send(all history). Returns `str` (or `Iterator[str]` if `stream=True`).
|
|
66
|
+
- `chat()` (no args) = send existing history without adding anything. Returns `str` (or `Iterator[str]` if `stream=True`).
|
|
67
|
+
- `insert(text)` = add to history only, never sends.
|
|
68
|
+
- Role objects (`s.user`, `s.assistant`, `s.system`) are created by Session; users don't instantiate `Role` directly.
|
|
69
|
+
- Tool calls loop automatically inside `chat()` up to `max_tool_rounds`.
|
|
70
|
+
|
|
71
|
+
## Module Architecture
|
|
72
|
+
|
|
73
|
+
```
|
|
74
|
+
src/aigent/
|
|
75
|
+
├── __init__.py # Exports: Aigent, tool, Message, Response, ...
|
|
76
|
+
├── agent.py # Aigent class — main entry, config, session(), raw()
|
|
77
|
+
├── session.py # Session + Role classes — context manager, chat(), insert(), stream()
|
|
78
|
+
├── message.py # Message.system/user/assistant/tool() factory methods
|
|
79
|
+
├── response.py # Response + Usage dataclasses
|
|
80
|
+
├── tool.py # @tool decorator, Tool/ToolParam/ToolCall dataclasses
|
|
81
|
+
├── exceptions.py # LLMError hierarchy
|
|
82
|
+
└── backends/
|
|
83
|
+
├── base.py # BaseBackend — abstract: build_request, parse_response, map_error
|
|
84
|
+
├── openai.py # OpenAIBackend — Chat Completions API
|
|
85
|
+
└── anthropic.py # AnthropicBackend — Messages API
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Data Flow
|
|
89
|
+
|
|
90
|
+
**Session chat with tools:**
|
|
91
|
+
1. `s.chat(text)` → appends user message to history
|
|
92
|
+
2. Sends full history to API via `agent.raw()` → backend formats → httpx → API
|
|
93
|
+
3. If `tool_calls` in response → execute functions → insert tool results → loop (up to `max_tool_rounds`)
|
|
94
|
+
4. Return final text response
|
|
95
|
+
|
|
96
|
+
**Insert-then-chat pattern:**
|
|
97
|
+
1. `s.user.insert("...")` / `s.assistant.insert("...")` — build up history
|
|
98
|
+
2. `s.chat()` — send without adding, LLM responds to the pre-built context
|
|
99
|
+
|
|
100
|
+
## Environment Variables
|
|
101
|
+
|
|
102
|
+
- `OPENAI_API_KEY` — default for `api_type="openai"`
|
|
103
|
+
- `OPENAI_BASE_URL` — defaults to `https://api.openai.com/v1`
|
|
104
|
+
- `OPENAI_MODEL` — defaults to `gpt-4o`
|
|
105
|
+
- `ANTHROPIC_API_KEY` — default for `api_type="anthropic"`
|
|
106
|
+
- `ANTHROPIC_BASE_URL` — defaults to `https://api.anthropic.com/v1`
|
|
107
|
+
- `ANTHROPIC_MODEL` — defaults to `claude-sonnet-4-6`
|
|
108
|
+
|
|
109
|
+
## Dependencies
|
|
110
|
+
|
|
111
|
+
- **httpx** — only external dependency (HTTP client)
|
|
112
|
+
- Standard library: `dataclasses`, `json`, `os`, `logging`, `inspect`
|
|
113
|
+
|
|
114
|
+
## Scope (explicitly out)
|
|
115
|
+
|
|
116
|
+
- No async
|
|
117
|
+
- No token counting
|
|
118
|
+
- No chain/agent/RAG orchestration
|
|
119
|
+
- OpenAI + Anthropic API types only (but OpenAI-compatible services work via `api_type="openai"`)
|
uss_aigent-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.
|
uss_aigent-0.1.0/NOTICE
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: uss-aigent
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A progressive-disclosure Python library for LLM APIs
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
License-File: NOTICE
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Requires-Dist: httpx
|
|
10
|
+
Provides-Extra: dev
|
|
11
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
12
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# Aigent
|
|
2
|
+
|
|
3
|
+
一个渐进式披露的 Python LLM API 库。从一行代码开始,到完全控制 —— 全部使用地道的 Python 表达。
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
from aigent import Aigent
|
|
7
|
+
|
|
8
|
+
agent = Aigent(api_type="openai")
|
|
9
|
+
with agent.session() as s:
|
|
10
|
+
print(s.chat("你好!"))
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## 安装
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install aigent
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
需要 Python 3.10+。唯一外部依赖是 [httpx](https://www.pypi.org/project/httpx/)。
|
|
20
|
+
|
|
21
|
+
## 快速开始
|
|
22
|
+
|
|
23
|
+
### 第一层 —— 聊天
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from aigent import Aigent
|
|
27
|
+
|
|
28
|
+
# 零配置:从环境变量读取 OPENAI_API_KEY / ANTHROPIC_API_KEY
|
|
29
|
+
agent = Aigent(api_type="anthropic")
|
|
30
|
+
|
|
31
|
+
with agent.session(system="你是专业翻译。") as s:
|
|
32
|
+
result = s.chat("翻译成英文:你好世界")
|
|
33
|
+
print(result)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### 第二层 —— 工具
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from aigent import Aigent, tool
|
|
40
|
+
|
|
41
|
+
@tool
|
|
42
|
+
def get_weather(city: str, unit: str = "celsius") -> str:
|
|
43
|
+
"""查询城市天气。"""
|
|
44
|
+
# 实际代码中可调用天气 API
|
|
45
|
+
return f"{city}: 22°{unit[0].upper()}"
|
|
46
|
+
|
|
47
|
+
agent = Aigent(api_type="openai")
|
|
48
|
+
with agent.session(tools=[get_weather]) as s:
|
|
49
|
+
reply = s.chat("北京天气怎么样?")
|
|
50
|
+
print(reply)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`@tool` 装饰器自动从函数签名和 docstring 生成 JSON Schema —— 无需手写。
|
|
54
|
+
|
|
55
|
+
### 第三层 —— 完全控制
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from aigent import Aigent, Message
|
|
59
|
+
|
|
60
|
+
agent = Aigent(api_type="anthropic")
|
|
61
|
+
|
|
62
|
+
# 手动编排消息
|
|
63
|
+
resp = agent.raw(
|
|
64
|
+
[Message.system("你是乐于助人的助手。"), Message.user("你好!")],
|
|
65
|
+
max_tokens=200,
|
|
66
|
+
temperature=0.7,
|
|
67
|
+
)
|
|
68
|
+
print(resp.content) # str
|
|
69
|
+
print(resp.usage) # Usage(prompt_tokens=..., completion_tokens=...)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Session 与 Role API
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
agent = Aigent()
|
|
76
|
+
|
|
77
|
+
with agent.session() as s:
|
|
78
|
+
# 以用户身份聊天(默认)
|
|
79
|
+
s.chat("你好")
|
|
80
|
+
|
|
81
|
+
# 以助手身份聊天
|
|
82
|
+
s.chat("我很好!", role="assistant")
|
|
83
|
+
|
|
84
|
+
# 流式输出
|
|
85
|
+
for token in s.chat("写一首诗", stream=True):
|
|
86
|
+
print(token, end="")
|
|
87
|
+
|
|
88
|
+
# 插入但不发送 —— 逐步构建上下文
|
|
89
|
+
s.user.insert("我想学 Python。")
|
|
90
|
+
s.assistant.insert("好选择!你想从哪里开始?")
|
|
91
|
+
reply = s.chat() # 不追加新消息,直接发送已有历史
|
|
92
|
+
|
|
93
|
+
# 角色对象
|
|
94
|
+
s.system.insert("你是一位 Python 专家。")
|
|
95
|
+
s.role("tool").insert('{"result": 42}', tool_call_id="call_abc")
|
|
96
|
+
|
|
97
|
+
# 历史管理
|
|
98
|
+
print(s.history) # 只读消息列表
|
|
99
|
+
s.clear() # 重置对话
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## 支持的后端
|
|
103
|
+
|
|
104
|
+
| `api_type` | 后端 | 默认模型 |
|
|
105
|
+
|------------|------|----------|
|
|
106
|
+
| `"openai"` | OpenAI Chat Completions | `gpt-4o` |
|
|
107
|
+
| `"anthropic"` | Anthropic Messages | `claude-sonnet-4-6` |
|
|
108
|
+
|
|
109
|
+
兼容 OpenAI 接口的服务(Azure、本地 LLM 等)可通过 `api_type="openai"` + 自定义 `base_url` 使用。
|
|
110
|
+
|
|
111
|
+
## 配置
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
agent = Aigent(
|
|
115
|
+
api_type="openai",
|
|
116
|
+
api_key="sk-...", # 或 OPENAI_API_KEY 环境变量
|
|
117
|
+
base_url="https://api.openai.com/v1", # 或 OPENAI_BASE_URL 环境变量
|
|
118
|
+
model="gpt-4o", # 或 OPENAI_MODEL 环境变量
|
|
119
|
+
system="你是乐于助人的助手。", # 所有 session 的默认系统提示
|
|
120
|
+
timeout=30.0,
|
|
121
|
+
max_retries=3,
|
|
122
|
+
)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
各后端环境变量:
|
|
126
|
+
|
|
127
|
+
| 变量 | OpenAI | Anthropic |
|
|
128
|
+
|------|--------|-----------|
|
|
129
|
+
| API key | `OPENAI_API_KEY` | `ANTHROPIC_API_KEY` |
|
|
130
|
+
| Base URL | `OPENAI_BASE_URL` | `ANTHROPIC_BASE_URL` |
|
|
131
|
+
| Model | `OPENAI_MODEL` | `ANTHROPIC_MODEL` |
|
|
132
|
+
|
|
133
|
+
## 错误处理
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
from aigent import (
|
|
137
|
+
Aigent,
|
|
138
|
+
AuthenticationError,
|
|
139
|
+
RateLimitError,
|
|
140
|
+
APIError,
|
|
141
|
+
ConnectionError,
|
|
142
|
+
TimeoutError,
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
agent = Aigent()
|
|
146
|
+
try:
|
|
147
|
+
with agent.session() as s:
|
|
148
|
+
s.chat("你好")
|
|
149
|
+
except AuthenticationError:
|
|
150
|
+
print("请检查 API key。")
|
|
151
|
+
except RateLimitError:
|
|
152
|
+
print("请求过于频繁,请稍后。")
|
|
153
|
+
except (ConnectionError, TimeoutError):
|
|
154
|
+
print("网络问题。")
|
|
155
|
+
except APIError as e:
|
|
156
|
+
print(f"API 返回了 {e.status_code}")
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
所有异常均继承自 `LLMError`。
|
|
160
|
+
|
|
161
|
+
## 流式输出
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
with agent.session() as s:
|
|
165
|
+
for token in s.chat("给我讲个故事", stream=True):
|
|
166
|
+
print(token, end="", flush=True)
|
|
167
|
+
# token 会被自动累积并追加到历史中
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
## 许可证
|
|
171
|
+
|
|
172
|
+
Apache 2.0 —— 详见 [LICENSE](LICENSE)。
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
# Aigent
|
|
2
|
+
|
|
3
|
+
A progressive-disclosure Python library for LLM APIs. Start with a one-liner, scale to full control — all in idiomatic Python.
|
|
4
|
+
|
|
5
|
+
```python
|
|
6
|
+
from aigent import Aigent
|
|
7
|
+
|
|
8
|
+
agent = Aigent(api_type="openai")
|
|
9
|
+
with agent.session() as s:
|
|
10
|
+
print(s.chat("Hello!"))
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Installation
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install aigent
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Requires Python 3.10+. The only external dependency is [httpx](https://www.pypi.org/project/httpx/).
|
|
20
|
+
|
|
21
|
+
## Quick Start
|
|
22
|
+
|
|
23
|
+
### Tier 1 — Chat
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from aigent import Aigent
|
|
27
|
+
|
|
28
|
+
# Zero-config: reads OPENAI_API_KEY / ANTHROPIC_API_KEY from env
|
|
29
|
+
agent = Aigent(api_type="anthropic")
|
|
30
|
+
|
|
31
|
+
with agent.session(system="You are a professional translator.") as s:
|
|
32
|
+
result = s.chat("Translate to English: 你好世界")
|
|
33
|
+
print(result)
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
### Tier 2 — Tools
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from aigent import Aigent, tool
|
|
40
|
+
|
|
41
|
+
@tool
|
|
42
|
+
def get_weather(city: str, unit: str = "celsius") -> str:
|
|
43
|
+
"""Get current weather for a city."""
|
|
44
|
+
# In real code, call a weather API here
|
|
45
|
+
return f"{city}: 22°{unit[0].upper()}"
|
|
46
|
+
|
|
47
|
+
agent = Aigent(api_type="openai")
|
|
48
|
+
with agent.session(tools=[get_weather]) as s:
|
|
49
|
+
reply = s.chat("What's the weather in Beijing?")
|
|
50
|
+
print(reply)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The `@tool` decorator auto-generates JSON Schema from your function signature and docstring — no manual schema writing.
|
|
54
|
+
|
|
55
|
+
### Tier 3 — Full Control
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from aigent import Aigent, Message
|
|
59
|
+
|
|
60
|
+
agent = Aigent(api_type="anthropic")
|
|
61
|
+
|
|
62
|
+
# Manually orchestrate messages
|
|
63
|
+
resp = agent.raw(
|
|
64
|
+
[Message.system("You are helpful."), Message.user("Hi!")],
|
|
65
|
+
max_tokens=200,
|
|
66
|
+
temperature=0.7,
|
|
67
|
+
)
|
|
68
|
+
print(resp.content) # str
|
|
69
|
+
print(resp.usage) # Usage(prompt_tokens=..., completion_tokens=...)
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Session & Role API
|
|
73
|
+
|
|
74
|
+
```python
|
|
75
|
+
agent = Aigent()
|
|
76
|
+
|
|
77
|
+
with agent.session() as s:
|
|
78
|
+
# Chat as user (default)
|
|
79
|
+
s.chat("Hello")
|
|
80
|
+
|
|
81
|
+
# Chat as assistant
|
|
82
|
+
s.chat("I'm doing great!", role="assistant")
|
|
83
|
+
|
|
84
|
+
# Streaming
|
|
85
|
+
for token in s.chat("Write a poem", stream=True):
|
|
86
|
+
print(token, end="")
|
|
87
|
+
|
|
88
|
+
# Insert without sending — build context gradually
|
|
89
|
+
s.user.insert("I want to learn Python.")
|
|
90
|
+
s.assistant.insert("Great choice! Where would you like to start?")
|
|
91
|
+
reply = s.chat() # sends existing history without adding new message
|
|
92
|
+
|
|
93
|
+
# Role objects
|
|
94
|
+
s.system.insert("You are a Python expert.")
|
|
95
|
+
s.role("tool").insert('{"result": 42}', tool_call_id="call_abc")
|
|
96
|
+
|
|
97
|
+
# History management
|
|
98
|
+
print(s.history) # read-only list of messages
|
|
99
|
+
s.clear() # reset the conversation
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Supported Backends
|
|
103
|
+
|
|
104
|
+
| `api_type` | Backend | Default Model |
|
|
105
|
+
|------------|---------|---------------|
|
|
106
|
+
| `"openai"` | OpenAI Chat Completions | `gpt-4o` |
|
|
107
|
+
| `"anthropic"` | Anthropic Messages | `claude-sonnet-4-6` |
|
|
108
|
+
|
|
109
|
+
OpenAI-compatible services (Azure, local LLMs, etc.) work via `api_type="openai"` with a custom `base_url`.
|
|
110
|
+
|
|
111
|
+
## Configuration
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
agent = Aigent(
|
|
115
|
+
api_type="openai",
|
|
116
|
+
api_key="sk-...", # or OPENAI_API_KEY env var
|
|
117
|
+
base_url="https://api.openai.com/v1", # or OPENAI_BASE_URL env var
|
|
118
|
+
model="gpt-4o", # or OPENAI_MODEL env var
|
|
119
|
+
system="You are helpful.", # default system prompt for all sessions
|
|
120
|
+
timeout=30.0,
|
|
121
|
+
max_retries=3,
|
|
122
|
+
)
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Environment variables per backend:
|
|
126
|
+
|
|
127
|
+
| Env | OpenAI | Anthropic |
|
|
128
|
+
|-----|--------|-----------|
|
|
129
|
+
| API key | `OPENAI_API_KEY` | `ANTHROPIC_API_KEY` |
|
|
130
|
+
| Base URL | `OPENAI_BASE_URL` | `ANTHROPIC_BASE_URL` |
|
|
131
|
+
| Model | `OPENAI_MODEL` | `ANTHROPIC_MODEL` |
|
|
132
|
+
|
|
133
|
+
## Error Handling
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
from aigent import (
|
|
137
|
+
Aigent,
|
|
138
|
+
AuthenticationError,
|
|
139
|
+
RateLimitError,
|
|
140
|
+
APIError,
|
|
141
|
+
ConnectionError,
|
|
142
|
+
TimeoutError,
|
|
143
|
+
)
|
|
144
|
+
|
|
145
|
+
agent = Aigent()
|
|
146
|
+
try:
|
|
147
|
+
with agent.session() as s:
|
|
148
|
+
s.chat("Hello")
|
|
149
|
+
except AuthenticationError:
|
|
150
|
+
print("Check your API key.")
|
|
151
|
+
except RateLimitError:
|
|
152
|
+
print("Slow down.")
|
|
153
|
+
except (ConnectionError, TimeoutError):
|
|
154
|
+
print("Network issue.")
|
|
155
|
+
except APIError as e:
|
|
156
|
+
print(f"API returned {e.status_code}")
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
All exceptions inherit from `LLMError`.
|
|
160
|
+
|
|
161
|
+
## Streaming
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
with agent.session() as s:
|
|
165
|
+
for token in s.chat("Tell me a story", stream=True):
|
|
166
|
+
print(token, end="", flush=True)
|
|
167
|
+
# Tokens are also accumulated and auto-appended to history
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
## License
|
|
171
|
+
|
|
172
|
+
Apache 2.0 — see [LICENSE](LICENSE).
|