tina-python 0.7.2__py3-none-any.whl → 0.7.4__py3-none-any.whl

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.
tina/__init__.py CHANGED
@@ -3,11 +3,24 @@ from tina.agent import (
3
3
  Tools,
4
4
  KeywordActions,
5
5
  ContextManager,
6
+ MultimodalContextManager,
6
7
  ToolsExecutor,
7
8
  MultimodalAgent,
8
9
  AgentState,
9
10
  AgentEvents,
10
11
  )
12
+ from tina.context import (
13
+ AssistantMessage,
14
+ Message,
15
+ RawMessage,
16
+ SystemMessage,
17
+ ToolCalls,
18
+ ToolResultMessage,
19
+ UserMessage,
20
+ check_pairs,
21
+ dump_messages,
22
+ parse_messages,
23
+ )
11
24
  from tina.llm.files_api import FilesAPI
12
25
 
13
26
  __all__ = [
@@ -15,10 +28,22 @@ __all__ = [
15
28
  "Tools",
16
29
  "KeywordActions",
17
30
  "ContextManager",
31
+ "MultimodalContextManager",
18
32
  "ToolsExecutor",
19
33
  "MultimodalAgent",
20
34
  "AgentState",
21
35
  "AgentEvents",
22
36
  "FilesAPI",
37
+ # 消息对象(上下文层)
38
+ "Message",
39
+ "SystemMessage",
40
+ "UserMessage",
41
+ "AssistantMessage",
42
+ "ToolCalls",
43
+ "ToolResultMessage",
44
+ "RawMessage",
45
+ "parse_messages",
46
+ "dump_messages",
47
+ "check_pairs",
23
48
  ]
24
- __version__ = "0.7.2"
49
+ __version__ = "0.7.4"
tina/agent/__init__.py CHANGED
@@ -2,9 +2,28 @@ from .agent import Agent
2
2
  from .multimodal_agent import MultimodalAgent
3
3
  from .core.tools import Tools
4
4
  from .core.keyword_actions import KeywordActions
5
- from .core.context_manager import ContextManager, BaseContextManager
5
+ from tina.context import (
6
+ AssistantMessage,
7
+ BaseContextManager,
8
+ ContextManager,
9
+ Message,
10
+ MultimodalContextManager,
11
+ RawMessage,
12
+ SystemMessage,
13
+ ToolCalls,
14
+ ToolResultMessage,
15
+ UserMessage,
16
+ check_pairs,
17
+ dump_messages,
18
+ parse_messages,
19
+ )
6
20
  from .core.executor import ToolsExecutor
7
- from .core.agent_runtime import BaseAgentRuntime
21
+ from .core.agent_runtime import (
22
+ BaseAgentRuntime,
23
+ ToolCallingAgentRuntime,
24
+ ToolCallingMutilemodalAgentRuntime,
25
+ ToolCallingMultimodalAgentRuntime,
26
+ )
8
27
  from .core.state import AgentState
9
28
  from .core.events import AgentEvents
10
29
  from .core.agent_response import AgentResponse, ToolCall
@@ -15,11 +34,25 @@ __all__ = [
15
34
  "KeywordActions",
16
35
  "BaseContextManager",
17
36
  "ContextManager",
37
+ "MultimodalContextManager",
18
38
  "ToolsExecutor",
19
39
  "MultimodalAgent",
20
40
  "BaseAgentRuntime",
41
+ "ToolCallingAgentRuntime",
42
+ "ToolCallingMutilemodalAgentRuntime",
43
+ "ToolCallingMultimodalAgentRuntime",
21
44
  "AgentState",
22
45
  "AgentEvents",
23
46
  "AgentResponse",
24
47
  "ToolCall",
48
+ "Message",
49
+ "SystemMessage",
50
+ "UserMessage",
51
+ "AssistantMessage",
52
+ "ToolCalls",
53
+ "ToolResultMessage",
54
+ "RawMessage",
55
+ "parse_messages",
56
+ "dump_messages",
57
+ "check_pairs",
25
58
  ]
tina/agent/agent.py CHANGED
@@ -29,8 +29,7 @@ from ..llm.base_api import BaseAPI
29
29
  from .core.tools import Tools
30
30
  from .core.keyword_actions import KeywordActions
31
31
  from ..mcp.client import MCPClient, RemoteType, StdioType
32
- from .core.prompt import Prompt
33
- from .core.context_manager import ContextManager
32
+ from tina.context import ContextManager
34
33
  from .core.agent_runtime import ToolCallingAgentRuntime, BaseAgentRuntime
35
34
  from .core.events import AgentEvents
36
35
  from ..core.error import TinaError
@@ -62,9 +61,7 @@ class Agent:
62
61
  events: AgentEvents = None,
63
62
  context_manager: ContextManager = None,
64
63
  agent_runtime: BaseAgentRuntime = None,
65
- max_tool_loop: int = 30,
66
- max_context_length: int = 100000,
67
- max_tool_result_length: int = 6000,
64
+ max_tool_loop: int = 100,
68
65
  name: str = None,
69
66
  keyword_actions: KeywordActions = None,
70
67
  ):
@@ -76,8 +73,6 @@ class Agent:
76
73
  tools: tina.Tools类型,工具集
77
74
  sys_prompt: str 系统提示词
78
75
  MCP: tina.MCPClient类型,MCP客户端对象,如果不传入,则不进行MCP调用。
79
- context_length: int 最大上下文长度,超过该长度则删除旧消息,保留最近的消息。
80
- context_limit: int 上下文限制,使用大模型来总结你的上下文,数字为0时不触发
81
76
  max_tool_loop: int 最大工具调用次数,超过该次数则停止调用工具
82
77
  name: str 智能体名字,用于多Agent区分
83
78
  keyword_actions: KeywordActions,可选关键词动作(不进 tools schema);
@@ -95,24 +90,20 @@ class Agent:
95
90
  if context_manager is None:
96
91
  if agent_runtime is not None:
97
92
  context_manager = agent_runtime.context_manager
98
- else:
99
- context_manager = ContextManager(
100
- max_length=max_context_length,
101
- max_tool_result_length=max_tool_result_length,
102
- )
93
+ if context_manager is None: # runtime 自己也没带,兜底新建一个
94
+ context_manager = ContextManager()
103
95
  self.context_manager = context_manager
104
96
  # 初始化MCP
105
97
  self._mcp_to_tools(mcp)
106
98
  self.events = AgentEvents() if events is None else events
107
99
  if system_prompt is not None:
108
100
  self.context_manager.set_system_message(system_prompt)
109
- elif not self.context_manager.get_system_message():
110
- # 未显式给 system_prompt 时,保留传入的 context_manager 自带的系统提示;
111
- # 只有它没有系统提示时才填默认。
112
- self.context_manager.set_system_message(Prompt("tina").prompt)
101
+ # 没给 system_prompt 就**不注入任何默认提示词**:
102
+ # 要么沿用 context_manager 自带的(如 CodingContextManager),要么就没有
103
+ # system 消息。角色设定是产品决策,框架不该替你选。
104
+ # 想要现成的可以用 `Prompt("tina").prompt` 自己传。
113
105
  self._inject_keyword_actions_prompt()
114
106
 
115
- self.messages = self.context_manager.get_messages()
116
107
  if agent_runtime is None:
117
108
  self.runtime = ToolCallingAgentRuntime(
118
109
  self.llm,
@@ -124,15 +115,32 @@ class Agent:
124
115
  keyword_actions=self.keyword_actions,
125
116
  )
126
117
  else:
127
- self.runtime = agent_runtime
128
- self.runtime.context_manager = self.context_manager
129
- if (
130
- self.keyword_actions is not None
131
- and getattr(self.runtime, "keyword_actions", None) is None
132
- ):
133
- self.runtime.keyword_actions = self.keyword_actions
118
+ self.set_runtime(agent_runtime)
134
119
  self.other_agents = []
135
120
 
121
+ def set_runtime(self, runtime: BaseAgentRuntime) -> None:
122
+ """替换运行时,并把它需要的引用同步过去
123
+
124
+ 直接用 ``agent.runtime = xxx`` 也行,但那样得自己记得同步
125
+ ``context_manager`` / ``keyword_actions``,漏一个就会两边各说各话
126
+ (运行时用的是旧上下文管理器 → 模型看到的和 Agent 维护的不是一份)。
127
+
128
+ 自定义运行时如果想拿到 Agent 本身的引用(比如要在一轮推理前后回调
129
+ Agent),实现 ``attach(agent)`` 即可,这里会调用它。
130
+ """
131
+ self.runtime = runtime
132
+ # 运行时必须跟着当前 Agent 的上下文管理器走
133
+ runtime.context_manager = self.context_manager
134
+ # keyword_actions 只在运行时自己没有时才补,别覆盖它自己的配置
135
+ if (
136
+ self.keyword_actions is not None
137
+ and getattr(runtime, "keyword_actions", None) is None
138
+ ):
139
+ runtime.keyword_actions = self.keyword_actions
140
+ attach = getattr(runtime, "attach", None)
141
+ if callable(attach):
142
+ attach(self)
143
+
136
144
  def set_keyword_actions(self, keyword_actions: KeywordActions | None) -> None:
137
145
  """挂载或替换 KeywordActions;会同步更新 system prompt 末尾的说明块。"""
138
146
  self.keyword_actions = keyword_actions
@@ -150,18 +158,24 @@ class Agent:
150
158
  将 KeywordActions 说明块追加到 system prompt 末尾:
151
159
  <keyword_action>...</keyword_action>
152
160
  """
153
- prompt = self._strip_keyword_action_block(
154
- self.context_manager.get_system_message() or ""
155
- )
161
+ existing = self.context_manager.get_system_message() or ""
162
+ prompt = self._strip_keyword_action_block(existing)
156
163
  block = ""
157
164
  if self.keyword_actions is not None:
158
165
  block = self.keyword_actions.build_prompt_block()
166
+
159
167
  if block:
160
168
  wrapped = f"<keyword_action>\n{block}\n</keyword_action>"
161
- self.context_manager.set_system_message(f"{prompt}\n\n{wrapped}" if prompt else wrapped)
169
+ new_prompt = f"{prompt}\n\n{wrapped}" if prompt else wrapped
162
170
  logger.warn("使用了关键词动作,会影响你的系统提示词")
163
171
  else:
164
- self.context_manager.set_system_message(prompt)
172
+ new_prompt = prompt
173
+
174
+ # 没变化就不动 —— 否则「没给 system_prompt 也没关键词」的情况下,
175
+ # 这里会凭空造出一条 content 为空的 system 消息。
176
+ if new_prompt == existing:
177
+ return
178
+ self.context_manager.set_system_message(new_prompt)
165
179
 
166
180
  def build_keyword_actions_prompt_block(self) -> str:
167
181
  """生成可拼进 system prompt 的关键词动作说明块。"""
@@ -354,6 +368,24 @@ class Agent:
354
368
  """
355
369
  self.events.add_before_llm_call_handler(func)
356
370
 
371
+ def on_usage(self):
372
+ """
373
+ 每次 LLM 请求返回 usage 时触发
374
+
375
+ 需要事件处理函数接受下面的参数:
376
+ usage: tina.utils.Usage
377
+ """
378
+ return self.events.on_usage()
379
+
380
+ def add_on_usage_handler(self, func: callable | list[callable]):
381
+ """
382
+ 每次 LLM 请求返回 usage 时触发
383
+
384
+ 需要事件处理函数接受下面的参数:
385
+ usage: tina.utils.Usage
386
+ """
387
+ self.events.add_on_usage_handler(func)
388
+
357
389
  def _mcp_to_tools(self, MCP):
358
390
  """如果传入了MCP,则将MCP的工具集加入到当前的工具集中"""
359
391
  try:
@@ -384,29 +416,76 @@ class Agent:
384
416
  except Exception: # noqa: BLE001 工具集未命名等情况下静默跳过
385
417
  pass
386
418
 
419
+ @property
420
+ def messages(self) -> list:
421
+ """当前上下文的消息对象列表(活引用,永远和 context_manager 同步)
422
+
423
+ 读它总是拿到最新的那一份(不会因为换过 context_manager 而拿到旧列表)。
424
+ 赋值等价于 `context_manager.set_messages(...)`。
425
+
426
+ 往里 append 原生 dict 会当场抛 TypeError —— 那是 0.7.3 的写法,
427
+ 现在要加 OpenAI 格式的消息请用 `add_messages([...])` 或 `set_raw_messages([...])`。
428
+ """
429
+ return self.context_manager.get_messages()
430
+
431
+ @messages.setter
432
+ def messages(self, value) -> None:
433
+ self.context_manager.set_messages(value)
434
+
387
435
  def get_messages(self) -> list:
388
436
  """
389
437
  获取当前Agent的完整消息列表(包含 system 系统提示词)
390
- Agent会在当前运行状态维护一个自己的消息列表,可以通过该方法获取
438
+
439
+ 返回的是**消息对象**(`Message` / `ToolCalls`),改了立刻生效。
440
+ 要 OpenAI wire format 的 `list[dict]`,用 `get_raw_messages()`。
391
441
  """
392
442
  return self.messages
393
443
 
444
+ def get_raw_messages(self) -> list[dict]:
445
+ """
446
+ 获取 OpenAI wire format 的消息列表(`list[dict]`)
447
+
448
+ 喂 LLM、存盘、或者交给不认 tina 对象的老代码时用这个。
449
+ """
450
+ return self.context_manager.get_raw_messages()
451
+
452
+ def set_raw_messages(self, messages: list[dict]) -> None:
453
+ """
454
+ 用 OpenAI wire format 的 `list[dict]` 替换整个上下文
455
+ """
456
+ self.context_manager.set_raw_messages(messages)
457
+
394
458
  def get_conversation(self) -> list:
395
459
  """
396
460
  获取当前Agent的对话消息列表(不包含 system 系统提示词)
461
+
462
+ 返回的是**消息对象**;要 wire format 用 `get_raw_conversation()`。
397
463
  """
398
464
  return self.context_manager.get_conversation()
399
465
 
466
+ def get_raw_conversation(self) -> list[dict]:
467
+ """
468
+ 获取不含 system 的 OpenAI wire format 对话列表(`list[dict]`)
469
+
470
+ 存盘 / 导出 / 交给老代码时用这个。
471
+ """
472
+ return self.context_manager.get_raw_conversation()
473
+
474
+ def copy_conversation(self) -> list:
475
+ """获取对话消息对象的深拷贝(不含 system),改它不影响上下文"""
476
+ return self.context_manager.copy_conversation()
477
+
400
478
  def set_context_manager(self, context_manager: ContextManager) -> None:
401
479
  """
402
- 替换上下文管理器,并同步给运行时与 messages
480
+ 替换上下文管理器,并同步给运行时
481
+
482
+ `messages` 是 property,会自动跟着新的 context_manager 走,不需要再手动同步。
403
483
 
404
484
  Args:
405
485
  context_manager: 新的上下文管理器
406
486
  """
407
487
  self.context_manager = context_manager
408
488
  self.runtime.context_manager = context_manager
409
- self.messages = context_manager.get_messages()
410
489
 
411
490
  def clear_messages(self) -> None:
412
491
  """
@@ -500,7 +579,7 @@ class Agent:
500
579
  Args:
501
580
  messages:消息列表,可以一次性添加多个消息,格式为[{"role": "user", "content": "你好,我是用户"}]
502
581
  """
503
- self.messages = self.context_manager.add_messages(messages)
582
+ self.context_manager.add_messages(messages)
504
583
 
505
584
  def get_tools_call_result(self) -> list:
506
585
  """