# HTTP chat reliability

Get one request working before adding chat history, retries, or saved state. Use the provider’s documented endpoint and supply credentials at runtime, never in source.

- **Send the expected types.** OpenAI Responses accepts a string or typed input items, not a list of bare strings. Keep token limits numeric and flags Boolean. [Request contract](https://developers.openai.com/api/reference/resources/responses/methods/create).
- **Check status before reading text.** Read `error`, `status`, and `incomplete_details` first. In raw Responses HTTP JSON, read message content in `output`; the SDK’s `output_text` helper is not a guaranteed JSON field. Keep refusals, tool-only responses, and empty completed answers distinct. [Response items](https://developers.openai.com/api/docs/guides/migrate-to-responses).
- **Keep the last usable conversation.** Start new in memory, then replace saved state only after a usable response and a successful write. Keep an incomplete response ID separately, label partial text, and never silently repeat a paid call. A response ID does not guarantee it can be resumed. [Output and reasoning limits](https://developers.openai.com/api/docs/guides/reasoning).
- **Make each exit match what happened.** On the last turn, don’t offer a follow-up. Saving before a dialog means dismissing it won’t undo the write; saving after a dialog means cancellation might prevent the write. Say “Saved” only after storage returns.

## OpenAI Responses example

Enter an API key and a model ID available to your OpenAI project when the shortcut runs. The key is sent to OpenAI and is not saved by this example. Each turn can incur API charges. With `store: true`, OpenAI retains responses for continuation; the shortcut saves response IDs locally, not the full conversation. Test it on your device before relying on it.

```shortcuty
shortcut:
  chosen_model = input.ask(prompt: "OpenAI model ID", type: "Text")
  model = trim(chosen_model)
  guard model is not empty else:
    flow.stop()
  entered_key = input.ask(prompt: "OpenAI API key", type: "Text")
  api_key = trim(entered_key)
  guard api_key is not empty else:
    flow.stop()
  authorization = text("Bearer \(api_key)")
  active_id = storage.get<Text>("ChatExampleResume_v1") ?? ""
  menu("Conversation"):
    case "Resume saved":
      active_id = active_id
    case "Start new":
      active_id = ""
  repeat 30 times:
    entered = input.ask(prompt: "Message?", type: "Text")
    submitted = trim(entered)
    guard submitted is not empty else:
      flow.stop()
    if active_id is not empty:
      payload = {"model": model, "input": submitted, "max_output_tokens": 4096, "store": true, "previous_response_id": active_id}
    else:
      payload = {"model": model, "input": submitted, "max_output_tokens": 4096, "store": true}
    response = web.request(url: "https://api.openai.com/v1/responses", method: "POST", headers: {"Authorization": authorization}, json: payload) else:
      alert("No response. Saved conversation unchanged.")
      flow.stop()
    if response["error"] has value:
      alert("Service error. Saved conversation unchanged.")
      flow.stop()
    response_id = ""
    if let raw_id = response["id"]:
      response_id = trim(text("\(raw_id)"))
    status = ""
    if let raw_status = response["status"]:
      status = text("\(raw_status)")
    incomplete_reason = "unknown"
    if let details = response["incomplete_details"]:
      if let reason = details["reason"]:
        incomplete_reason = text("\(reason)")
    answer = ""
    refused = false
    if let output_items = response["output"]:
      for item in output_items:
        output_item = item
        if output_item["type"] == "message":
          if let content_parts = output_item["content"]:
            for item in content_parts:
              part = item
              if part["type"] == "output_text":
                if let part_text = part["text"]:
                  answer = text("\(answer)\(part_text)")
              if part["type"] == "refusal":
                refused = true
    if status == "incomplete":
      if response_id is not empty:
        storage.set<Text>("ChatExamplePending_v1", response_id)
      if answer is not empty:
        result("Partial answer: \(answer)")
      if incomplete_reason == "max_output_tokens":
        alert("Output allowance exhausted, possibly during reasoning. Saved conversation unchanged.")
      else:
        alert("Incomplete response: \(incomplete_reason). Saved conversation unchanged.")
      flow.stop()
    guard status == "completed" else:
      alert("Unexpected response status. Saved conversation unchanged.")
      flow.stop()
    if refused:
      alert("The model declined this request. Saved conversation unchanged.")
      flow.stop()
    answer = trim(answer)
    guard answer is not empty else:
      alert("Completed without answer text. Saved conversation unchanged.")
      flow.stop()
    guard response_id is not empty else:
      alert("Missing response ID. Saved conversation unchanged.")
      flow.stop()
    storage.set<Text>("ChatExampleResume_v1", response_id)
    active_id = response_id
    result("Saved conversation. Closing this dialog does not undo the save.\n\(answer)")
    if repeat_index == 30:
      result("Turn limit reached. The saved conversation remains available.")
      flow.stop()
    menu("Next"):
      case "Follow up":
        active_id = response_id
      case "New chat":
        active_id = ""
      case "Done":
        flow.stop()
```
