Base: codex-main originale (prima del fork aKode)
This commit is contained in:
34
sdk/python/examples/01_quickstart_constructor/async.py
Normal file
34
sdk/python/examples/01_quickstart_constructor/async.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import (
|
||||
ensure_local_sdk_src,
|
||||
runtime_config,
|
||||
server_label,
|
||||
)
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
|
||||
from openai_codex import AsyncCodex
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
print("Server:", server_label(codex.metadata))
|
||||
|
||||
thread = await codex.thread_start(
|
||||
model="gpt-5.4", config={"model_reasoning_effort": "high"}
|
||||
)
|
||||
result = await thread.run("Say hello in one sentence.")
|
||||
print("Items:", len(result.items))
|
||||
print("Text:", result.final_response)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
24
sdk/python/examples/01_quickstart_constructor/sync.py
Normal file
24
sdk/python/examples/01_quickstart_constructor/sync.py
Normal file
@@ -0,0 +1,24 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import (
|
||||
ensure_local_sdk_src,
|
||||
runtime_config,
|
||||
server_label,
|
||||
)
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
print("Server:", server_label(codex.metadata))
|
||||
|
||||
thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"})
|
||||
result = thread.run("Say hello in one sentence.")
|
||||
print("Items:", len(result.items))
|
||||
print("Text:", result.final_response)
|
||||
35
sdk/python/examples/02_turn_run/async.py
Normal file
35
sdk/python/examples/02_turn_run/async.py
Normal file
@@ -0,0 +1,35 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
|
||||
from openai_codex import AsyncCodex
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
thread = await codex.thread_start(
|
||||
model="gpt-5.4", config={"model_reasoning_effort": "high"}
|
||||
)
|
||||
turn = await thread.turn("Give 3 bullets about SIMD.")
|
||||
result = await turn.run()
|
||||
|
||||
print("thread_id:", thread.id)
|
||||
print("turn_id:", result.id)
|
||||
print("status:", result.status)
|
||||
if result.error is not None:
|
||||
print("error:", result.error)
|
||||
print("text:", result.final_response)
|
||||
print("items.count:", len(result.items))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
24
sdk/python/examples/02_turn_run/sync.py
Normal file
24
sdk/python/examples/02_turn_run/sync.py
Normal file
@@ -0,0 +1,24 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"})
|
||||
result = thread.turn("Give 3 bullets about SIMD.").run()
|
||||
|
||||
print("thread_id:", thread.id)
|
||||
print("turn_id:", result.id)
|
||||
print("status:", result.status)
|
||||
if result.error is not None:
|
||||
print("error:", result.error)
|
||||
print("text:", result.final_response)
|
||||
print("items.count:", len(result.items))
|
||||
66
sdk/python/examples/03_turn_stream_events/async.py
Normal file
66
sdk/python/examples/03_turn_stream_events/async.py
Normal file
@@ -0,0 +1,66 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
|
||||
from openai_codex import AsyncCodex
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
thread = await codex.thread_start(
|
||||
model="gpt-5.4", config={"model_reasoning_effort": "high"}
|
||||
)
|
||||
turn = await thread.turn("Explain SIMD in 3 short bullets.")
|
||||
|
||||
event_count = 0
|
||||
saw_started = False
|
||||
saw_delta = False
|
||||
completed_status = None
|
||||
completed_texts = []
|
||||
|
||||
async for event in turn.stream():
|
||||
event_count += 1
|
||||
if event.method == "turn/started":
|
||||
saw_started = True
|
||||
print("stream.started")
|
||||
continue
|
||||
if event.method == "item/agentMessage/delta":
|
||||
delta = event.payload.delta
|
||||
if delta:
|
||||
if not saw_delta:
|
||||
print("assistant> ", end="", flush=True)
|
||||
print(delta, end="", flush=True)
|
||||
saw_delta = True
|
||||
continue
|
||||
if event.method == "item/completed":
|
||||
root = event.payload.item.root
|
||||
if root.type == "agentMessage":
|
||||
completed_texts.append(root.text)
|
||||
continue
|
||||
if event.method == "turn/completed":
|
||||
completed_status = event.payload.turn.status.value
|
||||
|
||||
if completed_status is None:
|
||||
raise RuntimeError("stream ended without turn/completed")
|
||||
if saw_delta:
|
||||
print()
|
||||
else:
|
||||
final_text = "".join(completed_texts).strip()
|
||||
print("assistant>", final_text)
|
||||
|
||||
print("stream.started.seen:", saw_started)
|
||||
print("stream.completed:", completed_status)
|
||||
print("events.count:", event_count)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
56
sdk/python/examples/03_turn_stream_events/sync.py
Normal file
56
sdk/python/examples/03_turn_stream_events/sync.py
Normal file
@@ -0,0 +1,56 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"})
|
||||
turn = thread.turn("Explain SIMD in 3 short bullets.")
|
||||
|
||||
event_count = 0
|
||||
saw_started = False
|
||||
saw_delta = False
|
||||
completed_status = None
|
||||
completed_texts = []
|
||||
|
||||
for event in turn.stream():
|
||||
event_count += 1
|
||||
if event.method == "turn/started":
|
||||
saw_started = True
|
||||
print("stream.started")
|
||||
continue
|
||||
if event.method == "item/agentMessage/delta":
|
||||
delta = event.payload.delta
|
||||
if delta:
|
||||
if not saw_delta:
|
||||
print("assistant> ", end="", flush=True)
|
||||
print(delta, end="", flush=True)
|
||||
saw_delta = True
|
||||
continue
|
||||
if event.method == "item/completed":
|
||||
root = event.payload.item.root
|
||||
if root.type == "agentMessage":
|
||||
completed_texts.append(root.text)
|
||||
continue
|
||||
if event.method == "turn/completed":
|
||||
completed_status = event.payload.turn.status.value
|
||||
|
||||
if completed_status is None:
|
||||
raise RuntimeError("stream ended without turn/completed")
|
||||
if saw_delta:
|
||||
print()
|
||||
else:
|
||||
final_text = "".join(completed_texts).strip()
|
||||
print("assistant>", final_text)
|
||||
|
||||
print("stream.started.seen:", saw_started)
|
||||
print("stream.completed:", completed_status)
|
||||
print("events.count:", event_count)
|
||||
26
sdk/python/examples/04_models_and_metadata/async.py
Normal file
26
sdk/python/examples/04_models_and_metadata/async.py
Normal file
@@ -0,0 +1,26 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config, server_label
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
|
||||
from openai_codex import AsyncCodex
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
print("server:", server_label(codex.metadata))
|
||||
models = await codex.models()
|
||||
print("models.count:", len(models.data))
|
||||
print("models:", ", ".join(model.id for model in models.data[:5]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
18
sdk/python/examples/04_models_and_metadata/sync.py
Normal file
18
sdk/python/examples/04_models_and_metadata/sync.py
Normal file
@@ -0,0 +1,18 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config, server_label
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
print("server:", server_label(codex.metadata))
|
||||
models = codex.models()
|
||||
print("models.count:", len(models.data))
|
||||
print("models:", ", ".join(model.id for model in models.data[:5]))
|
||||
34
sdk/python/examples/05_existing_thread/async.py
Normal file
34
sdk/python/examples/05_existing_thread/async.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
|
||||
from openai_codex import AsyncCodex
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
original = await codex.thread_start(
|
||||
model="gpt-5.4", config={"model_reasoning_effort": "high"}
|
||||
)
|
||||
|
||||
first_turn = await original.turn("Tell me one fact about Saturn.")
|
||||
_ = await first_turn.run()
|
||||
print("Created thread:", original.id)
|
||||
|
||||
resumed = await codex.thread_resume(original.id)
|
||||
second_turn = await resumed.turn("Continue with one more fact.")
|
||||
second = await second_turn.run()
|
||||
print(second.final_response)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
23
sdk/python/examples/05_existing_thread/sync.py
Normal file
23
sdk/python/examples/05_existing_thread/sync.py
Normal file
@@ -0,0 +1,23 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
# Create an initial thread and turn so we have a real thread to resume.
|
||||
original = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"})
|
||||
first = original.turn("Tell me one fact about Saturn.").run()
|
||||
print("Created thread:", original.id)
|
||||
|
||||
# Resume the existing thread by ID.
|
||||
resumed = codex.thread_resume(original.id)
|
||||
second = resumed.turn("Continue with one more fact.").run()
|
||||
print(second.final_response)
|
||||
@@ -0,0 +1,60 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
|
||||
from openai_codex import AsyncCodex
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
thread = await codex.thread_start(
|
||||
model="gpt-5.4", config={"model_reasoning_effort": "high"}
|
||||
)
|
||||
first = await (await thread.turn("One sentence about structured planning.")).run()
|
||||
second = await (await thread.turn("Now restate it for a junior engineer.")).run()
|
||||
|
||||
reopened = await codex.thread_resume(thread.id)
|
||||
listing_active = await codex.thread_list(limit=20, archived=False)
|
||||
reading = await reopened.read(include_turns=True)
|
||||
|
||||
_ = await reopened.set_name("sdk-lifecycle-demo")
|
||||
_ = await codex.thread_archive(reopened.id)
|
||||
listing_archived = await codex.thread_list(limit=20, archived=True)
|
||||
unarchived = await codex.thread_unarchive(reopened.id)
|
||||
|
||||
resumed = await codex.thread_resume(
|
||||
unarchived.id,
|
||||
model="gpt-5.4",
|
||||
config={"model_reasoning_effort": "high"},
|
||||
)
|
||||
resumed_result = await (await resumed.turn("Continue in one short sentence.")).run()
|
||||
|
||||
forked = await codex.thread_fork(unarchived.id, model="gpt-5.4")
|
||||
forked_result = await (
|
||||
await forked.turn("Take a different angle in one short sentence.")
|
||||
).run()
|
||||
|
||||
compact_result = await unarchived.compact()
|
||||
|
||||
print("Lifecycle OK:", thread.id)
|
||||
print("first:", first.id, first.status)
|
||||
print("second:", second.id, second.status)
|
||||
print("read.turns:", len(reading.thread.turns))
|
||||
print("list.active:", len(listing_active.data))
|
||||
print("list.archived:", len(listing_archived.data))
|
||||
print("resumed:", resumed_result.id, resumed_result.status)
|
||||
print("forked:", forked_result.id, forked_result.status)
|
||||
print("compact:", compact_result.model_dump(mode="json", by_alias=True))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
48
sdk/python/examples/06_thread_lifecycle_and_controls/sync.py
Normal file
48
sdk/python/examples/06_thread_lifecycle_and_controls/sync.py
Normal file
@@ -0,0 +1,48 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"})
|
||||
first = thread.turn("One sentence about structured planning.").run()
|
||||
second = thread.turn("Now restate it for a junior engineer.").run()
|
||||
|
||||
reopened = codex.thread_resume(thread.id)
|
||||
listing_active = codex.thread_list(limit=20, archived=False)
|
||||
reading = reopened.read(include_turns=True)
|
||||
|
||||
_ = reopened.set_name("sdk-lifecycle-demo")
|
||||
_ = codex.thread_archive(reopened.id)
|
||||
listing_archived = codex.thread_list(limit=20, archived=True)
|
||||
unarchived = codex.thread_unarchive(reopened.id)
|
||||
|
||||
resumed = codex.thread_resume(
|
||||
unarchived.id,
|
||||
model="gpt-5.4",
|
||||
config={"model_reasoning_effort": "high"},
|
||||
)
|
||||
resumed_result = resumed.turn("Continue in one short sentence.").run()
|
||||
|
||||
forked = codex.thread_fork(unarchived.id, model="gpt-5.4")
|
||||
forked_result = forked.turn("Take a different angle in one short sentence.").run()
|
||||
|
||||
compact_result = unarchived.compact()
|
||||
|
||||
print("Lifecycle OK:", thread.id)
|
||||
print("first:", first.id, first.status)
|
||||
print("second:", second.id, second.status)
|
||||
print("read.turns:", len(reading.thread.turns))
|
||||
print("list.active:", len(listing_active.data))
|
||||
print("list.archived:", len(listing_archived.data))
|
||||
print("resumed:", resumed_result.id, resumed_result.status)
|
||||
print("forked:", forked_result.id, forked_result.status)
|
||||
print("compact:", compact_result.model_dump(mode="json", by_alias=True))
|
||||
37
sdk/python/examples/07_image_and_text/async.py
Normal file
37
sdk/python/examples/07_image_and_text/async.py
Normal file
@@ -0,0 +1,37 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, generated_sample_image_data_url, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
|
||||
from openai_codex import AsyncCodex, ImageInput, TextInput
|
||||
|
||||
IMAGE_DATA_URL = generated_sample_image_data_url()
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
thread = await codex.thread_start(
|
||||
model="gpt-5.4", config={"model_reasoning_effort": "high"}
|
||||
)
|
||||
turn = await thread.turn(
|
||||
[
|
||||
TextInput("What is in this image? Give 3 bullets."),
|
||||
ImageInput(IMAGE_DATA_URL),
|
||||
]
|
||||
)
|
||||
result = await turn.run()
|
||||
|
||||
print("Status:", result.status)
|
||||
print(result.final_response)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
26
sdk/python/examples/07_image_and_text/sync.py
Normal file
26
sdk/python/examples/07_image_and_text/sync.py
Normal file
@@ -0,0 +1,26 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, generated_sample_image_data_url, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import Codex, ImageInput, TextInput
|
||||
|
||||
IMAGE_DATA_URL = generated_sample_image_data_url()
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"})
|
||||
result = thread.turn(
|
||||
[
|
||||
TextInput("What is in this image? Give 3 bullets."),
|
||||
ImageInput(IMAGE_DATA_URL),
|
||||
]
|
||||
).run()
|
||||
|
||||
print("Status:", result.status)
|
||||
print(result.final_response)
|
||||
43
sdk/python/examples/08_local_image_and_text/async.py
Normal file
43
sdk/python/examples/08_local_image_and_text/async.py
Normal file
@@ -0,0 +1,43 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import (
|
||||
ensure_local_sdk_src,
|
||||
runtime_config,
|
||||
temporary_sample_image_path,
|
||||
)
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
|
||||
from openai_codex import AsyncCodex, LocalImageInput, TextInput
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
with temporary_sample_image_path() as image_path:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
thread = await codex.thread_start(
|
||||
model="gpt-5.4", config={"model_reasoning_effort": "high"}
|
||||
)
|
||||
|
||||
turn = await thread.turn(
|
||||
[
|
||||
TextInput(
|
||||
"Read this generated local image and summarize the colors/layout in 2 bullets."
|
||||
),
|
||||
LocalImageInput(str(image_path.resolve())),
|
||||
]
|
||||
)
|
||||
result = await turn.run()
|
||||
|
||||
print("Status:", result.status)
|
||||
print(result.final_response)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
32
sdk/python/examples/08_local_image_and_text/sync.py
Normal file
32
sdk/python/examples/08_local_image_and_text/sync.py
Normal file
@@ -0,0 +1,32 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import (
|
||||
ensure_local_sdk_src,
|
||||
runtime_config,
|
||||
temporary_sample_image_path,
|
||||
)
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import Codex, LocalImageInput, TextInput
|
||||
|
||||
with temporary_sample_image_path() as image_path:
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"})
|
||||
|
||||
result = thread.turn(
|
||||
[
|
||||
TextInput(
|
||||
"Read this generated local image and summarize the colors/layout in 2 bullets."
|
||||
),
|
||||
LocalImageInput(str(image_path.resolve())),
|
||||
]
|
||||
).run()
|
||||
|
||||
print("Status:", result.status)
|
||||
print(result.final_response)
|
||||
23
sdk/python/examples/09_async_parity/sync.py
Normal file
23
sdk/python/examples/09_async_parity/sync.py
Normal file
@@ -0,0 +1,23 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config, server_label
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
print("Server:", server_label(codex.metadata))
|
||||
|
||||
thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"})
|
||||
turn = thread.turn("Say hello in one sentence.")
|
||||
result = turn.run()
|
||||
|
||||
print("Thread:", thread.id)
|
||||
print("Turn:", result.id)
|
||||
print("Text:", result.final_response.strip())
|
||||
91
sdk/python/examples/10_error_handling_and_retry/async.py
Normal file
91
sdk/python/examples/10_error_handling_and_retry/async.py
Normal file
@@ -0,0 +1,91 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
import random
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import TypeVar
|
||||
|
||||
from openai_codex import (
|
||||
AsyncCodex,
|
||||
JsonRpcError,
|
||||
ServerBusyError,
|
||||
is_retryable_error,
|
||||
)
|
||||
from openai_codex.types import TurnStatus
|
||||
|
||||
ResultT = TypeVar("ResultT")
|
||||
|
||||
|
||||
async def retry_on_overload_async(
|
||||
op: Callable[[], Awaitable[ResultT]],
|
||||
*,
|
||||
max_attempts: int = 3,
|
||||
initial_delay_s: float = 0.25,
|
||||
max_delay_s: float = 2.0,
|
||||
jitter_ratio: float = 0.2,
|
||||
) -> ResultT:
|
||||
if max_attempts < 1:
|
||||
raise ValueError("max_attempts must be >= 1")
|
||||
|
||||
delay = initial_delay_s
|
||||
attempt = 0
|
||||
while True:
|
||||
attempt += 1
|
||||
try:
|
||||
return await op()
|
||||
except Exception as exc: # noqa: BLE001
|
||||
if attempt >= max_attempts or not is_retryable_error(exc):
|
||||
raise
|
||||
jitter = delay * jitter_ratio
|
||||
sleep_for = min(max_delay_s, delay) + random.uniform(-jitter, jitter)
|
||||
if sleep_for > 0:
|
||||
await asyncio.sleep(sleep_for)
|
||||
delay = min(max_delay_s, delay * 2)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
thread = await codex.thread_start(
|
||||
model="gpt-5.4", config={"model_reasoning_effort": "high"}
|
||||
)
|
||||
|
||||
try:
|
||||
result = await retry_on_overload_async(
|
||||
_run_turn(thread, "Summarize retry best practices in 3 bullets."),
|
||||
max_attempts=3,
|
||||
initial_delay_s=0.25,
|
||||
max_delay_s=2.0,
|
||||
)
|
||||
except ServerBusyError as exc:
|
||||
print("Server overloaded after retries:", exc.message)
|
||||
return
|
||||
except JsonRpcError as exc:
|
||||
print(f"JSON-RPC error {exc.code}: {exc.message}")
|
||||
return
|
||||
|
||||
if result.status == TurnStatus.failed:
|
||||
print("Turn failed:", result.error)
|
||||
return
|
||||
|
||||
print("Text:", result.final_response)
|
||||
|
||||
|
||||
def _run_turn(thread, prompt: str):
|
||||
async def _inner():
|
||||
turn = await thread.turn(prompt)
|
||||
return await turn.run()
|
||||
|
||||
return _inner
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
38
sdk/python/examples/10_error_handling_and_retry/sync.py
Normal file
38
sdk/python/examples/10_error_handling_and_retry/sync.py
Normal file
@@ -0,0 +1,38 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import (
|
||||
Codex,
|
||||
JsonRpcError,
|
||||
ServerBusyError,
|
||||
retry_on_overload,
|
||||
)
|
||||
from openai_codex.types import TurnStatus
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"})
|
||||
|
||||
try:
|
||||
result = retry_on_overload(
|
||||
lambda: thread.turn("Summarize retry best practices in 3 bullets.").run(),
|
||||
max_attempts=3,
|
||||
initial_delay_s=0.25,
|
||||
max_delay_s=2.0,
|
||||
)
|
||||
except ServerBusyError as exc:
|
||||
print("Server overloaded after retries:", exc.message)
|
||||
except JsonRpcError as exc:
|
||||
print(f"JSON-RPC error {exc.code}: {exc.message}")
|
||||
else:
|
||||
if result.status == TurnStatus.failed:
|
||||
print("Turn failed:", result.error)
|
||||
else:
|
||||
print("Text:", result.final_response)
|
||||
88
sdk/python/examples/11_cli_mini_app/async.py
Normal file
88
sdk/python/examples/11_cli_mini_app/async.py
Normal file
@@ -0,0 +1,88 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
|
||||
from openai_codex import (
|
||||
AsyncCodex,
|
||||
)
|
||||
from openai_codex.types import (
|
||||
ThreadTokenUsageUpdatedNotification,
|
||||
TurnCompletedNotification,
|
||||
)
|
||||
|
||||
|
||||
def _format_usage(usage: object) -> str:
|
||||
last = usage.last
|
||||
total = usage.total
|
||||
return (
|
||||
"usage>\n"
|
||||
f" last: input={last.input_tokens} output={last.output_tokens} reasoning={last.reasoning_output_tokens} total={last.total_tokens} cached={last.cached_input_tokens}\n"
|
||||
f" total: input={total.input_tokens} output={total.output_tokens} reasoning={total.reasoning_output_tokens} total={total.total_tokens} cached={total.cached_input_tokens}"
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
print("Codex async mini CLI. Type /exit to quit.")
|
||||
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
thread = await codex.thread_start(
|
||||
model="gpt-5.4", config={"model_reasoning_effort": "high"}
|
||||
)
|
||||
print("Thread:", thread.id)
|
||||
|
||||
while True:
|
||||
try:
|
||||
user_input = (await asyncio.to_thread(input, "you> ")).strip()
|
||||
except EOFError:
|
||||
break
|
||||
|
||||
if not user_input:
|
||||
continue
|
||||
if user_input in {"/exit", "/quit"}:
|
||||
break
|
||||
|
||||
turn = await thread.turn(user_input)
|
||||
usage = None
|
||||
status = None
|
||||
error = None
|
||||
|
||||
print("assistant> ", end="", flush=True)
|
||||
async for event in turn.stream():
|
||||
payload = event.payload
|
||||
if event.method == "item/agentMessage/delta":
|
||||
delta = payload.delta
|
||||
if delta:
|
||||
print(delta, end="", flush=True)
|
||||
continue
|
||||
if isinstance(payload, ThreadTokenUsageUpdatedNotification):
|
||||
usage = payload.token_usage
|
||||
continue
|
||||
if isinstance(payload, TurnCompletedNotification):
|
||||
status = payload.turn.status
|
||||
error = payload.turn.error
|
||||
|
||||
print()
|
||||
if status is None:
|
||||
raise RuntimeError("stream ended without turn/completed")
|
||||
if usage is None:
|
||||
raise RuntimeError("stream ended without token usage")
|
||||
|
||||
status_text = status.value
|
||||
print(f"assistant.status> {status_text}")
|
||||
if status_text == "failed":
|
||||
print("assistant.error>", error)
|
||||
|
||||
print(_format_usage(usage))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
79
sdk/python/examples/11_cli_mini_app/sync.py
Normal file
79
sdk/python/examples/11_cli_mini_app/sync.py
Normal file
@@ -0,0 +1,79 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import (
|
||||
Codex,
|
||||
)
|
||||
from openai_codex.types import (
|
||||
ThreadTokenUsageUpdatedNotification,
|
||||
TurnCompletedNotification,
|
||||
)
|
||||
|
||||
print("Codex mini CLI. Type /exit to quit.")
|
||||
|
||||
|
||||
def _format_usage(usage: object) -> str:
|
||||
last = usage.last
|
||||
total = usage.total
|
||||
return (
|
||||
"usage>\n"
|
||||
f" last: input={last.input_tokens} output={last.output_tokens} reasoning={last.reasoning_output_tokens} total={last.total_tokens} cached={last.cached_input_tokens}\n"
|
||||
f" total: input={total.input_tokens} output={total.output_tokens} reasoning={total.reasoning_output_tokens} total={total.total_tokens} cached={total.cached_input_tokens}"
|
||||
)
|
||||
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"})
|
||||
print("Thread:", thread.id)
|
||||
|
||||
while True:
|
||||
try:
|
||||
user_input = input("you> ").strip()
|
||||
except EOFError:
|
||||
break
|
||||
|
||||
if not user_input:
|
||||
continue
|
||||
if user_input in {"/exit", "/quit"}:
|
||||
break
|
||||
|
||||
turn = thread.turn(user_input)
|
||||
usage = None
|
||||
status = None
|
||||
error = None
|
||||
|
||||
print("assistant> ", end="", flush=True)
|
||||
for event in turn.stream():
|
||||
payload = event.payload
|
||||
if event.method == "item/agentMessage/delta":
|
||||
delta = payload.delta
|
||||
if delta:
|
||||
print(delta, end="", flush=True)
|
||||
continue
|
||||
if isinstance(payload, ThreadTokenUsageUpdatedNotification):
|
||||
usage = payload.token_usage
|
||||
continue
|
||||
if isinstance(payload, TurnCompletedNotification):
|
||||
status = payload.turn.status
|
||||
error = payload.turn.error
|
||||
|
||||
print()
|
||||
if status is None:
|
||||
raise RuntimeError("stream ended without turn/completed")
|
||||
if usage is None:
|
||||
raise RuntimeError("stream ended without token usage")
|
||||
|
||||
status_text = status.value
|
||||
print(f"assistant.status> {status_text}")
|
||||
if status_text == "failed":
|
||||
print("assistant.error>", error)
|
||||
|
||||
print(_format_usage(usage))
|
||||
83
sdk/python/examples/12_turn_params_kitchen_sink/async.py
Normal file
83
sdk/python/examples/12_turn_params_kitchen_sink/async.py
Normal file
@@ -0,0 +1,83 @@
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
|
||||
from openai_codex import (
|
||||
AsyncCodex,
|
||||
)
|
||||
from openai_codex.types import (
|
||||
ReasoningSummary,
|
||||
)
|
||||
|
||||
OUTPUT_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"summary": {"type": "string"},
|
||||
"actions": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
},
|
||||
},
|
||||
"required": ["summary", "actions"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
SUMMARY = ReasoningSummary.model_validate("concise")
|
||||
|
||||
PROMPT = (
|
||||
"Analyze a safe rollout plan for enabling a feature flag in production. "
|
||||
"Return JSON matching the requested schema."
|
||||
)
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
thread = await codex.thread_start(
|
||||
model="gpt-5.4", config={"model_reasoning_effort": "high"}
|
||||
)
|
||||
|
||||
turn = await thread.turn(
|
||||
PROMPT,
|
||||
output_schema=OUTPUT_SCHEMA,
|
||||
summary=SUMMARY,
|
||||
)
|
||||
result = await turn.run()
|
||||
structured_text = result.final_response.strip()
|
||||
try:
|
||||
structured = json.loads(structured_text)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise RuntimeError(
|
||||
f"Expected JSON matching OUTPUT_SCHEMA, got: {structured_text!r}"
|
||||
) from exc
|
||||
|
||||
summary = structured["summary"]
|
||||
actions = structured["actions"]
|
||||
if (
|
||||
not isinstance(summary, str)
|
||||
or not isinstance(actions, list)
|
||||
or not all(isinstance(action, str) for action in actions)
|
||||
):
|
||||
raise RuntimeError(
|
||||
f"Expected structured output with string summary/actions, got: {structured!r}"
|
||||
)
|
||||
|
||||
print("Status:", result.status)
|
||||
print("summary:", summary)
|
||||
print("actions:")
|
||||
for action in actions:
|
||||
print("-", action)
|
||||
print("Items:", len(result.items))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
73
sdk/python/examples/12_turn_params_kitchen_sink/sync.py
Normal file
73
sdk/python/examples/12_turn_params_kitchen_sink/sync.py
Normal file
@@ -0,0 +1,73 @@
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import (
|
||||
Codex,
|
||||
)
|
||||
from openai_codex.types import (
|
||||
ReasoningSummary,
|
||||
)
|
||||
|
||||
OUTPUT_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"summary": {"type": "string"},
|
||||
"actions": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
},
|
||||
},
|
||||
"required": ["summary", "actions"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
SUMMARY = ReasoningSummary.model_validate("concise")
|
||||
|
||||
PROMPT = (
|
||||
"Analyze a safe rollout plan for enabling a feature flag in production. "
|
||||
"Return JSON matching the requested schema."
|
||||
)
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"})
|
||||
|
||||
turn = thread.turn(
|
||||
PROMPT,
|
||||
output_schema=OUTPUT_SCHEMA,
|
||||
summary=SUMMARY,
|
||||
)
|
||||
result = turn.run()
|
||||
structured_text = result.final_response.strip()
|
||||
try:
|
||||
structured = json.loads(structured_text)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise RuntimeError(
|
||||
f"Expected JSON matching OUTPUT_SCHEMA, got: {structured_text!r}"
|
||||
) from exc
|
||||
|
||||
summary = structured["summary"]
|
||||
actions = structured["actions"]
|
||||
if (
|
||||
not isinstance(summary, str)
|
||||
or not isinstance(actions, list)
|
||||
or not all(isinstance(action, str) for action in actions)
|
||||
):
|
||||
raise RuntimeError(
|
||||
f"Expected structured output with string summary/actions, got: {structured!r}"
|
||||
)
|
||||
|
||||
print("Status:", result.status)
|
||||
print("summary:", summary)
|
||||
print("actions:")
|
||||
for action in actions:
|
||||
print("-", action)
|
||||
print("Items:", len(result.items))
|
||||
112
sdk/python/examples/13_model_select_and_turn_params/async.py
Normal file
112
sdk/python/examples/13_model_select_and_turn_params/async.py
Normal file
@@ -0,0 +1,112 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
|
||||
from openai_codex import (
|
||||
AsyncCodex,
|
||||
Sandbox,
|
||||
)
|
||||
from openai_codex.types import (
|
||||
ReasoningEffort,
|
||||
ReasoningSummary,
|
||||
)
|
||||
|
||||
REASONING_RANK = {
|
||||
"none": 0,
|
||||
"minimal": 1,
|
||||
"low": 2,
|
||||
"medium": 3,
|
||||
"high": 4,
|
||||
"xhigh": 5,
|
||||
"max": 6,
|
||||
"ultra": 7,
|
||||
}
|
||||
|
||||
|
||||
def _pick_highest_model(models):
|
||||
visible = [m for m in models if not m.hidden]
|
||||
if not visible:
|
||||
raise RuntimeError("models response did not include visible models")
|
||||
|
||||
known_names = {m.id for m in visible} | {m.model for m in visible}
|
||||
top_candidates = [m for m in visible if not (m.upgrade and m.upgrade in known_names)]
|
||||
if not top_candidates:
|
||||
raise RuntimeError("models response did not include top-level visible models")
|
||||
return max(top_candidates, key=lambda m: (m.model, m.id))
|
||||
|
||||
|
||||
def _pick_highest_turn_effort(model) -> ReasoningEffort:
|
||||
if not model.supported_reasoning_efforts:
|
||||
raise RuntimeError(f"{model.model} did not advertise supported reasoning efforts")
|
||||
|
||||
best = max(
|
||||
model.supported_reasoning_efforts,
|
||||
key=lambda option: REASONING_RANK[option.reasoning_effort.value],
|
||||
)
|
||||
return ReasoningEffort(best.reasoning_effort.value)
|
||||
|
||||
|
||||
OUTPUT_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"summary": {"type": "string"},
|
||||
"actions": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
},
|
||||
},
|
||||
"required": ["summary", "actions"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
models = await codex.models(include_hidden=True)
|
||||
selected_model = _pick_highest_model(models.data)
|
||||
selected_effort = _pick_highest_turn_effort(selected_model)
|
||||
|
||||
print("selected.model:", selected_model.model)
|
||||
print("selected.effort:", selected_effort.value)
|
||||
|
||||
thread = await codex.thread_start(
|
||||
model=selected_model.model,
|
||||
config={"model_reasoning_effort": selected_effort.value},
|
||||
)
|
||||
|
||||
first_turn = await thread.turn(
|
||||
"Give one short sentence about reliable production releases.",
|
||||
model=selected_model.model,
|
||||
effort=selected_effort,
|
||||
)
|
||||
first = await first_turn.run()
|
||||
|
||||
print("agent.message:", first.final_response)
|
||||
print("items:", len(first.items))
|
||||
|
||||
second_turn = await thread.turn(
|
||||
"Return JSON for a safe feature-flag rollout plan.",
|
||||
cwd=str(Path.cwd()),
|
||||
effort=selected_effort,
|
||||
model=selected_model.model,
|
||||
output_schema=OUTPUT_SCHEMA,
|
||||
sandbox=Sandbox.read_only,
|
||||
summary=ReasoningSummary.model_validate("concise"),
|
||||
)
|
||||
second = await second_turn.run()
|
||||
|
||||
print("agent.message.params:", second.final_response)
|
||||
print("items.params:", len(second.items))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
102
sdk/python/examples/13_model_select_and_turn_params/sync.py
Normal file
102
sdk/python/examples/13_model_select_and_turn_params/sync.py
Normal file
@@ -0,0 +1,102 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import (
|
||||
Codex,
|
||||
Sandbox,
|
||||
)
|
||||
from openai_codex.types import (
|
||||
ReasoningEffort,
|
||||
ReasoningSummary,
|
||||
)
|
||||
|
||||
REASONING_RANK = {
|
||||
"none": 0,
|
||||
"minimal": 1,
|
||||
"low": 2,
|
||||
"medium": 3,
|
||||
"high": 4,
|
||||
"xhigh": 5,
|
||||
"max": 6,
|
||||
"ultra": 7,
|
||||
}
|
||||
|
||||
|
||||
def _pick_highest_model(models):
|
||||
visible = [m for m in models if not m.hidden]
|
||||
if not visible:
|
||||
raise RuntimeError("models response did not include visible models")
|
||||
|
||||
known_names = {m.id for m in visible} | {m.model for m in visible}
|
||||
top_candidates = [m for m in visible if not (m.upgrade and m.upgrade in known_names)]
|
||||
if not top_candidates:
|
||||
raise RuntimeError("models response did not include top-level visible models")
|
||||
return max(top_candidates, key=lambda m: (m.model, m.id))
|
||||
|
||||
|
||||
def _pick_highest_turn_effort(model) -> ReasoningEffort:
|
||||
if not model.supported_reasoning_efforts:
|
||||
raise RuntimeError(f"{model.model} did not advertise supported reasoning efforts")
|
||||
|
||||
best = max(
|
||||
model.supported_reasoning_efforts,
|
||||
key=lambda option: REASONING_RANK[option.reasoning_effort.value],
|
||||
)
|
||||
return ReasoningEffort(best.reasoning_effort.value)
|
||||
|
||||
|
||||
OUTPUT_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"summary": {"type": "string"},
|
||||
"actions": {
|
||||
"type": "array",
|
||||
"items": {"type": "string"},
|
||||
},
|
||||
},
|
||||
"required": ["summary", "actions"],
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
models = codex.models(include_hidden=True)
|
||||
selected_model = _pick_highest_model(models.data)
|
||||
selected_effort = _pick_highest_turn_effort(selected_model)
|
||||
|
||||
print("selected.model:", selected_model.model)
|
||||
print("selected.effort:", selected_effort.value)
|
||||
|
||||
thread = codex.thread_start(
|
||||
model=selected_model.model,
|
||||
config={"model_reasoning_effort": selected_effort.value},
|
||||
)
|
||||
|
||||
first = thread.turn(
|
||||
"Give one short sentence about reliable production releases.",
|
||||
model=selected_model.model,
|
||||
effort=selected_effort,
|
||||
).run()
|
||||
|
||||
print("agent.message:", first.final_response)
|
||||
print("items:", len(first.items))
|
||||
|
||||
second = thread.turn(
|
||||
"Return JSON for a safe feature-flag rollout plan.",
|
||||
cwd=str(Path.cwd()),
|
||||
effort=selected_effort,
|
||||
model=selected_model.model,
|
||||
output_schema=OUTPUT_SCHEMA,
|
||||
sandbox=Sandbox.read_only,
|
||||
summary=ReasoningSummary.model_validate("concise"),
|
||||
).run()
|
||||
|
||||
print("agent.message.params:", second.final_response)
|
||||
print("items.params:", len(second.items))
|
||||
71
sdk/python/examples/14_turn_controls/async.py
Normal file
71
sdk/python/examples/14_turn_controls/async.py
Normal file
@@ -0,0 +1,71 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
|
||||
from openai_codex import AsyncCodex
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
thread = await codex.thread_start(
|
||||
model="gpt-5.4", config={"model_reasoning_effort": "high"}
|
||||
)
|
||||
steer_turn = await thread.turn("Count from 1 to 40 with commas, then one summary sentence.")
|
||||
steer_result = await steer_turn.steer("Keep it brief and stop after 10 numbers.")
|
||||
|
||||
steer_event_count = 0
|
||||
steer_completed_status = None
|
||||
steer_deltas = []
|
||||
async for event in steer_turn.stream():
|
||||
steer_event_count += 1
|
||||
if event.method == "item/agentMessage/delta":
|
||||
steer_deltas.append(event.payload.delta)
|
||||
continue
|
||||
if event.method == "turn/completed":
|
||||
steer_completed_status = event.payload.turn.status.value
|
||||
|
||||
if steer_completed_status is None:
|
||||
raise RuntimeError("stream ended without turn/completed")
|
||||
steer_preview = "".join(steer_deltas).strip()
|
||||
|
||||
interrupt_turn = await thread.turn(
|
||||
"Count from 1 to 200 with commas, then one summary sentence."
|
||||
)
|
||||
interrupt_result = await interrupt_turn.interrupt()
|
||||
|
||||
interrupt_event_count = 0
|
||||
interrupt_completed_status = None
|
||||
interrupt_deltas = []
|
||||
async for event in interrupt_turn.stream():
|
||||
interrupt_event_count += 1
|
||||
if event.method == "item/agentMessage/delta":
|
||||
interrupt_deltas.append(event.payload.delta)
|
||||
continue
|
||||
if event.method == "turn/completed":
|
||||
interrupt_completed_status = event.payload.turn.status.value
|
||||
|
||||
if interrupt_completed_status is None:
|
||||
raise RuntimeError("stream ended without turn/completed")
|
||||
interrupt_preview = "".join(interrupt_deltas).strip()
|
||||
|
||||
print("steer.result:", steer_result.model_dump(mode="json", by_alias=True))
|
||||
print("steer.final.status:", steer_completed_status)
|
||||
print("steer.events.count:", steer_event_count)
|
||||
print("steer.assistant.preview:", steer_preview)
|
||||
print("interrupt.result:", interrupt_result.model_dump(mode="json", by_alias=True))
|
||||
print("interrupt.final.status:", interrupt_completed_status)
|
||||
print("interrupt.events.count:", interrupt_event_count)
|
||||
print("interrupt.assistant.preview:", interrupt_preview)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
59
sdk/python/examples/14_turn_controls/sync.py
Normal file
59
sdk/python/examples/14_turn_controls/sync.py
Normal file
@@ -0,0 +1,59 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
thread = codex.thread_start(model="gpt-5.4", config={"model_reasoning_effort": "high"})
|
||||
steer_turn = thread.turn("Count from 1 to 40 with commas, then one summary sentence.")
|
||||
steer_result = steer_turn.steer("Keep it brief and stop after 10 numbers.")
|
||||
|
||||
steer_event_count = 0
|
||||
steer_completed_status = None
|
||||
steer_deltas = []
|
||||
for event in steer_turn.stream():
|
||||
steer_event_count += 1
|
||||
if event.method == "item/agentMessage/delta":
|
||||
steer_deltas.append(event.payload.delta)
|
||||
continue
|
||||
if event.method == "turn/completed":
|
||||
steer_completed_status = event.payload.turn.status.value
|
||||
|
||||
if steer_completed_status is None:
|
||||
raise RuntimeError("stream ended without turn/completed")
|
||||
steer_preview = "".join(steer_deltas).strip()
|
||||
|
||||
interrupt_turn = thread.turn("Count from 1 to 200 with commas, then one summary sentence.")
|
||||
interrupt_result = interrupt_turn.interrupt()
|
||||
|
||||
interrupt_event_count = 0
|
||||
interrupt_completed_status = None
|
||||
interrupt_deltas = []
|
||||
for event in interrupt_turn.stream():
|
||||
interrupt_event_count += 1
|
||||
if event.method == "item/agentMessage/delta":
|
||||
interrupt_deltas.append(event.payload.delta)
|
||||
continue
|
||||
if event.method == "turn/completed":
|
||||
interrupt_completed_status = event.payload.turn.status.value
|
||||
|
||||
if interrupt_completed_status is None:
|
||||
raise RuntimeError("stream ended without turn/completed")
|
||||
interrupt_preview = "".join(interrupt_deltas).strip()
|
||||
|
||||
print("steer.result:", steer_result.model_dump(mode="json", by_alias=True))
|
||||
print("steer.final.status:", steer_completed_status)
|
||||
print("steer.events.count:", steer_event_count)
|
||||
print("steer.assistant.preview:", steer_preview)
|
||||
print("interrupt.result:", interrupt_result.model_dump(mode="json", by_alias=True))
|
||||
print("interrupt.final.status:", interrupt_completed_status)
|
||||
print("interrupt.events.count:", interrupt_event_count)
|
||||
print("interrupt.assistant.preview:", interrupt_preview)
|
||||
34
sdk/python/examples/15_login_and_account/async.py
Normal file
34
sdk/python/examples/15_login_and_account/async.py
Normal file
@@ -0,0 +1,34 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
import asyncio
|
||||
|
||||
from openai_codex import AsyncCodex
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
# Browser login returns a live handle. Open `auth_url` and await `wait()`
|
||||
# in a real app; this example cancels immediately so it stays non-blocking.
|
||||
login = await codex.login_chatgpt()
|
||||
canceled = await login.cancel()
|
||||
completed = await login.wait()
|
||||
account = await codex.account()
|
||||
|
||||
print("login.id:", login.login_id)
|
||||
print("login.auth_url:", login.auth_url)
|
||||
print("login.cancel.status:", canceled.status)
|
||||
print("login.completed.success:", completed.success)
|
||||
print("account.requires_openai_auth:", account.requires_openai_auth)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
26
sdk/python/examples/15_login_and_account/sync.py
Normal file
26
sdk/python/examples/15_login_and_account/sync.py
Normal file
@@ -0,0 +1,26 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import Codex
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
# Browser login returns a live handle. Open `auth_url` and call `wait()`
|
||||
# in a real app; this example cancels immediately so it stays non-blocking.
|
||||
login = codex.login_chatgpt()
|
||||
canceled = login.cancel()
|
||||
completed = login.wait()
|
||||
account = codex.account()
|
||||
|
||||
print("login.id:", login.login_id)
|
||||
print("login.auth_url:", login.auth_url)
|
||||
print("login.cancel.status:", canceled.status)
|
||||
print("login.completed.success:", completed.success)
|
||||
print("account.requires_openai_auth:", account.requires_openai_auth)
|
||||
40
sdk/python/examples/16_external_message/async.py
Normal file
40
sdk/python/examples/16_external_message/async.py
Normal file
@@ -0,0 +1,40 @@
|
||||
"""Process an untrusted notification within a task authorized by the user."""
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import AsyncCodex, ExternalMessage, Sandbox
|
||||
|
||||
|
||||
async def main() -> None:
|
||||
async with AsyncCodex(config=runtime_config()) as codex:
|
||||
thread = await codex.thread_start(sandbox=Sandbox.read_only)
|
||||
await thread.run(
|
||||
"When deployment notifications arrive, summarize their status and suggest "
|
||||
"what I should check. Do not change files or deploy anything."
|
||||
)
|
||||
|
||||
# External content has tool authority; it does not supply user permission.
|
||||
result = await thread.run(
|
||||
ExternalMessage(
|
||||
tool_name="notifications",
|
||||
namespace="slack",
|
||||
content="Staging deployment failed: the health check returned HTTP 503.",
|
||||
),
|
||||
source="slack_notification",
|
||||
)
|
||||
print("status:", result.status)
|
||||
print("text:", result.final_response)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
33
sdk/python/examples/16_external_message/sync.py
Normal file
33
sdk/python/examples/16_external_message/sync.py
Normal file
@@ -0,0 +1,33 @@
|
||||
"""Process an untrusted notification within a task authorized by the user."""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
_EXAMPLES_ROOT = Path(__file__).resolve().parents[1]
|
||||
if str(_EXAMPLES_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_EXAMPLES_ROOT))
|
||||
|
||||
from _bootstrap import ensure_local_sdk_src, runtime_config
|
||||
|
||||
ensure_local_sdk_src()
|
||||
|
||||
from openai_codex import Codex, ExternalMessage, Sandbox
|
||||
|
||||
with Codex(config=runtime_config()) as codex:
|
||||
thread = codex.thread_start(sandbox=Sandbox.read_only)
|
||||
thread.run(
|
||||
"When deployment notifications arrive, summarize their status and suggest "
|
||||
"what I should check. Do not change files or deploy anything."
|
||||
)
|
||||
|
||||
# External content has tool authority; it does not supply user permission.
|
||||
result = thread.run(
|
||||
ExternalMessage(
|
||||
tool_name="notifications",
|
||||
namespace="slack",
|
||||
content="Staging deployment failed: the health check returned HTTP 503.",
|
||||
),
|
||||
source="slack_notification",
|
||||
)
|
||||
print("status:", result.status)
|
||||
print("text:", result.final_response)
|
||||
97
sdk/python/examples/README.md
Normal file
97
sdk/python/examples/README.md
Normal file
@@ -0,0 +1,97 @@
|
||||
# Python SDK Examples
|
||||
|
||||
Each example folder contains runnable versions:
|
||||
|
||||
- `sync.py` (public sync surface: `Codex`)
|
||||
- `async.py` (public async surface: `AsyncCodex`)
|
||||
|
||||
All examples intentionally use only public SDK exports from `openai_codex`
|
||||
and `openai_codex.types`.
|
||||
|
||||
Examples use plain strings for text-only turns and typed input objects for
|
||||
multimodal or structured input lists.
|
||||
|
||||
Use `ExternalMessage` for untrusted content from another agent, tool, or
|
||||
application. It retains tool-level authority and does not grant user
|
||||
authorization or approval; example 16 establishes the user's task first.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Python `>=3.10`
|
||||
- Install the SDK for the same Python interpreter you will use to run examples
|
||||
|
||||
Install the published SDK:
|
||||
|
||||
```bash
|
||||
python -m pip install openai-codex
|
||||
```
|
||||
|
||||
The SDK installs its pinned `openai-codex-cli-bin` runtime dependency.
|
||||
The pinned runtime version comes from the SDK package dependency.
|
||||
|
||||
## Run From A Checkout
|
||||
|
||||
Contributors using these checked-in scripts should install development
|
||||
dependencies from `sdk/python`:
|
||||
|
||||
```bash
|
||||
uv sync --group dev
|
||||
source .venv/bin/activate
|
||||
```
|
||||
|
||||
The examples bootstrap local SDK imports from `sdk/python/src`. If the pinned
|
||||
runtime is not already installed, the bootstrap installs the matching runtime
|
||||
package for the active interpreter and cleans up temporary files afterward.
|
||||
|
||||
## Run examples
|
||||
|
||||
From `sdk/python`:
|
||||
|
||||
```bash
|
||||
python examples/<example-folder>/sync.py
|
||||
python examples/<example-folder>/async.py
|
||||
```
|
||||
|
||||
The checked-in examples use the local SDK source tree automatically.
|
||||
|
||||
## Recommended first run
|
||||
|
||||
```bash
|
||||
python examples/01_quickstart_constructor/sync.py
|
||||
python examples/01_quickstart_constructor/async.py
|
||||
```
|
||||
|
||||
## Index
|
||||
|
||||
- `01_quickstart_constructor/`
|
||||
- first run / sanity check
|
||||
- `02_turn_run/`
|
||||
- inspect full turn output fields
|
||||
- `03_turn_stream_events/`
|
||||
- stream a turn with a small curated event view
|
||||
- `04_models_and_metadata/`
|
||||
- discover visible models for the connected runtime
|
||||
- `05_existing_thread/`
|
||||
- resume a real existing thread (created in-script)
|
||||
- `06_thread_lifecycle_and_controls/`
|
||||
- thread lifecycle + control calls
|
||||
- `07_image_and_text/`
|
||||
- image data URL + text multimodal turn
|
||||
- `08_local_image_and_text/`
|
||||
- local image + text multimodal turn using a generated temporary sample image
|
||||
- `09_async_parity/`
|
||||
- parity-style sync flow (see async parity in other examples)
|
||||
- `10_error_handling_and_retry/`
|
||||
- overload retry pattern + typed error handling structure
|
||||
- `11_cli_mini_app/`
|
||||
- interactive chat loop
|
||||
- `12_turn_params_kitchen_sink/`
|
||||
- structured output with a curated advanced `turn(...)` configuration
|
||||
- `13_model_select_and_turn_params/`
|
||||
- list models, pick highest model + highest supported reasoning effort, run turns, print message and usage
|
||||
- `14_turn_controls/`
|
||||
- separate `steer()` and `interrupt()` demos with concise summaries
|
||||
- `15_login_and_account/`
|
||||
- browser-login handle lifecycle, cancellation, and account inspection
|
||||
- `16_external_message/`
|
||||
- process an untrusted external notification within a user-authorized task
|
||||
113
sdk/python/examples/_bootstrap.py
Normal file
113
sdk/python/examples/_bootstrap.py
Normal file
@@ -0,0 +1,113 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import sys
|
||||
import tempfile
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterator
|
||||
|
||||
_SDK_PYTHON_DIR = Path(__file__).resolve().parents[1]
|
||||
_SDK_PYTHON_STR = str(_SDK_PYTHON_DIR)
|
||||
if _SDK_PYTHON_STR not in sys.path:
|
||||
sys.path.insert(0, _SDK_PYTHON_STR)
|
||||
|
||||
from _runtime_setup import ensure_runtime_package_installed
|
||||
|
||||
|
||||
def _ensure_runtime_dependencies(sdk_python_dir: Path) -> None:
|
||||
if importlib.util.find_spec("pydantic") is not None:
|
||||
return
|
||||
|
||||
python = sys.executable
|
||||
raise RuntimeError(
|
||||
"Missing required dependency: pydantic.\n"
|
||||
f"Interpreter: {python}\n"
|
||||
"Install dependencies with the same interpreter used to run this example:\n"
|
||||
f" cd {sdk_python_dir} && uv sync\n"
|
||||
"Then activate `.venv`, or reinstall with the Python interpreter above."
|
||||
)
|
||||
|
||||
|
||||
def ensure_local_sdk_src() -> Path:
|
||||
"""Add sdk/python/src to sys.path so examples run without installing the package."""
|
||||
sdk_python_dir = _SDK_PYTHON_DIR
|
||||
src_dir = sdk_python_dir / "src"
|
||||
package_dir = src_dir / "openai_codex"
|
||||
if not package_dir.exists():
|
||||
raise RuntimeError(f"Could not locate local SDK package at {package_dir}")
|
||||
|
||||
_ensure_runtime_dependencies(sdk_python_dir)
|
||||
|
||||
src_str = str(src_dir)
|
||||
if src_str not in sys.path:
|
||||
sys.path.insert(0, src_str)
|
||||
return src_dir
|
||||
|
||||
|
||||
def runtime_config():
|
||||
"""Return an example-friendly CodexConfig for repo-source SDK usage."""
|
||||
from openai_codex import CodexConfig
|
||||
|
||||
ensure_runtime_package_installed(sys.executable, _SDK_PYTHON_DIR)
|
||||
return CodexConfig()
|
||||
|
||||
|
||||
def _png_chunk(chunk_type: bytes, data: bytes) -> bytes:
|
||||
import struct
|
||||
|
||||
payload = chunk_type + data
|
||||
checksum = zlib.crc32(payload) & 0xFFFFFFFF
|
||||
return struct.pack(">I", len(data)) + payload + struct.pack(">I", checksum)
|
||||
|
||||
|
||||
def _generated_sample_png_bytes() -> bytes:
|
||||
import struct
|
||||
|
||||
width = 96
|
||||
height = 96
|
||||
top_left = (120, 180, 255)
|
||||
top_right = (255, 220, 90)
|
||||
bottom_left = (90, 180, 95)
|
||||
bottom_right = (180, 85, 85)
|
||||
|
||||
rows = bytearray()
|
||||
for y in range(height):
|
||||
rows.append(0)
|
||||
for x in range(width):
|
||||
if y < height // 2 and x < width // 2:
|
||||
color = top_left
|
||||
elif y < height // 2:
|
||||
color = top_right
|
||||
elif x < width // 2:
|
||||
color = bottom_left
|
||||
else:
|
||||
color = bottom_right
|
||||
rows.extend(color)
|
||||
|
||||
header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ _png_chunk(b"IHDR", header)
|
||||
+ _png_chunk(b"IDAT", zlib.compress(bytes(rows)))
|
||||
+ _png_chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def generated_sample_image_data_url() -> str:
|
||||
encoded = base64.b64encode(_generated_sample_png_bytes()).decode("ascii")
|
||||
return f"data:image/png;base64,{encoded}"
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def temporary_sample_image_path() -> Iterator[Path]:
|
||||
with tempfile.TemporaryDirectory(prefix="codex-python-example-image-") as temp_root:
|
||||
image_path = Path(temp_root) / "generated_sample.png"
|
||||
image_path.write_bytes(_generated_sample_png_bytes())
|
||||
yield image_path
|
||||
|
||||
|
||||
def server_label(metadata: Any) -> str:
|
||||
return f"{metadata.serverInfo.name} {metadata.serverInfo.version}"
|
||||
Reference in New Issue
Block a user