Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
173 commits
Select commit Hold shift + click to select a range
67e5f36
feat: Add OpenAI Responses API support to LLM class
enyst Sep 6, 2025
6c806b0
Update openhands/sdk/llm/llm.py
enyst Sep 6, 2025
39a610e
fix: Update RESPONSES_API_PATTERNS to only include models with native…
enyst Sep 6, 2025
7855588
Clean up unnecessary hasattr() checks for usage object properties
enyst Sep 6, 2025
a805fc7
fix: Clean up ResponsesAPIResponse attribute access
enyst Sep 6, 2025
00219c2
Merge branch 'main' into openhands/support-responses-api
enyst Sep 7, 2025
9d3d816
Merge remote-tracking branch 'origin/main' into openhands/support-res…
enyst Sep 8, 2025
30f1397
llm: fix Responses->ChatCompletions conversion to satisfy ModelRespon…
enyst Sep 8, 2025
6970f32
Merge commit '585d4779b188694e99127431db51190db19e4352' into openhand…
xingyaoww Sep 9, 2025
1133d42
feat: Add GPT-5 model support and reasoning debug example
enyst Sep 9, 2025
88c7ef4
Revert "feat: Add GPT-5 model support and reasoning debug example"
enyst Sep 9, 2025
977702b
fix(responses): keep tools/tool_choice for Responses API; only drop s…
enyst Sep 9, 2025
d00924c
fix: Remove tools parameter from Responses API calls
enyst Sep 9, 2025
cf690e6
examples_local: restrict to litellm_proxy gpt-5-mini; dedupe + wrap l…
enyst Sep 9, 2025
b46811a
Revert "fix: Remove tools parameter from Responses API calls"
enyst Sep 9, 2025
567a501
fix: Update test to correctly expect tools parameter in Responses API
enyst Sep 9, 2025
1c8598a
responses: map reasoning_tokens from Responses usage to completion fo…
enyst Sep 9, 2025
ec47dc6
responses: include reasoning_tokens mapping; run OH Responses probe b…
enyst Sep 9, 2025
0300404
responses: send Responses.reasoning to request summaries; set text.ve…
enyst Sep 9, 2025
c8b05d6
responses: request reasoning summary + encrypted content; wire text.v…
enyst Sep 9, 2025
74788c2
responses: use api_base + custom_llm_provider for litellm proxy; wrap…
enyst Sep 9, 2025
be25231
responses: use underlying model id for LiteLLM proxy responses; ensur…
enyst Sep 9, 2025
cbf03c1
responses(kwargs): remove unsupported OpenAI Responses fields for pro…
enyst Sep 9, 2025
e5ffe65
responses(kwargs): request concise reasoning summary via Responses.re…
enyst Sep 9, 2025
d79e1a9
responses(kwargs): set reasoning.summary='detailed' for gpt-5-mini vi…
enyst Sep 9, 2025
fc992c1
responses(converter): fix remaining E501 by shortening comment
enyst Sep 9, 2025
5b8b1b1
add gpt-5-mini
enyst Sep 9, 2025
57b163a
examples_local: fix lint formatting after edits.
enyst Sep 9, 2025
7f7941f
chore: remove stray local test artifact from llm/
enyst Sep 9, 2025
1f3e07d
llm: delegate completion() to Responses API for models that support i…
enyst Sep 9, 2025
919be46
examples_local: focus reasoning debug on LiteLLM proxy model only; re…
enyst Sep 9, 2025
bd83648
examples_local: restrict reasoning debug to LiteLLM proxy model gpt-5…
enyst Sep 10, 2025
f031b55
fix tests; keep only summaries
enyst Sep 10, 2025
e7da224
feat(responses):
openhands-agent Sep 10, 2025
4869ad8
Merge branch 'main' into openhands/support-responses-api
enyst Sep 10, 2025
16a24a2
Update openhands/sdk/tool/tool.py
enyst Sep 10, 2025
409ea77
use test model for pause tests
enyst Sep 10, 2025
bda59e5
tests: expect flattened Responses tool shape in normalization test
openhands-agent Sep 10, 2025
c7e85a7
fix(responses): clean tool conversion, avoid None fields, add debug o…
openhands-agent Sep 10, 2025
1eb29df
style: wrap long comment in Responses tool conversion to fix ruff E501
openhands-agent Sep 10, 2025
d081d39
feat(tool): add Tool.to_responses() returning plain dict for OpenAI R…
enyst Sep 10, 2025
e6764ac
refactor(responses): minimize defensiveness; assume ChatCompletionToo…
openhands-agent Sep 10, 2025
b2c250f
- Updated normalization test to use ChatCompletionToolParam and asser…
enyst Sep 10, 2025
bb94844
test(responses): relax tool-object schema assertion; assert required …
openhands-agent Sep 10, 2025
e6c4142
style: shorten comment to fix ruff E501; rely on dict-based Chat Comp…
openhands-agent Sep 10, 2025
191d2d8
cut verbosity
enyst Sep 10, 2025
e2756cc
merge: resolve conflict in Tool; keep to_responses(); preserve ToolTy…
enyst Sep 10, 2025
2c501d4
Delete .tmp/reasoning_content_example.py
enyst Sep 10, 2025
f61d8c0
Delete examples/responses_api_example.py
enyst Sep 10, 2025
4f37823
clean up llm
enyst Sep 10, 2025
db5687b
refactor(llm): unify completion/responses call paths via a single engine
enyst Sep 10, 2025
ed84a58
refactor(llm): use structured input for Responses; centralize Message…
enyst Sep 10, 2025
0dfdfe9
Merge upstream/main into openhands/support-responses-api; rebase LLM …
enyst Sep 10, 2025
cfcabf9
feat(llm): integrate OpenAI Responses API with structured inputs and …
enyst Sep 10, 2025
9ae8559
fix(telemetry): guard metrics context_window with safe int conversion
enyst Sep 10, 2025
0d6385e
chore(llm): remove duplicate store-default code in Responses path
enyst Sep 10, 2025
416b011
fix(llm): harden Responses routing and non-native FC; restore model i…
enyst Sep 11, 2025
1957208
revert: simplify use_mock_tools logic back to original implementation
enyst Sep 11, 2025
eb64bb4
Remove unnecessary wildcards from model feature patterns
enyst Sep 11, 2025
d1687cd
refactor: simplify usage object handling in responses_converter
enyst Sep 11, 2025
0154bd8
Update openhands/sdk/llm/utils/telemetry.py
enyst Sep 11, 2025
e605ef2
refactor(llm): simplify Responses integration per feedback; fix routi…
enyst Sep 11, 2025
4790b22
fix(llm): remove import causing circular dep; default store=False in …
enyst Sep 11, 2025
5ba6066
refactor(responses): align tool schema and defaults; remove circular …
enyst Sep 11, 2025
5e4fe5c
remove agent pet code
enyst Sep 11, 2025
01eb36d
chore(responses): remove messages_to_responses_input; align tests wit…
enyst Sep 11, 2025
a79847c
clean up 'defensive' params
enyst Sep 11, 2025
97e245b
reorder
enyst Sep 11, 2025
ca6cd40
Merge branch 'main' of github.com:All-Hands-AI/agent-sdk into openhan…
enyst Sep 11, 2025
6458f0f
fix test, responses API doesn't mock fc
enyst Sep 11, 2025
d551e64
LLM: route completion() to Responses API for reasoning models; map to…
enyst Sep 12, 2025
277d6b5
Responses converter: only accept created_at per OpenAI Responses API;…
enyst Sep 12, 2025
17b84fe
clean out useless condition
enyst Sep 12, 2025
a9aa19f
simplify code
enyst Sep 12, 2025
95d495e
LLM: simplify tool_calls conversion; assume Chat Completions shape an…
enyst Sep 12, 2025
26b0fa6
LLM: require tool messages to use tool_call_id; drop fallbacks to cal…
enyst Sep 12, 2025
a57e91d
LLM: use correct tool_call id key and inline values when emitting fun…
enyst Sep 12, 2025
78f4dba
use dicts
enyst Sep 12, 2025
ef16c33
tests: align responses_converter tests with strict Responses API obje…
enyst Sep 12, 2025
7eb58e9
Responses converter: enforce direct attribute access for Responses ob…
enyst Sep 12, 2025
201d6c7
Responses converter: simplify output.message.content parsing; assume …
enyst Sep 12, 2025
637aa00
Responses converter: strong typing for Responses API objects; direct …
enyst Sep 12, 2025
64427ce
Tests: use real OpenAI Responses SDK objects for message/reasoning; c…
enyst Sep 12, 2025
74c164d
Responses tests: consolidate support/error test; switch mocks to crea…
enyst Sep 12, 2025
0aa6a93
Tests: fix CI failures for Responses strictness + completion modes
enyst Sep 12, 2025
a9ac121
clean up
enyst Sep 12, 2025
b68f8f2
Update openhands/sdk/llm/llm.py
enyst Sep 12, 2025
9e079cd
LLM Responses: normalize messages in responses() and simplify convert…
enyst Sep 12, 2025
23b82ba
fix type hints
enyst Sep 12, 2025
ee17e9e
Responses: convert LiteLLM/OpenAI typed output to canonical Chat Comp…
enyst Sep 12, 2025
b7bd7a9
LLM Responses: tighten types, normalize inputs; tests: implement conv…
enyst Sep 12, 2025
e9bfd42
Responses path: default store=True; fix tool-call ordering for Respon…
enyst Sep 12, 2025
8ace3db
avoid litellm bridge, keep stateless
enyst Sep 12, 2025
b7501ba
Merge branch 'main' of github.com:All-Hands-AI/agent-sdk into openhan…
enyst Sep 13, 2025
b180201
Refactor to use discriminated union for completion/responses
enyst Sep 13, 2025
c21d97e
agent: pass Tool objects to LLM.completion instead of pre-converting …
enyst Sep 13, 2025
67d5154
llm: separate chat vs responses tool types; enforce non-stream respon…
enyst Sep 13, 2025
f2c0b3f
examples: extend 05_use_llm_registry to record responses path vs chat…
enyst Sep 14, 2025
f601e91
llm: include 'kind' in telemetry log_ctx and pass drop_params to lite…
enyst Sep 14, 2025
581f949
llm(responses): force native Responses API path under proxy by passin…
enyst Sep 14, 2025
f581d14
examples(12): use OPENAI_API_KEY and call OpenAI directly (no proxy);…
enyst Sep 14, 2025
2f95173
llm(responses): set store=True by default on Responses path; keep rea…
enyst Sep 14, 2025
5b239a6
examples(12): default to litellm_proxy/openai/gpt-5-mini-2025-08-07 a…
enyst Sep 14, 2025
e20a1b0
examples(12): use LITELLM_API_KEY (proxy) instead of OPENAI_API_KEY; …
enyst Sep 14, 2025
9c22235
llm(responses): capture reasoning from top-level response.reasoning w…
enyst Sep 14, 2025
3d7be56
responses-converter: remove fallback that incorrectly treated request…
enyst Sep 14, 2025
ab4d75b
examples: restore 05, 06 to main content (strip debugging/telemetry a…
enyst Sep 14, 2025
a48028e
chore(examples): remove examples_local and debug-only example 12 from…
enyst Sep 14, 2025
f3fbe65
llm: unify routing via _select_kind + _pre_normalize; make completion…
enyst Sep 14, 2025
8badda1
llm: finalize unified routing; fix responses() pre-normalization and …
enyst Sep 14, 2025
bd526e6
rename function
enyst Sep 14, 2025
4331c82
tool: simplify conversions; remove defensive None-guards
enyst Sep 14, 2025
cb830e4
telemetry: require non-None context_window; drop defensive casting
enyst Sep 14, 2025
f14c755
llm.telemetry: ensure context_window is always int in log ctx (fallba…
enyst Sep 14, 2025
3c6c6a4
responses_converter: simplify usage extraction; drop hasattr/getattr …
enyst Sep 14, 2025
8d28c51
responses: harden usage handling for mocks; clean long line in local …
enyst Sep 14, 2025
7eda5cf
llm(responses): trim over-defensive tool fallback; rely on function a…
enyst Sep 14, 2025
7785fa9
chore: remove local examples from repo scope
enyst Sep 14, 2025
4cb3a10
docs(microagents): add guideline to avoid overly defensive code
enyst Sep 14, 2025
8e150b0
Update .openhands/microagents/repo.md
enyst Sep 14, 2025
8e0e912
Merge branch 'main' into openhands/support-responses-api
enyst Sep 15, 2025
b8c7bd1
Merge branch 'main' into openhands/support-responses-api
xingyaoww Sep 15, 2025
222a4d4
Merge branch 'main' into openhands/support-responses-api
xingyaoww Sep 15, 2025
73799fa
feat: Add image input support to Responses API converter
enyst Sep 15, 2025
af06c72
feat(visualizer): show reasoning in MessageEvent panels when present
enyst Sep 15, 2025
a27434f
Merge branch 'openhands/support-responses-api' of github.com:All-Hand…
enyst Sep 15, 2025
03d9d78
Merge branch 'main' into openhands/support-responses-api
enyst Sep 15, 2025
55475fd
Merge commit 'f8e800a93a3726555a30d1c42a692f4c556187c5' into openhand…
xingyaoww Sep 16, 2025
9c73760
Remove redundant else clause in messages handling
enyst Sep 17, 2025
ba8be8b
Improve type annotation for messages_to_responses_items function
enyst Sep 17, 2025
57d66eb
remove task
xingyaoww Sep 18, 2025
3144a88
Merge remote-tracking branch 'upstream/main' into openhands/support-r…
enyst Sep 19, 2025
dfed315
LLM: centralize tool conversion; gate Responses API to supported mode…
enyst Sep 19, 2025
4979ff4
LLM: simplify _pre_normalize chat path to assume list[Message]; keep …
enyst Sep 20, 2025
431fc66
Merge remote-tracking branch 'upstream/main' into openhands/support-r…
enyst Sep 20, 2025
15433cb
responses: align tools param to list[ToolBase] | None; include tool d…
enyst Sep 21, 2025
b40fde7
merge: resolve conflict in LLM by combining Responses routing helpers…
enyst Sep 21, 2025
e595cef
types: make tools parameter covariant by using Sequence[ToolBase] in …
enyst Sep 21, 2025
ba731f3
scripts: add e2e_responses_reasoning.py to exercise Responses API rea…
enyst Sep 21, 2025
511d135
responses: map reasoning_effort -> reasoning.effort for Responses API…
enyst Sep 21, 2025
275d993
responses: set reasoning.effort from self.reasoning_effort for Respon…
enyst Sep 21, 2025
5029ab3
agent: resolve merge conflict by passing Tool objects through to LLM.…
enyst Sep 21, 2025
821bdbe
agent: use tools_map when passing tools to LLM.completion (align with…
enyst Sep 21, 2025
9982d45
fix(scripts): typing for tools Sequence[Any] to appease pyright in e2…
enyst Sep 21, 2025
17a9c38
merge(main): resolve conflicts after merging main into support-respon…
enyst Sep 21, 2025
29598b0
sdk(llm): simplify Responses API signature to accept Message|str only…
enyst Sep 22, 2025
480675e
tests(conversation): merge main into support-responses-api and resolv…
enyst Sep 22, 2025
bb96b6a
tests(llm.responses): align tests with narrowed responses() API; drop…
enyst Sep 22, 2025
a2462a6
tests(conversation): avoid openhands.tools imports in SDK tests; use …
enyst Sep 22, 2025
e032f29
Xw/responses api typing (#397)
xingyaoww Sep 22, 2025
97bde4e
sdk(responses): tighten converter typing and remove redundancies
enyst Sep 22, 2025
45e1162
sdk(responses): type Responses tools with ToolParam end-to-end
enyst Sep 22, 2025
eed006c
Merge branch 'main' into openhands/support-responses-api
enyst Sep 22, 2025
82f98ec
Merge remote-tracking branch 'upstream/main' into openhands/support-r…
enyst Sep 22, 2025
9788683
fix(telemetry): correct duplicate tools pop key in telemetry log ctx
enyst Sep 22, 2025
b2cc3a9
llm(responses): add seed to Responses transport and drop redundant ap…
enyst Sep 22, 2025
375edec
Merge branch 'main' into openhands/support-responses-api
enyst Sep 22, 2025
7f29575
sdk(llm): messages_to_responses_items now accepts only typed AllMessa…
enyst Sep 22, 2025
d3e6b84
Merge branch 'openhands/support-responses-api' of github.com:All-Hand…
enyst Sep 22, 2025
791e352
Merge branch 'chore/review-142-fixes' into openhands/support-response…
enyst Sep 22, 2025
990f8fa
Update .openhands/microagents/repo.md
enyst Sep 23, 2025
add21f9
Merge upstream main into openhands/support-responses-api; adopt upstr…
enyst Sep 23, 2025
4f22c7d
Delete PRD_responses_agent_llm.md
enyst Sep 23, 2025
1da790e
examples: add prompt cache probe example to verify Anthropic caching …
enyst Sep 23, 2025
939853d
examples: extend prompt cache probe to exercise repeated agent run an…
enyst Sep 23, 2025
24546c9
telemetry: write request payload (log_ctx) immediately to log dir whe…
enyst Sep 23, 2025
4e33141
simplify the probe
enyst Sep 23, 2025
c50019d
convert pydantic to serializable types before sending
enyst Sep 25, 2025
95d1cdb
Fix tests post-merge: update local tool factories to return list; add…
enyst Sep 25, 2025
f5468dc
Clean up Message._list_serializer duplicate lines; keep message-level…
enyst Sep 25, 2025
52effc0
Responses API + merge cleanup:
enyst Sep 25, 2025
a96ce55
pre-commit: format/lint fixes after merge
enyst Sep 25, 2025
794a2df
tests: update persistence usage to new Conversation signature in stat…
enyst Oct 1, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
152 changes: 152 additions & 0 deletions examples/22_prompt_cache_probe.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
"""OpenHands Agent SDK — Prompt Cache Probe (Anthropic)

This example runs a short task using an Anthropic model via LiteLLM proxy,
logs completion metadata, and prints whether prompt caching (read/write tokens)
appears in the usage.

Requirements:
- LITELLM_API_KEY set in the environment
- Network access to the LiteLLM proxy

It will:
1) Create an LLM with logging enabled (JSON logs written to a temp dir)
2) Create a default agent with bash/file editor tools
3) Ask the agent to read README.mdx and summarize it
4) Print a summary of cache read/write tokens from the telemetry logs
"""

import glob
import json
import os
import signal
import time
from pathlib import Path

import litellm
from pydantic import SecretStr

from openhands.sdk import Conversation
from openhands.sdk.llm.llm import LLM
from openhands.sdk.preset.default import get_default_agent
from openhands.sdk.security.confirmation_policy import NeverConfirm


# Make ^C a clean exit instead of a stack trace
signal.signal(signal.SIGINT, lambda *_: (_ for _ in ()).throw(KeyboardInterrupt()))


def main() -> None:
api_key = os.getenv("LITELLM_API_KEY")
assert api_key, "LITELLM_API_KEY environment variable is not set."

# Create a writable logs directory for telemetry JSON logs
logs_dir = Path.cwd() / ".prompt_cache_logs"
logs_dir.mkdir(exist_ok=True)

# Anthropic via LiteLLM proxy, aligned with other examples in this repo
llm = LLM(
model="litellm_proxy/anthropic/claude-sonnet-4-20250514",
base_url="https://llm-proxy.eval.all-hands.dev",
api_key=SecretStr(api_key),
max_output_tokens=256,
# Enable completion logging so we can inspect cache read/write tokens
log_completions=True,
log_completions_folder=str(logs_dir),
)

# Work around LiteLLM logging deepcopy issue by disabling LiteLLM internal logging
try:
litellm.set_verbose = True # type: ignore[attr-defined]
except Exception:
pass

agent = get_default_agent(llm=llm, working_dir=os.getcwd(), cli_mode=True)
convo = Conversation(agent=agent)

# Disable confirmation so tools execute without prompting
convo.set_confirmation_policy(NeverConfirm())

# Start time to filter newly written logs
t0 = time.time()

# Ask the agent to read README and summarize
task = (
"Please read the ./README.mdx file and provide a one-sentence summary.\n"
"Use available tools to open and read files as needed."
)
print("\n▶️ Sending task to agent:", task)
convo.send_message(task)

# Drive until finished
from openhands.sdk.conversation.state import AgentExecutionStatus

while convo.state.agent_status != AgentExecutionStatus.FINISHED:
convo.run()

print("\n✅ Run complete. Inspecting telemetry logs in:", logs_dir)

# Collect JSON logs generated after t0
logs = sorted(
[
Path(p)
for p in glob.glob(str(logs_dir / "*.json"))
if os.path.getmtime(p) >= t0
]
)

if not logs:
print("No telemetry logs found; ensure log directory exists and is writable.")
return

any_cache_read = False
any_cache_write = False

for p in logs:
try:
data = json.loads(Path(p).read_text())
except Exception as e:
print(f" - {p.name}: failed to parse JSON: {e}")
continue

usage_summary = data.get("usage_summary", {})
cache_read = int(usage_summary.get("cache_read_tokens", 0) or 0)
prompt_tokens = int(usage_summary.get("prompt_tokens", 0) or 0)
completion_tokens = int(usage_summary.get("completion_tokens", 0) or 0)

# Also check cache creation tokens on providers that expose it
cache_write = 0
try:
resp = data.get("response", {})
usage = resp.get("usage") if isinstance(resp, dict) else None
if usage and isinstance(usage, dict):
cache_write = int(usage.get("_cache_creation_input_tokens", 0) or 0)
except Exception:
pass

# Responses path indicator: raw_response is included for Responses API
used_responses_api = "raw_response" in data

any_cache_read |= cache_read > 0
any_cache_write |= cache_write > 0

print(
" -",
p.name,
f"transport={'responses' if used_responses_api else 'chat'}",
f"prompt={prompt_tokens}",
f"completion={completion_tokens}",
f"cache_read={cache_read}",
f"cache_write={cache_write}",
)

print("\nSummary:")
print(" cache_read observed:", any_cache_read)
print(" cache_write observed:", any_cache_write)
if not any_cache_read:
print(
" No cache reads observed; prompt caching may not be active on read paths."
)


if __name__ == "__main__":
main()
Loading