OpenAI-Compatible API
MedBackend provides an OpenAI-compatible API layer that allows you to integrate LLM capabilities into your healthcare applications while automatically storing all conversations in FHIR Communication resources. This enables seamless AI integration with full audit trails, RBAC compliance, and FHIR-native conversation history.
Overview
The OpenAI API layer acts as a middleware that:
- Accepts requests in the OpenAI
/v1/chat/completionsformat - Stores user prompts as FHIR Communication resources with
ai-promptcategory - Forwards requests to your configured LLM provider
- Stores AI responses as FHIR Communication resources with
ai-responsecategory - Returns responses in OpenAI-compatible format (streaming and non-streaming)
- Maintains conversation threading via
partOfandinResponseToreferences
Key Benefits
| Benefit | Description |
|---|---|
| Drop-in Replacement | Use existing OpenAI SDKs with minimal code changes |
| FHIR-Native Storage | All conversations stored as Communication resources |
| Audit Trail | Complete history of all AI interactions |
| RBAC Integration | AI access is governed by your project's permission rules — see the prerequisites |
| Your own model provider | Each agent calls the provider and endpoint you configure, with your key |
| Streaming Support | Full SSE streaming for real-time responses |
Architecture
┌──────────────────────────────────────────────────────────────────────┐
│ Your Application │
│ (OpenAI SDK / HTTP Client) │
└──────────────────────┬────────────────────────────────────────────────┘
│ POST /v1/chat/completions
│ { messages: [...], stream: true, ... }
▼
┌──────────────────────────────────────────────────────────────────────┐
│ 1. Authenticate the request │
│ 2. Store the prompt as a FHIR Communication (ai-prompt) │
│ 3. Load prior conversation history, if conversation_id is given │
│ 4. Forward the prompt to your configured LLM provider │
│ 5. Store the response as a FHIR Communication (ai-response) │
└──────────────────────┬────────────────────────────────────────────────┘
│ OpenAI-compatible response
│ (streamed via SSE, or a single JSON body)
▼
┌──────────────────────────────────────────────────────────────────────┐
│ Your Application │
└──────────────────────────────────────────────────────────────────────┘
Request Flow
The following diagram illustrates the complete request lifecycle for both streaming and non-streaming requests:
Client MedBackend
│ │
│ 1. POST /v1/chat/completions │
│ Authorization: Bearer <jwt> │
│ X-Project-ID: <project-id> │
│ { │
│ "messages": [...], │
│ "stream": true, │
│ "conversation_id": "conv-001" │
│ } │
├──────────────────────────────────────────▶│
│ │
│ │ 2. Authenticates and authorises the
│ │ request, then stores the prompt
│ │ as a FHIR Communication
│ │ (ai-prompt)
│ │
│ │ 3. Loads prior conversation history,
│ │ if conversation_id is given, and
│ │ forwards it to your configured
│ │ LLM provider
│ │
│ 4. SSE Stream (if stream: true) │
│◀──────────────────────────────────────────│
│ data: {"choices":[{"delta": │
│ {"content":"Based"}}]} │
│ │
│◀──────────────────────────────────────────│
│ data: {"choices":[{"delta": │
│ {"content":" on"}}]} │
│ │
│ ... (streaming continues) ... │
│ │
│◀──────────────────────────────────────────│
│ data: {"choices":[{"delta":{}, │
│ "finish_reason":"stop"}]} │
│ │
│◀──────────────────────────────────────────│
│ data: [DONE] │
│ │
│ │ 5. Stores the response as a FHIR
│ │ Communication (ai-response)
│ │
│ 6. Continue conversation... │
│ (new request with same │
│ conversation_id) │
│ │
Non-Streaming Flow
For non-streaming requests (stream: false), the flow is the same up to this point, except the response is returned as a single JSON object once the LLM provider completes, instead of a stream of SSE chunks:
Client MedBackend
│ │
│ POST /v1/chat/completions │
│ { "stream": false, ... } │
├──────────────────────────────────────────▶│
│ │
│ (steps 2-3 same as above) │
│ │
│ Complete JSON response │
│◀──────────────────────────────────────────│
│ { │
│ "id": "chatcmpl-abc123", │
│ "choices": [{ │
│ "message": { │
│ "role": "assistant", │
│ "content": "Based on your..." │
│ }, │
│ "finish_reason": "stop" │
│ }], │
│ "conversation_id": "conv-001", │
│ "communication_id": "comm-response-456" │
│ } │
│ │
Key Points
| Step | Description | FHIR Impact |
|---|---|---|
| 1 | Client sends request | - |
| 2 | Authenticate & store prompt | Communication created (ai-prompt) |
| 3 | Load history & forward to provider | Communications in thread, filtered by your project's RBAC |
| 4 | Stream response | Real-time SSE delivery |
| 5 | Store AI response | Communication created (ai-response) |
| 6 | Continue conversation | Use same conversation_id |
RBAC Prerequisites
Read this before enabling an agent. Conversation history is read back through your project's own RBAC rules, exactly like any other FHIR read. If the rules are missing, the assistant still answers — it just has no memory of the conversation.
The rule you need
For every entity type allowed to use the agent, your project needs a rule permitting it to read Communication:
| Entity type | Resource | Operation | Validator | Sees a message where they are its |
|---|---|---|---|---|
Patient | Communication | read | patient_compartment | subject, sender or recipient |
Practitioner | Communication | read | practitioner_compartment | sender or recipient |
RelatedPerson | Communication | read | relatedperson_compartment | sender or recipient |
Add them in the dashboard under the project's RBAC configuration. The entity types that need one are the same list you set as the agent's allowed entities.
The last column is what keeps this safe, and it comes from the FHIR R4 compartment definitions rather than from us. A caller reads only the threads they are a party to — granting the rule does not expose one user's conversation to another, so it is safe to grant to every entity type that uses the agent.
The agent's own Device identity needs Communication create to write messages; that part is provided by the platform and you do not configure it.
read, not search
A read rule covers both operations — a search with no search rule of its own is decided by the read rules for the same resource. The reverse is not true: a search-only rule leaves the single-message read denied, so the thread still fails to load. Always grant read.
What it looks like when the rule is missing
There is no error. The request succeeds, the response is well-formed, and the model replies as if the conversation had just started:
User: "I'm worried about the side effects you mentioned."
Assistant: "I'd be happy to help. Which medication are you asking about?"
Nothing in the API response indicates that history was withheld — the write path is not permission-gated, so each turn is stored correctly even while none of them can be read back. If your agent appears to forget everything between turns, check this before anything else.
Default templates
The Patient Portal template ships Patient → Communication read and create. The Clinical Provider (EHR) template ships Practitioner → Communication read.
Applying a template only affects the project you apply it to, at the moment you apply it — a project configured before these rules existed, or configured by hand, will not have them.
Endpoints
POST /v1/chat/completions
Send a chat completion request. Compatible with the OpenAI API format.
Headers:
Authorization: Bearer <your-jwt-token>
Content-Type: application/json
X-Project-ID: <your-project-id>
Request Body:
{
"messages": [
{"role": "system", "content": "You are a helpful medical assistant."},
{"role": "user", "content": "What medications am I currently taking?"}
],
"stream": true,
"model": "gpt-4o",
"conversation_id": "comm-001",
"patient_id": "patient-123",
"max_tokens": 1000,
"temperature": 0.7
}
| Field | Type | Required | Description |
|---|---|---|---|
messages | array | Yes | Array of message objects in OpenAI format |
stream | boolean | No | Enable SSE streaming (default: false) |
model | string | No | Model override (uses configured default if not specified) |
conversation_id | string | No | Continue an existing conversation |
patient_id | string | No | Patient context for FHIR queries — authorization-checked, see Patient context |
max_tokens | integer | No | Maximum tokens in response |
temperature | float | No | Sampling temperature (0-2) |
Patient context
A patient_id in the request body is an assertion about someone else's chart, so it is not taken on trust. Before the value is used, it is normalised to a bare patient id and then read back through your project's own RBAC rules — the same read a Patient(id:) GraphQL query performs. Only a permitted read lets the value reach the stored Communication and the agent's grounding context.
- Your project needs a
Patientreadrule for the calling entity type. There is no separate patient permission for the chat proxy: if the caller could not read that patient through the FHIR API, they cannot name them here either. (Which entity types may reach an agent at all is a separate, deny-by-default setting — see RBAC Prerequisites.) - A reference is normalised before it is checked, and the normalised form is what is used.
Patient/patient-123andpatient-123are equivalent. A value naming a different resource type, or one that is not a usable id, is refused. - Omitting
patient_idis not the same as being refused one. With nopatient_idin the body, the patient context is derived from the authenticated token when the caller is aPatient. APractitioner,DeviceorRelatedPersoncaller that sends nopatient_idgets no patient context at all. - Being permitted to read a patient does not make the patient a party to the message. The stored
Communicationreferences the patient assubjectonly when the caller is that patient, and asaboutotherwise — so a practitioner's AI consult about a patient does not become readable by that patient.
When the check fails the request is refused with 403 before any call to the LLM provider:
{
"error": {
"message": "Not permitted to reference the requested patient",
"type": "permission_denied"
}
}
That message is fixed. "You may not read that patient", "no such patient", and "that is not a usable patient id" all produce this identical response, deliberately — distinguishing them would let the endpoint be used to test whether a given identifier belongs to a patient at your organization. The reason is recorded in the audit trail and the server log; it is never returned to the caller.
conversation_id is authorized separately, with the same shape of refusal: 403 and Not permitted to continue the requested conversation.
Response (Non-Streaming):
{
"id": "chatcmpl-abc123",
"object": "chat.completion",
"created": 1705312800,
"model": "openai/gpt-4o",
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": "Based on your records, you are currently taking..."
},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 50,
"completion_tokens": 100,
"total_tokens": 150
},
"conversation_id": "comm-001",
"communication_id": "comm-response-456"
}
Response (Streaming):
When stream: true, responses are delivered as Server-Sent Events (SSE):
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Based"},"finish_reason":null}]}
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" on"},"finish_reason":null}]}
...
data: {"id":"chatcmpl-abc123","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]
GET /v1/models
List available models configured for your project.
Response:
{
"object": "list",
"data": [{
"id": "openai/gpt-4o",
"object": "model",
"owned_by": "medbackend"
}]
}
Integration Examples
Python (OpenAI SDK)
from openai import OpenAI
# Point the SDK to MedBackend
client = OpenAI(
base_url="https://your-medbackend.com/v1",
api_key="your-jwt-token",
default_headers={
"X-Project-ID": "your-project-id"
}
)
# Non-streaming request
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "system", "content": "You are a helpful medical assistant."},
{"role": "user", "content": "What are my recent lab results?"}
],
extra_body={
"patient_id": "patient-123",
"conversation_id": "existing-conv-id" # Optional: continue conversation
}
)
print(response.choices[0].message.content)
Python (Streaming)
from openai import OpenAI
client = OpenAI(
base_url="https://your-medbackend.com/v1",
api_key="your-jwt-token",
default_headers={"X-Project-ID": "your-project-id"}
)
# Streaming request
stream = client.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "Explain my diagnosis in simple terms."}
],
stream=True,
extra_body={"patient_id": "patient-123"}
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
JavaScript/TypeScript
import OpenAI from 'openai';
const client = new OpenAI({
baseURL: 'https://your-medbackend.com/v1',
apiKey: 'your-jwt-token',
defaultHeaders: {
'X-Project-ID': 'your-project-id'
}
});
// Non-streaming
const response = await client.chat.completions.create({
model: 'gpt-4o',
messages: [
{ role: 'user', content: 'What medications am I taking?' }
],
// MedBackend-specific parameters
patient_id: 'patient-123',
conversation_id: 'conv-001'
} as any);
console.log(response.choices[0].message.content);
JavaScript (Streaming)
const stream = await client.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Summarize my health history.' }],
stream: true,
patient_id: 'patient-123'
} as any);
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) {
process.stdout.write(content);
}
}
cURL
# Non-streaming
curl -X POST https://your-medbackend.com/v1/chat/completions \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-H "X-Project-ID: your-project-id" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "What are my allergies?"}
],
"patient_id": "patient-123"
}'
# Streaming
curl -X POST https://your-medbackend.com/v1/chat/completions \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-H "Content-Type: application/json" \
-H "X-Project-ID: your-project-id" \
-N \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "Explain my lab results."}
],
"stream": true,
"patient_id": "patient-123"
}'
Conversation Threading
MedBackend automatically manages conversation history using FHIR Communication resources. When you provide a conversation_id, the system:
- Loads all previous messages in the conversation
- Includes them in the context sent to the LLM
- Links new messages using
partOfandinResponseToreferences
Starting a New Conversation
Omit conversation_id to start a new conversation. The response will include the new conversation_id:
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "Hello!"}]
)
# Save this for continuing the conversation
conversation_id = response.conversation_id
Continuing a Conversation
Include the conversation_id to continue:
response = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What did I ask about earlier?"}],
extra_body={"conversation_id": conversation_id}
)
FHIR Communication Storage
All messages are stored as FHIR Communication resources:
User Prompt (ai-prompt)
{
"resourceType": "Communication",
"id": "comm-prompt-123",
"status": "completed",
"category": [{
"coding": [{
"system": "http://medbackend.com/fhir/communication-category",
"code": "ai-prompt",
"display": "AI Prompt"
}]
}],
"subject": {
"reference": "Patient/patient-123"
},
"sender": {
"reference": "Practitioner/user-456"
},
"sent": "2025-01-13T10:30:00Z",
"payload": [{
"contentString": "What medications am I currently taking?"
}],
"partOf": [{
"reference": "Communication/conversation-root"
}]
}
AI Response (ai-response)
{
"resourceType": "Communication",
"id": "comm-response-789",
"status": "completed",
"category": [{
"coding": [{
"system": "http://medbackend.com/fhir/communication-category",
"code": "ai-response",
"display": "AI Response"
}]
}],
"subject": {
"reference": "Patient/patient-123"
},
"sender": {
"reference": "Device/ai-agent-default"
},
"sent": "2025-01-13T10:30:05Z",
"payload": [{
"contentString": "Based on your records, you are currently taking..."
}],
"partOf": [{
"reference": "Communication/conversation-root"
}],
"inResponseTo": [{
"reference": "Communication/comm-prompt-123"
}]
}
Configuration
Agents are configured in the dashboard, under the project's developer tools. Each agent names a provider, the endpoint to call and the API key you supply for it; the key is stored by the platform and never returned. A request that names an agent is forwarded to that agent's backend. A request that names no agent uses the platform's default model.
Error Handling
The API returns standard HTTP status codes with detailed error messages:
| Status | Meaning |
|---|---|
400 | Invalid request body or parameters — including a conversation_id that is not a usable Communication reference |
401 | Missing or invalid Authorization header, or token validation failed |
403 | Denied: the agent, the named patient, or the named conversation is not permitted to this caller |
500 | Server error, including a failure reaching the LLM provider on the default (non-agent) path |
502 | The FHIR server, or a configured agent backend, could not be reached |
An outage is never rendered as a denial: an unreachable FHIR server answers 502, not 403.
/v1/chat/completions has no rate limit of any kind, so it never returns 429. The platform's two rate limits apply to the GraphQL view — both /graphql and /graphql-simple, which share one decorator — and to POST /api/account/token/device/, and both are currently log-only — requests that cross them are served normally, so neither of those endpoints returns 429 today either. No client needs 429 handling for this API yet.
Error Response Format:
{
"error": {
"message": "Not permitted to reference the requested patient",
"type": "permission_denied"
}
}
Every error carries a human-readable message in error.message. Where present, error.type is one of invalid_request_error, permission_denied, permission_error, authentication_error, upstream_error, configuration_error, internal_error, server_error; some errors add code and details.
Do not branch on the message text — the refusals above deliberately share one wording across several distinct causes.
Best Practices
Security
- Always use HTTPS in production
- Rotate JWT tokens regularly
- Use patient-scoped queries when accessing patient data
- Review audit logs for AI interactions
Performance
- Use streaming for long responses to improve perceived latency
- Batch related queries when possible
- Consider conversation length - very long histories may impact response time
Conversation Management
- Store
conversation_idfor multi-turn conversations - Use descriptive system prompts for consistent AI behavior
- Consider implementing conversation summarization for very long threads
RBAC Integration
- The AI agent applies your existing FHIR RBAC rules to every patient and conversation it touches
- Which entity types may reach an agent at all is a separate, deny-by-default setting configured per project — a project with no such configuration denies every chat request
- A
patient_idyou send is checked against the project'sPatientreadrules before it is used; grant that rule to any entity type that needs to name a patient - Configure appropriate validation rules for Communication resources
Troubleshooting
Common Issues
The assistant has no memory of previous turns:
- The most common cause is a missing RBAC rule, and it produces no error — see RBAC Prerequisites
- Check that every entity type allowed to use the agent has a
Communicationreadrule in the project's RBAC configuration - A
search-only rule is not sufficient - Confirm you are sending the same
conversation_idon each turn; a new id starts a new thread by design
"Unauthorized" errors:
- Verify your JWT token is valid and not expired
- Ensure the
X-Project-IDheader is included - Check that your user has the required permissions
403 on a request that names a patient_id or a conversation_id:
- The response is deliberately the same whether the resource does not exist or you are not permitted to reference it — do not read it as "not found"
- Confirm the calling entity type has a
Patientreadrule (forpatient_id) or aCommunicationreadrule (forconversation_id) in the project's RBAC configuration - Confirm the id belongs to the project named by your token
- The specific reason is in the project's audit trail
Streaming not working:
- Check that your client supports SSE
- Verify there are no proxies buffering the response
- Use
Accept: text/event-streamheader
Slow responses:
- Check LLM provider status
- Reduce conversation history length
- Consider using a faster model for simple queries