gamecrafters-agent 0.0.1__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.
- gamecrafters_agent-0.0.1/PKG-INFO +17 -0
- gamecrafters_agent-0.0.1/README.md +0 -0
- gamecrafters_agent-0.0.1/pyproject.toml +26 -0
- gamecrafters_agent-0.0.1/src/agent/__init__.py +63 -0
- gamecrafters_agent-0.0.1/src/agent/agent.py +252 -0
- gamecrafters_agent-0.0.1/src/agent/anthropic/__init__.py +13 -0
- gamecrafters_agent-0.0.1/src/agent/anthropic/llm.py +78 -0
- gamecrafters_agent-0.0.1/src/agent/anthropic/messages.py +51 -0
- gamecrafters_agent-0.0.1/src/agent/anthropic/parsers.py +20 -0
- gamecrafters_agent-0.0.1/src/agent/anthropic/tooling.py +11 -0
- gamecrafters_agent-0.0.1/src/agent/anthropic/usages.py +35 -0
- gamecrafters_agent-0.0.1/src/agent/deepseek/__init__.py +13 -0
- gamecrafters_agent-0.0.1/src/agent/deepseek/llm.py +105 -0
- gamecrafters_agent-0.0.1/src/agent/deepseek/messages.py +43 -0
- gamecrafters_agent-0.0.1/src/agent/deepseek/parsers.py +23 -0
- gamecrafters_agent-0.0.1/src/agent/deepseek/tooling.py +14 -0
- gamecrafters_agent-0.0.1/src/agent/deepseek/usages.py +29 -0
- gamecrafters_agent-0.0.1/src/agent/documents.py +75 -0
- gamecrafters_agent-0.0.1/src/agent/evaluation.py +383 -0
- gamecrafters_agent-0.0.1/src/agent/execution.py +33 -0
- gamecrafters_agent-0.0.1/src/agent/google/__init__.py +13 -0
- gamecrafters_agent-0.0.1/src/agent/google/llm.py +103 -0
- gamecrafters_agent-0.0.1/src/agent/google/messages.py +41 -0
- gamecrafters_agent-0.0.1/src/agent/google/parsers.py +20 -0
- gamecrafters_agent-0.0.1/src/agent/google/tooling.py +12 -0
- gamecrafters_agent-0.0.1/src/agent/google/usages.py +32 -0
- gamecrafters_agent-0.0.1/src/agent/llm.py +29 -0
- gamecrafters_agent-0.0.1/src/agent/loaders.py +34 -0
- gamecrafters_agent-0.0.1/src/agent/memory.py +308 -0
- gamecrafters_agent-0.0.1/src/agent/messages.py +31 -0
- gamecrafters_agent-0.0.1/src/agent/openai/__init__.py +13 -0
- gamecrafters_agent-0.0.1/src/agent/openai/llm.py +77 -0
- gamecrafters_agent-0.0.1/src/agent/openai/messages.py +31 -0
- gamecrafters_agent-0.0.1/src/agent/openai/parsers.py +22 -0
- gamecrafters_agent-0.0.1/src/agent/openai/tooling.py +13 -0
- gamecrafters_agent-0.0.1/src/agent/openai/usages.py +30 -0
- gamecrafters_agent-0.0.1/src/agent/parsers.py +19 -0
- gamecrafters_agent-0.0.1/src/agent/py.typed +0 -0
- gamecrafters_agent-0.0.1/src/agent/rag/__init__.py +12 -0
- gamecrafters_agent-0.0.1/src/agent/rag/context.py +42 -0
- gamecrafters_agent-0.0.1/src/agent/rag/pipeline.py +90 -0
- gamecrafters_agent-0.0.1/src/agent/rag/retriever.py +43 -0
- gamecrafters_agent-0.0.1/src/agent/state_machine.py +319 -0
- gamecrafters_agent-0.0.1/src/agent/tooling.py +77 -0
- gamecrafters_agent-0.0.1/src/agent/usages.py +8 -0
- gamecrafters_agent-0.0.1/src/agent/vector_store/__init__.py +10 -0
- gamecrafters_agent-0.0.1/src/agent/vector_store/base.py +41 -0
- gamecrafters_agent-0.0.1/src/agent/vector_store/chroma.py +183 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: gamecrafters-agent
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary:
|
|
5
|
+
Author: GameCrafters
|
|
6
|
+
Author-email: GameCrafters <support@gamecrafters.io>
|
|
7
|
+
Requires-Dist: anthropic>=1.0.0
|
|
8
|
+
Requires-Dist: chromadb>=1.5.9
|
|
9
|
+
Requires-Dist: google-genai>=2.25.0
|
|
10
|
+
Requires-Dist: httpx2>=2.12.0
|
|
11
|
+
Requires-Dist: openai>=3.3.1
|
|
12
|
+
Requires-Dist: pdfplumber>=0.11.10
|
|
13
|
+
Requires-Dist: pydantic>=2.13.4
|
|
14
|
+
Requires-Dist: pytest>=9.1.1
|
|
15
|
+
Requires-Python: >=3.14
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
|
|
File without changes
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "gamecrafters-agent"
|
|
3
|
+
version = "0.0.1"
|
|
4
|
+
description = ""
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
authors = [
|
|
7
|
+
{ name = "GameCrafters", email = "support@gamecrafters.io" }
|
|
8
|
+
]
|
|
9
|
+
requires-python = ">=3.14"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"anthropic>=1.0.0",
|
|
12
|
+
"chromadb>=1.5.9",
|
|
13
|
+
"google-genai>=2.25.0",
|
|
14
|
+
"httpx2>=2.12.0",
|
|
15
|
+
"openai>=3.3.1",
|
|
16
|
+
"pdfplumber>=0.11.10",
|
|
17
|
+
"pydantic>=2.13.4",
|
|
18
|
+
"pytest>=9.1.1",
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[build-system]
|
|
22
|
+
requires = ["uv_build>=0.10.4,<0.11.0"]
|
|
23
|
+
build-backend = "uv_build"
|
|
24
|
+
|
|
25
|
+
[tool.uv.build-backend]
|
|
26
|
+
module-name = "agent"
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
from .agent import Agent, AgentState, PROVIDERS, parse_model
|
|
2
|
+
from .documents import Corpus, Document
|
|
3
|
+
from .evaluation import AgentEvaluator, EvaluationResult, JudgeEvaluation, QualityControlMetrics, SystemMetrics, TaskCompletionMetrics, TestCase, ToolInteractionMetrics
|
|
4
|
+
from .execution import RunResult, Runner
|
|
5
|
+
from .llm import LLM, convert_input
|
|
6
|
+
from .loaders import PDFLoader
|
|
7
|
+
from .memory import DEFAULT_NAMESPACE, DEFAULT_SESSION, LongTermMemory, MemoryFragment, MemorySearchResult, SessionNotFoundError, ShortTermMemory, TimestampFilter
|
|
8
|
+
from .messages import AnyMessage, AssistantMessage, BaseMessage, SystemMessage, ToolCall, ToolMessage, UserMessage
|
|
9
|
+
from .parsers import OutputParser, PydanticOutputParser, TextOutputParser
|
|
10
|
+
from .state_machine import EntryPoint, Run, Snapshot, StateMachine, StateMachineError, Step, Termination, Transition
|
|
11
|
+
from .tooling import Tool, tool
|
|
12
|
+
from .usages import TokenUsage
|
|
13
|
+
|
|
14
|
+
__all__ = (
|
|
15
|
+
"Agent",
|
|
16
|
+
"AgentState",
|
|
17
|
+
"PROVIDERS",
|
|
18
|
+
"parse_model",
|
|
19
|
+
"Corpus",
|
|
20
|
+
"Document",
|
|
21
|
+
"AgentEvaluator",
|
|
22
|
+
"EvaluationResult",
|
|
23
|
+
"JudgeEvaluation",
|
|
24
|
+
"QualityControlMetrics",
|
|
25
|
+
"SystemMetrics",
|
|
26
|
+
"TaskCompletionMetrics",
|
|
27
|
+
"TestCase",
|
|
28
|
+
"ToolInteractionMetrics",
|
|
29
|
+
"RunResult",
|
|
30
|
+
"Runner",
|
|
31
|
+
"LLM",
|
|
32
|
+
"convert_input",
|
|
33
|
+
"PDFLoader",
|
|
34
|
+
"DEFAULT_NAMESPACE",
|
|
35
|
+
"DEFAULT_SESSION",
|
|
36
|
+
"LongTermMemory",
|
|
37
|
+
"MemoryFragment",
|
|
38
|
+
"MemorySearchResult",
|
|
39
|
+
"SessionNotFoundError",
|
|
40
|
+
"ShortTermMemory",
|
|
41
|
+
"TimestampFilter",
|
|
42
|
+
"AnyMessage",
|
|
43
|
+
"AssistantMessage",
|
|
44
|
+
"BaseMessage",
|
|
45
|
+
"SystemMessage",
|
|
46
|
+
"ToolCall",
|
|
47
|
+
"ToolMessage",
|
|
48
|
+
"UserMessage",
|
|
49
|
+
"OutputParser",
|
|
50
|
+
"PydanticOutputParser",
|
|
51
|
+
"TextOutputParser",
|
|
52
|
+
"EntryPoint",
|
|
53
|
+
"Run",
|
|
54
|
+
"Snapshot",
|
|
55
|
+
"StateMachine",
|
|
56
|
+
"StateMachineError",
|
|
57
|
+
"Step",
|
|
58
|
+
"Termination",
|
|
59
|
+
"Transition",
|
|
60
|
+
"Tool",
|
|
61
|
+
"tool",
|
|
62
|
+
"TokenUsage",
|
|
63
|
+
)
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from pydantic import BaseModel
|
|
3
|
+
from typing import Any
|
|
4
|
+
from .anthropic.llm import LLM as AnthropicLLM
|
|
5
|
+
from .deepseek.llm import LLM as DeepSeekLLM
|
|
6
|
+
from .google.llm import LLM as GoogleLLM
|
|
7
|
+
from .llm import LLM
|
|
8
|
+
from .memory import DEFAULT_SESSION, ShortTermMemory
|
|
9
|
+
from .messages import AssistantMessage, SystemMessage, ToolMessage, UserMessage
|
|
10
|
+
from .openai.llm import LLM as OpenAILLM
|
|
11
|
+
from .state_machine import EntryPoint, StateMachine, StateMachineError, Step, Termination
|
|
12
|
+
from .tooling import Tool
|
|
13
|
+
from .usages import TokenUsage
|
|
14
|
+
|
|
15
|
+
# Map of the supported providers to their LLM implementation
|
|
16
|
+
PROVIDERS: dict[str, type[LLM]] = {
|
|
17
|
+
"openai": OpenAILLM,
|
|
18
|
+
"anthropic": AnthropicLLM,
|
|
19
|
+
"deepseek": DeepSeekLLM,
|
|
20
|
+
"google": GoogleLLM,
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
def parse_model(model: str) -> tuple[str, str]:
|
|
24
|
+
"""
|
|
25
|
+
Split a prefixed model identifier into its provider and model name
|
|
26
|
+
|
|
27
|
+
Args:
|
|
28
|
+
model: Name/identifier of the model, in "<provider>/<model>" form
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
The provider name and the model name to send to that provider
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
provider, separator, name = model.partition("/")
|
|
35
|
+
|
|
36
|
+
if not separator or not name:
|
|
37
|
+
raise ValueError(f"Invalid model {model}. Expected '<provider>/<model>'.")
|
|
38
|
+
|
|
39
|
+
if provider not in PROVIDERS:
|
|
40
|
+
raise ValueError(f"Invalid provider {provider}.")
|
|
41
|
+
|
|
42
|
+
return provider, name
|
|
43
|
+
|
|
44
|
+
# Define the state model
|
|
45
|
+
class AgentState(BaseModel):
|
|
46
|
+
input: str # The current input being processed
|
|
47
|
+
instructions: str | None = None # System instructions for the agent
|
|
48
|
+
messages: list[Any] = [] # List of conversation messages
|
|
49
|
+
current_tool_calls: list[Any] | None = None # Current pending tool calls
|
|
50
|
+
iteration: int = 0 # Number of LLM iterations completed
|
|
51
|
+
usage: TokenUsage = TokenUsage() # Tokens used across every iteration so far
|
|
52
|
+
|
|
53
|
+
class Agent:
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
name: str,
|
|
57
|
+
model: str,
|
|
58
|
+
instructions: str,
|
|
59
|
+
tools: list[Tool] | None = None,
|
|
60
|
+
temperature: float = 0.7,
|
|
61
|
+
max_iterations: int = 10,
|
|
62
|
+
max_tokens: int | None = None,
|
|
63
|
+
base_url: str | None = None,
|
|
64
|
+
api_key: str | None = None,
|
|
65
|
+
):
|
|
66
|
+
"""
|
|
67
|
+
Initialize an Agent instance
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
name: Name/identifier of the agent
|
|
71
|
+
model: Name/identifier of the LLM model to use, as "<provider>/<model>"
|
|
72
|
+
instructions: System instructions for the agent
|
|
73
|
+
tools: Optional list of tools available to the agent
|
|
74
|
+
temperature: Temperature parameter for LLM (default: 0.7)
|
|
75
|
+
max_iterations: Maximum number of LLM iterations before terminating (default: 10)
|
|
76
|
+
max_tokens: Optional maximum number of tokens the LLM may produce
|
|
77
|
+
base_url: Optional base URL for the LLM client
|
|
78
|
+
api_key: Optional API key for the LLM client
|
|
79
|
+
"""
|
|
80
|
+
self.name = name
|
|
81
|
+
self.instructions = instructions
|
|
82
|
+
self.tools = tools if tools else []
|
|
83
|
+
self.provider, self.model = parse_model(model)
|
|
84
|
+
self.temperature = temperature
|
|
85
|
+
self.max_iterations = max_iterations
|
|
86
|
+
self.max_tokens = max_tokens
|
|
87
|
+
self.base_url = base_url
|
|
88
|
+
self.api_key = api_key
|
|
89
|
+
self.memory = ShortTermMemory()
|
|
90
|
+
|
|
91
|
+
# Initialize state machine
|
|
92
|
+
self.workflow = self._create_state_machine()
|
|
93
|
+
|
|
94
|
+
def _prepare_messages_step(self, state: AgentState) -> dict:
|
|
95
|
+
"""Step logic: Prepare messages for LLM consumption"""
|
|
96
|
+
|
|
97
|
+
# Only open with the instructions when there is no history to continue
|
|
98
|
+
messages = state.messages or [SystemMessage(content=state.instructions)]
|
|
99
|
+
|
|
100
|
+
return {
|
|
101
|
+
"messages": messages + [UserMessage(content=state.input)]
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async def _llm_step(self, state: AgentState) -> dict:
|
|
105
|
+
"""Step logic: Process the current state through the LLM"""
|
|
106
|
+
|
|
107
|
+
# Initialize the LLM of the configured provider
|
|
108
|
+
llm = PROVIDERS[self.provider](
|
|
109
|
+
model=self.model,
|
|
110
|
+
temperature=self.temperature,
|
|
111
|
+
tools=self.tools,
|
|
112
|
+
max_tokens=self.max_tokens,
|
|
113
|
+
base_url=self.base_url,
|
|
114
|
+
api_key=self.api_key,
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
response = await llm.invoke(state.messages)
|
|
118
|
+
tool_calls = response.tool_calls if response.tool_calls else None
|
|
119
|
+
|
|
120
|
+
# Create assistant message with content, tool calls and the usage the call reported,
|
|
121
|
+
# keeping the reasoning that DeepSeek's thinking mode wants back on later calls and
|
|
122
|
+
# the steps that Gemini's stateless history has to replay as they were received
|
|
123
|
+
assistant_message = AssistantMessage(
|
|
124
|
+
content=response.content,
|
|
125
|
+
reasoning_content=response.reasoning_content,
|
|
126
|
+
steps=response.steps,
|
|
127
|
+
tool_calls=tool_calls,
|
|
128
|
+
usage=response.usage,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
# A run loops back through the LLM after every tool call, so usage accumulates
|
|
132
|
+
usage = response.usage or TokenUsage()
|
|
133
|
+
|
|
134
|
+
return {
|
|
135
|
+
"messages": state.messages + [assistant_message],
|
|
136
|
+
"current_tool_calls": tool_calls,
|
|
137
|
+
"iteration": state.iteration + 1,
|
|
138
|
+
"usage": TokenUsage(
|
|
139
|
+
input_tokens=state.usage.input_tokens + usage.input_tokens,
|
|
140
|
+
cached_tokens=state.usage.cached_tokens + usage.cached_tokens,
|
|
141
|
+
output_tokens=state.usage.output_tokens + usage.output_tokens,
|
|
142
|
+
total_tokens=state.usage.total_tokens + usage.total_tokens,
|
|
143
|
+
),
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
def _tool_step(self, state: AgentState) -> dict:
|
|
147
|
+
"""Step logic: Execute any pending tool calls"""
|
|
148
|
+
tool_messages = []
|
|
149
|
+
|
|
150
|
+
for call in state.current_tool_calls or []:
|
|
151
|
+
# Find the matching tool
|
|
152
|
+
tool = next((t for t in self.tools if t.name == call.function_name), None)
|
|
153
|
+
if tool:
|
|
154
|
+
result = str(tool(**call.args))
|
|
155
|
+
tool_messages.append(
|
|
156
|
+
ToolMessage(
|
|
157
|
+
content=json.dumps(result),
|
|
158
|
+
tool_call_id=call.tool_call_id,
|
|
159
|
+
name=call.function_name,
|
|
160
|
+
)
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
# Clear tool calls and add results to messages
|
|
164
|
+
return {
|
|
165
|
+
"messages": state.messages + tool_messages,
|
|
166
|
+
"current_tool_calls": None
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
def _create_state_machine(self) -> StateMachine[AgentState]:
|
|
170
|
+
"""Create the internal state machine for the agent"""
|
|
171
|
+
machine = StateMachine[AgentState](AgentState)
|
|
172
|
+
|
|
173
|
+
# Create steps
|
|
174
|
+
entry = EntryPoint[AgentState]()
|
|
175
|
+
prepare_messages = Step[AgentState]("prepare_messages", self._prepare_messages_step)
|
|
176
|
+
invoke_llm = Step[AgentState]("invoke_llm", self._llm_step)
|
|
177
|
+
execute_tools = Step[AgentState]("execute_tools", self._tool_step)
|
|
178
|
+
terminate = Termination[AgentState]()
|
|
179
|
+
|
|
180
|
+
machine.add_steps([entry, prepare_messages, invoke_llm, execute_tools, terminate])
|
|
181
|
+
|
|
182
|
+
# Add transitions
|
|
183
|
+
machine.connect(entry, prepare_messages)
|
|
184
|
+
machine.connect(prepare_messages, invoke_llm)
|
|
185
|
+
|
|
186
|
+
def check_tool_calls(state: AgentState) -> Step[AgentState] | str:
|
|
187
|
+
"""Transition logic: Keep going while the LLM calls tools and the iteration budget holds"""
|
|
188
|
+
if state.current_tool_calls and state.iteration < self.max_iterations:
|
|
189
|
+
return execute_tools
|
|
190
|
+
|
|
191
|
+
return terminate
|
|
192
|
+
|
|
193
|
+
machine.connect(invoke_llm, [execute_tools, terminate], check_tool_calls)
|
|
194
|
+
machine.connect(execute_tools, invoke_llm) # Go back to the LLM after tool execution
|
|
195
|
+
|
|
196
|
+
return machine
|
|
197
|
+
|
|
198
|
+
async def invoke(self, input: str, session_id: str | None = None) -> AgentState:
|
|
199
|
+
"""
|
|
200
|
+
Run the agent on an input
|
|
201
|
+
|
|
202
|
+
Args:
|
|
203
|
+
input: The user's input to process
|
|
204
|
+
session_id: Optional session to run in (uses the default if None)
|
|
205
|
+
|
|
206
|
+
Returns:
|
|
207
|
+
The final state after processing
|
|
208
|
+
"""
|
|
209
|
+
|
|
210
|
+
session_id = session_id or DEFAULT_SESSION
|
|
211
|
+
self.memory.create_session(session_id)
|
|
212
|
+
|
|
213
|
+
# Carry on from the messages the previous run in this session ended with
|
|
214
|
+
previous = self.memory.get_last_object(session_id)
|
|
215
|
+
|
|
216
|
+
run = await self.workflow.run(AgentState(
|
|
217
|
+
input=input,
|
|
218
|
+
instructions=self.instructions,
|
|
219
|
+
messages=previous.messages if previous else [],
|
|
220
|
+
))
|
|
221
|
+
|
|
222
|
+
state = run.get_final_state()
|
|
223
|
+
|
|
224
|
+
if state is None:
|
|
225
|
+
raise StateMachineError("Workflow finished without producing a state")
|
|
226
|
+
|
|
227
|
+
self.memory.push(state, session_id)
|
|
228
|
+
|
|
229
|
+
return state
|
|
230
|
+
|
|
231
|
+
def get_session_states(self, session_id: str | None = None) -> list[AgentState]:
|
|
232
|
+
"""
|
|
233
|
+
Get the final state of every run in a session
|
|
234
|
+
|
|
235
|
+
Args:
|
|
236
|
+
session_id: Optional session to read (uses the default if None)
|
|
237
|
+
|
|
238
|
+
Returns:
|
|
239
|
+
The states in the session, oldest first
|
|
240
|
+
"""
|
|
241
|
+
|
|
242
|
+
return self.memory.get_all_objects(session_id)
|
|
243
|
+
|
|
244
|
+
def reset_session(self, session_id: str | None = None) -> None:
|
|
245
|
+
"""
|
|
246
|
+
Forget the history of a session, or of every session at once
|
|
247
|
+
|
|
248
|
+
Args:
|
|
249
|
+
session_id: Optional session to reset (resets all sessions if None)
|
|
250
|
+
"""
|
|
251
|
+
|
|
252
|
+
self.memory.reset(session_id)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from .llm import LLM
|
|
2
|
+
from .messages import convert_messages
|
|
3
|
+
from .parsers import ToolOutputParser
|
|
4
|
+
from .tooling import convert_tool
|
|
5
|
+
from .usages import convert_usage
|
|
6
|
+
|
|
7
|
+
__all__ = (
|
|
8
|
+
"LLM",
|
|
9
|
+
"convert_messages",
|
|
10
|
+
"ToolOutputParser",
|
|
11
|
+
"convert_tool",
|
|
12
|
+
"convert_usage",
|
|
13
|
+
)
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import httpx2
|
|
2
|
+
from anthropic import AsyncAnthropic
|
|
3
|
+
from pydantic import BaseModel
|
|
4
|
+
from typing import Any
|
|
5
|
+
from ..llm import convert_input
|
|
6
|
+
from ..messages import AssistantMessage, BaseMessage
|
|
7
|
+
from ..tooling import Tool
|
|
8
|
+
from .messages import convert_messages
|
|
9
|
+
from .parsers import ToolOutputParser
|
|
10
|
+
from .tooling import convert_tool
|
|
11
|
+
from .usages import convert_usage
|
|
12
|
+
|
|
13
|
+
DEFAULT_MAX_TOKENS = 16000
|
|
14
|
+
|
|
15
|
+
class LLM:
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
model: str,
|
|
19
|
+
temperature: float = 0.0,
|
|
20
|
+
tools: list[Tool] | None = None,
|
|
21
|
+
max_tokens: int | None = None,
|
|
22
|
+
base_url: str | None = None,
|
|
23
|
+
api_key: str | None = None,
|
|
24
|
+
):
|
|
25
|
+
self.model = model
|
|
26
|
+
self.temperature = temperature
|
|
27
|
+
self.max_tokens = max_tokens
|
|
28
|
+
self.client = AsyncAnthropic(
|
|
29
|
+
base_url=base_url,
|
|
30
|
+
api_key=api_key,
|
|
31
|
+
timeout=httpx2.Timeout(3600.0)
|
|
32
|
+
)
|
|
33
|
+
self.tools: dict[str, Tool] = {tool.name: tool for tool in (tools or [])}
|
|
34
|
+
|
|
35
|
+
def register_tool(self, tool: Tool) -> None:
|
|
36
|
+
self.tools[tool.name] = tool
|
|
37
|
+
|
|
38
|
+
def _build_payload(self, messages: list[BaseMessage]) -> dict[str, Any]:
|
|
39
|
+
instructions, converted = convert_messages(messages)
|
|
40
|
+
|
|
41
|
+
# Sampling parameters are rejected by current Claude models, so
|
|
42
|
+
# temperature is intentionally left out of the payload
|
|
43
|
+
payload = {
|
|
44
|
+
"model": self.model,
|
|
45
|
+
"max_tokens": self.max_tokens or DEFAULT_MAX_TOKENS,
|
|
46
|
+
"messages": converted,
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if instructions is not None:
|
|
50
|
+
payload["system"] = instructions
|
|
51
|
+
|
|
52
|
+
if self.tools:
|
|
53
|
+
payload["tools"] = [convert_tool(tool) for tool in self.tools.values()]
|
|
54
|
+
payload["tool_choice"] = {"type": "auto"}
|
|
55
|
+
|
|
56
|
+
return payload
|
|
57
|
+
|
|
58
|
+
def _convert_response(self, response: Any) -> AssistantMessage:
|
|
59
|
+
return AssistantMessage(
|
|
60
|
+
content="".join(block.text for block in response.content if block.type == "text"),
|
|
61
|
+
tool_calls=ToolOutputParser().parse(response) or None,
|
|
62
|
+
usage=convert_usage(response),
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
async def invoke(
|
|
66
|
+
self,
|
|
67
|
+
input: str | BaseMessage | list[BaseMessage],
|
|
68
|
+
response_format: type[BaseModel] | None = None,
|
|
69
|
+
) -> AssistantMessage:
|
|
70
|
+
payload = self._build_payload(convert_input(input))
|
|
71
|
+
|
|
72
|
+
if response_format is not None:
|
|
73
|
+
payload["output_format"] = response_format
|
|
74
|
+
response = await self.client.messages.parse(**payload)
|
|
75
|
+
else:
|
|
76
|
+
response = await self.client.messages.create(**payload)
|
|
77
|
+
|
|
78
|
+
return self._convert_response(response)
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
from ..messages import AssistantMessage, BaseMessage, SystemMessage, ToolMessage
|
|
3
|
+
|
|
4
|
+
def convert_messages(messages: list[BaseMessage]) -> tuple[str | None, list[dict[str, Any]]]:
|
|
5
|
+
instructions = []
|
|
6
|
+
converted = []
|
|
7
|
+
tool_results = []
|
|
8
|
+
|
|
9
|
+
# Parallel tool results must arrive as blocks of a single user message
|
|
10
|
+
def flush_tool_results() -> None:
|
|
11
|
+
if tool_results:
|
|
12
|
+
converted.append({"role": "user", "content": list(tool_results)})
|
|
13
|
+
tool_results.clear()
|
|
14
|
+
|
|
15
|
+
for message in messages:
|
|
16
|
+
if isinstance(message, SystemMessage):
|
|
17
|
+
instructions.append(message.content or "")
|
|
18
|
+
continue
|
|
19
|
+
|
|
20
|
+
if isinstance(message, ToolMessage):
|
|
21
|
+
tool_results.append({
|
|
22
|
+
"type": "tool_result",
|
|
23
|
+
"tool_use_id": message.tool_call_id,
|
|
24
|
+
"content": message.content or "",
|
|
25
|
+
})
|
|
26
|
+
continue
|
|
27
|
+
|
|
28
|
+
flush_tool_results()
|
|
29
|
+
|
|
30
|
+
if isinstance(message, AssistantMessage):
|
|
31
|
+
content = []
|
|
32
|
+
|
|
33
|
+
if message.content:
|
|
34
|
+
content.append({"type": "text", "text": message.content})
|
|
35
|
+
|
|
36
|
+
for tool_call in message.tool_calls or []:
|
|
37
|
+
content.append({
|
|
38
|
+
"type": "tool_use",
|
|
39
|
+
"id": tool_call.tool_call_id,
|
|
40
|
+
"name": tool_call.function_name,
|
|
41
|
+
"input": tool_call.args,
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
if content:
|
|
45
|
+
converted.append({"role": "assistant", "content": content})
|
|
46
|
+
else:
|
|
47
|
+
converted.append({"role": "user", "content": message.content or ""})
|
|
48
|
+
|
|
49
|
+
flush_tool_results()
|
|
50
|
+
|
|
51
|
+
return "\n\n".join(instructions) or None, converted
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
from pydantic import BaseModel
|
|
2
|
+
from typing import Any
|
|
3
|
+
from ..messages import ToolCall
|
|
4
|
+
|
|
5
|
+
class ToolOutputParser(BaseModel):
|
|
6
|
+
def parse(self, response: Any) -> list[ToolCall]:
|
|
7
|
+
return [
|
|
8
|
+
self._parse_tool_call(block)
|
|
9
|
+
for block in response.content
|
|
10
|
+
if block.type == "tool_use"
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
def _parse_tool_call(self, tool_call: Any) -> ToolCall:
|
|
14
|
+
call = tool_call if isinstance(tool_call, dict) else tool_call.model_dump(exclude_none=True)
|
|
15
|
+
|
|
16
|
+
return ToolCall(
|
|
17
|
+
tool_call_id=call.get("id"),
|
|
18
|
+
function_name=call.get("name"),
|
|
19
|
+
args=call.get("input") or {},
|
|
20
|
+
)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
from ..tooling import Tool
|
|
3
|
+
|
|
4
|
+
def convert_tool(tool: Tool) -> dict[str, Any]:
|
|
5
|
+
schema = {
|
|
6
|
+
"name": tool.name,
|
|
7
|
+
"description": tool.description,
|
|
8
|
+
"input_schema": tool.schema(),
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
return {key: value for key, value in schema.items() if value is not None}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
from ..usages import TokenUsage
|
|
3
|
+
|
|
4
|
+
def convert_usage(response: Any) -> TokenUsage | None:
|
|
5
|
+
"""
|
|
6
|
+
Read the token usage off a response
|
|
7
|
+
|
|
8
|
+
Args:
|
|
9
|
+
response: The raw response the provider returned
|
|
10
|
+
|
|
11
|
+
Returns:
|
|
12
|
+
The tokens the call consumed, or None if the response reported no usage
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
usage = getattr(response, "usage", None)
|
|
16
|
+
|
|
17
|
+
if not usage:
|
|
18
|
+
return None
|
|
19
|
+
|
|
20
|
+
fields = usage if isinstance(usage, dict) else usage.model_dump(exclude_none=True)
|
|
21
|
+
|
|
22
|
+
# Claude reports cache traffic alongside input_tokens rather than within it, so
|
|
23
|
+
# fold both back in to keep cached_tokens a share of the input
|
|
24
|
+
cached_tokens = fields.get("cache_read_input_tokens", 0)
|
|
25
|
+
cache_writes = fields.get("cache_creation_input_tokens", 0)
|
|
26
|
+
input_tokens = fields.get("input_tokens", 0) + cached_tokens + cache_writes
|
|
27
|
+
output_tokens = fields.get("output_tokens", 0)
|
|
28
|
+
|
|
29
|
+
return TokenUsage(
|
|
30
|
+
input_tokens=input_tokens,
|
|
31
|
+
cached_tokens=cached_tokens,
|
|
32
|
+
output_tokens=output_tokens,
|
|
33
|
+
# Claude reports no total, so derive it the way the other providers report theirs
|
|
34
|
+
total_tokens=input_tokens + output_tokens,
|
|
35
|
+
)
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
from .llm import LLM
|
|
2
|
+
from .messages import convert_messages
|
|
3
|
+
from .parsers import ToolOutputParser
|
|
4
|
+
from .tooling import convert_tool
|
|
5
|
+
from .usages import convert_usage
|
|
6
|
+
|
|
7
|
+
__all__ = (
|
|
8
|
+
"LLM",
|
|
9
|
+
"convert_messages",
|
|
10
|
+
"ToolOutputParser",
|
|
11
|
+
"convert_tool",
|
|
12
|
+
"convert_usage",
|
|
13
|
+
)
|