Emend
API Reference

Interaction Management

Methods for publishing, searching, retrieving, and deleting user interactions.

publish_interactionmethod

Publish user interactions to the system. This is the primary method for sending data to Emend.

Async counterpart
Async applications can call await client.publish_interaction_async(...) with the same parameters and return type. It uses native async HTTP, applies the client's total timeout, and preserves task cancellation.
response = client.publish_interaction(    user_id,    interactions,    session_id="session_abc",    source="",    agent_version="agent-v0",    wait_for_response=False,    skip_aggregation=False,    force_extraction=False,    evaluation_only=False,    override_learning_stall=False,    retrieval_experiment_id=None,    retrieval_experiment_arm=None,)
Report the Emend context used by each response
If an agent response was produced with profiles or playbooks retrieved from Emend, add every injected learning to that response's retrieved_learnings. When the session is evaluated, Emend can then show whether each learning was relevant and whether its impact was positive, neutral, or negative. This attribution also provides the signal needed to improve future optimization of retrieved learnings. Omit the field only when no Emend learning was injected.
PropType
user_idrequiredstring
interactionsrequiredlist[InteractionData | dict]
sourcestring
agent_versionstring
session_idrequiredstring
wait_for_responseboolean
skip_aggregationboolean
force_extractionboolean
evaluation_onlyboolean
override_learning_stallboolean
retrieval_experiment_idstring
retrieval_experiment_arm"treatment" | "holdout"
Publish retrieval experiment attribution
When a learning-search response includes experiment, echo its experiment_id and arm on every related publish. Both treatment and holdout publish normally; do not set evaluation_only=True merely because the user is in holdout. Omit both fields when the search response has no experiment.

Returns: PublishUserInteractionResponse. In wait_for_response=False mode the response carries success, message, learning_status="deferred", and a request_id (so you can poll immediately); profile/playbook deltas are 0 because extraction has not run yet. In wait_for_response=True mode it also includes storage routing and real profile/playbook deltas. Use get_learning_status to poll for extraction progress after a deferred publish.

Client-side validation errors
Raises pydantic.ValidationError locally, before any HTTP request, when an interaction is contradictory or the whole batch is empty:
  • every interaction is empty (no content, shadow_content, expert_content, interacted_image_url, image_encoding, tools_used, citations, retrieved_learnings, and a user_action of none)
  • a user_action other than none with no user_action_description
  • both interacted_image_url and image_encoding set
The message names the offending interaction_data_list index. Because this fires client-side, try/except around HTTP status codes will not catch it, and there is no response object with success=False — the equivalent over raw HTTP is a 422. A missing or blank session_id raises ValueError.

Individually empty interactions are dropped rather than raising, so one empty placeholder turn does not fail a batch that also carries real turns. Unrecognised keys are discarded, not rejected — but both the drops and the unbound field names are listed in the returned warnings, so check it rather than only success. See Interaction Models.

Evaluation-Only Publish

Set evaluation_only=True when a session should be graded but should not teach Emend new profiles or playbooks, such as an offline candidate transcript. Do not use it for a retrieval-experiment holdout: both experiment arms should publish and learn normally so retrieval is the only controlled difference.

from emend import InteractionData, EmendClient client = EmendClient() client.publish_interaction(    user_id="user_123",    session_id="session_001",    source="prod_without_emend",    agent_version="v2.1.0",    evaluation_only=True,    interactions=[        InteractionData(role="User", content="Can you help me reset my account password?"),        InteractionData(role="Agent", content="Open Account Settings, choose Security, then select Reset Password."),    ],)

evaluation_only=True stores the request, schedules session-level success evaluation if the session passes agent_success_config.evaluation_only_sampling_rate, and excludes the request from profile extraction, playbook extraction, and aggregation. When that override is null, it inherits the current agent_success_config.sampling_rate. Retrieved-learning evaluation keeps its independent retrieved_learning_sampling_rate. The flag does not bypass the session inactivity delay, and it is not an experiment grouping dimension. Keep evaluation_only consistent across every publish in one session.

Interaction Dict Fields

PropType
created_atinteger
rolestring
contentstring
shadow_contentstring
expert_contentstring
image_encodingstring
user_actionUserActionType
user_action_descriptionstring
interacted_image_urlstring
tools_usedlist[ToolUsed | dict]
citationslist[Citation]
retrieved_learningslist[RetrievedLearning | dict]

Returns PublishUserInteractionResponse — see Interaction Models.

Examples

publish_interaction-examples.py
# Example 1: Basic Text Conversation (fire-and-forget)client.publish_interaction(    user_id="user_123",    interactions=[        {"role": "User", "content": "What's the weather like?"},        {"role": "Agent", "content": "It's sunny and 72°F today."}    ],    source="support-agent:v2",    session_id="session_001") # Example 2: Publish Retrieved Learnings — attach every Emend profile or# playbook injected into the agent's context to the response that used it.client.publish_interaction(    user_id="user_123",    interactions=[        {"role": "User", "content": "Recommend a laptop for my next work trip."},        {            "role": "Agent",            "content": "Choose a lightweight model with long battery life.",            "retrieved_learnings": [                {"kind": "profile", "learning_id": "prof-abc123"},                {"kind": "user_playbook", "learning_id": "42"},                {"kind": "agent_playbook", "learning_id": "7"},            ],        },    ],    session_id="session_001",    source="support-agent:v2",) # Example 3: Multi-Turn Conversation with Agent Versionclient.publish_interaction(    user_id="customer_456",    interactions=[        {"role": "User", "content": "I need help choosing a laptop"},        {"role": "Agent", "content": "I'd be happy to help! What's your budget?"},        {"role": "User", "content": "Around $1000 for programming work"},        {"role": "Agent", "content": "For programming, I recommend the ThinkPad X1..."}    ],    source="support-agent:v2",    agent_version="v2.1.0",    session_id="purchase_flow_789") # Example 4: Image Interactionsimport base64 def encode_image(path):    with open(path, "rb") as f:        return base64.b64encode(f.read()).decode("utf-8") client.publish_interaction(    user_id="user_123",    interactions=[        {            "role": "User",            "content": "What do you think of this outfit?",            "image_encoding": encode_image("outfit.jpg")        },        {"role": "Agent", "content": "Great choice! The colors complement each other well."}    ],    source="styling_consultation",    session_id="style_session_001") # Example 5: Expert Content for Learning from Expertsclient.publish_interaction(    user_id="user_123",    interactions=[        {"role": "User", "content": "What is your return policy for electronics?"},        {            "role": "Agent",            "content": "You can return electronics within 30 days.",            "expert_content": (                "Electronics can be returned within 30 days with the original receipt. "                "Items must be in original packaging. Opened software is final sale. "                "Defective items have a 90-day return window."            )        }    ],    source="expert_review",    agent_version="v1.0",    session_id="expert_session_001") # Example 6: User Action Trackingclient.publish_interaction(    user_id="shopper_789",    interactions=[        {            "user_action": "click",            "user_action_description": "Clicked 'Add to Cart' for MacBook Pro",            "interacted_image_url": "https://store.com/products/macbook-pro.jpg"        },        {            "user_action": "scroll",            "user_action_description": "Scrolled through laptop accessories"        }    ],    source="ecommerce",    session_id="shopping_session_001")
search_interactionsmethod

Search for user interactions using semantic queries.

response = client.search_interactions(    user_id="user_123",    query="laptop recommendations",    top_k=5,    most_recent_k=10)
PropType
user_idrequiredstring
request_idstring
querystring
start_timedatetime
end_timedatetime
top_kinteger
most_recent_kinteger
thresholdfloat
search_modeSearchMode

Returns SearchInteractionResponse — see Interaction Models.

get_interactionsmethod

Retrieve user interactions without semantic search.

response = client.get_interactions(    user_id="user_123",    top_k=50)
PropType
user_idrequiredstring
start_timedatetime
end_timedatetime
top_kinteger

Returns GetInteractionsResponse — see Interaction Models.

get_all_interactionsmethod

Get all user interactions across all users (admin operation).

response = client.get_all_interactions(limit=100)
PropType
limitinteger

Returns: GetInteractionsViewResponse with interactions from all users.

get_learning_statusmethod

Poll the learning status for a previously published request. Call this after a deferred publish_interaction (where wait_for_response=False). The response from the deferred path carries learning_status="deferred" to signal that extraction has been queued; use this method to track progress.

status = client.get_learning_status(request_id="req_abc123")# Returns one of: "pending", "processing", "done", "failed"
PropType
request_idrequiredstring

Returns: str — one of "pending" | "processing" | "done" | "failed". See LearningStatusResponse.

ValueMeaning
pendingExtraction queued but not yet started
processingA durable-queue worker is currently processing this request
doneExtraction completed successfully
failedExtraction failed permanently (dead job)
Info
This endpoint reads learning_jobs rows written by the durable queue. When the durable queue is off (in-memory deferred path), status is absence-based: "pending" for recent requests, "done" for requests older than 72 hours.

Example: Publish and poll until done

poll-until-done.py
import time response = client.publish_interaction(    user_id="user_123",    interactions=[{"role": "User", "content": "Help me with X"}],    session_id="sess_001",    wait_for_response=False,)# response.learning_status == "deferred" # The deferred response carries a request_id directly — no need to make a# throwaway wait_for_response=True call first.request_id = response.request_id for _ in range(30):  # poll up to 30 seconds    status = client.get_learning_status(request_id)    if status in ("done", "failed"):        print(f"Learning {status}")        break    time.sleep(1)
delete_interactionmethod

Delete a specific user interaction.

response = client.delete_interaction(    user_id,    interaction_id,    wait_for_response=False)
PropType
user_idrequiredstring
interaction_idrequiredinteger
wait_for_responseboolean

Returns DeleteUserInteractionResponse — see Interaction Models.