{"record":{"id":"b2e9ee3ac32116a6","repo":"invoke-ai/InvokeAI","slug":"str-e-valueerror-relationship-already-exists","errorCode":null,"errorMessage":"str(e) (ValueError, relationship already exists)","messagePattern":"str\\(e\\) \\(ValueError, relationship already exists\\)","errorType":"http","errorClass":"HTTPException","httpStatus":409,"severity":"info","filePath":"invokeai/app/api/routers/model_relationships.py","lineNumber":132,"sourceCode":") -> None:\n    \"\"\"\n    Add a relationship between two models.\n\n    Relationships are bidirectional and will be accessible from both models.\n\n    - Raises 400 if keys are invalid or identical.\n    - Raises 409 if the relationship already exists.\n    \"\"\"\n    if req.model_key_1 == req.model_key_2:\n        raise HTTPException(status_code=400, detail=\"Cannot relate a model to itself.\")\n\n    try:\n        ApiDependencies.invoker.services.model_relationships.add_model_relationship(\n            req.model_key_1,\n            req.model_key_2,\n        )\n    except ValueError as e:\n        raise HTTPException(status_code=409, detail=str(e))\n\n\n@model_relationships_router.delete(\n    \"/\",\n    status_code=status.HTTP_204_NO_CONTENT,\n    responses={\n        204: {\"description\": \"The relationship was successfully removed\"},\n        400: {\"description\": \"Invalid model keys or self-referential relationship\"},\n        404: {\"description\": \"The relationship does not exist\"},\n        422: {\"description\": \"Validation error\"},\n        500: {\"description\": \"Internal server error\"},\n    },\n    summary=\"Remove Model Relationship\",\n    description=\"Removes a **bidirectional** relationship between two models. The relationship must already exist.\",\n)\ndef remove_model_relationship(\n    current_user: AdminUserOrDefault,\n    req: ModelRelationshipCreateRequest = Body(..., description=\"The model keys to disconnect\"),","sourceCodeStart":114,"sourceCodeEnd":150,"githubUrl":"https://github.com/invoke-ai/InvokeAI/blob/0b6a024f2ff6a86bfb953dcdb9cc504ef7397a06/invokeai/app/api/routers/model_relationships.py#L114-L150","documentation":"HTTP 409 raised when the model relationships service throws ValueError because the exact bidirectional relationship between the two keys already exists. Since relationships are unique unordered pairs, adding the same pair twice collides.","triggerScenarios":"POST /api/v1/models/relationships with a (key1, key2) pair that was already related in either order; duplicate form submissions; scripts that don't check for existing relationships before adding.","commonSituations":"Re-running an idempotency-breaking sync script; double-clicking the 'relate' button; importing a relationships list that contains duplicates.","solutions":["Treat 409 as success (the relationship exists) and continue","Before adding, call GET related-models for one key and skip pairs already present","Deduplicate the input pair list and use 'add or ignore' logic in scripts","Wrap the call so ValueError/409 is swallowed but other errors propagate"],"exampleFix":"// before\nawait api.addRelationship({ model_key_1: a, model_key_2: b });\n// after\ntry {\n  await api.addRelationship({ model_key_1: a, model_key_2: b });\n} catch (e) {\n  if (e.status !== 409) throw e; // already related — fine\n}","handlingStrategy":"try-catch","validationCode":"const existing = new Set(await api.getRelatedModels(key1));\nif (existing.has(key2)) {\n  console.log('already related');\n} else {\n  await api.addRelationship({ model_key_1: key1, model_key_2: key2 });\n}","typeGuard":null,"tryCatchPattern":"try {\n  await api.addRelationship({ model_key_1: a, model_key_2: b });\n} catch (e) {\n  if (e.status === 409) return; // idempotent no-op\n  throw e;\n}","preventionTips":["Treat 'already exists' as success in scripts","Check existing relationships before adding","Debounce/duplicate-guard the relate button in UIs"],"tags":["http-409","duplicate","model-relationships"],"backgroundTag":"duplicate-resource-conflict","analyzedSha":"0b6a024f2ff6a86bfb953dcdb9cc504ef7397a06","analyzedAt":"2026-08-29T04:46:49.967Z","schemaVersion":2},"datasetVersion":"2026-08-29T07:17:48.351Z"}