> ## Documentation Index
> Fetch the complete documentation index at: https://docs.anycrm.anyreach.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Generate a Competitive Brief

Gated by the `ai.competitive_intelligence` config feature flag — a `403` names the flag when disabled.

The representative **async** AI-generation endpoint on this router — it writes a placeholder row, kicks off a background job, and returns `202` immediately so the request never blocks on an LLM call. [Generate a Deal Brief](/api-reference/deals/generate-brief) follows the identical pattern.

### Auth

Requires a CRM manage [scope](/authentication#scopes) and an active organization on the token. Any `*:manage` scope qualifies — in practice `contacts:manage`, `deals:manage`, `companies:manage`, or `activities:manage`.

### Flow

1. **Not `force` and a completed brief exists** → returns it immediately, `200 {success: true, skipped: true, id, payload, generated_at, source}`.
2. **Not `force` and a brief is currently generating** → `202 {accepted: true, already_running: true, id, message}`.
3. **Otherwise** → (if `force`, first deletes any stuck `ci_generating` placeholder rows), inserts a placeholder brief row, schedules a background job, and returns immediately: `202 {accepted: true, skipped: false, id, payload: <placeholder>, generated_at, source: "ci_generating", message}`.

The background job runs the same name-detection cascade as [Detect Competitors](/api-reference/deals/detect-competitors), then synthesizes the full brief via an LLM (Anthropic primary, OpenAI fallback, a minimal deterministic template if both are unavailable), PATCHes the same brief row with the final `payload` and a `ci_<source>` label, and re-syncs `deal_competitors` from the resulting battlecard names. A failure mid-job persists an error payload into the same row (`source: "ci_error"`) instead of leaving it stuck generating — poll [Get the Latest Competitive Brief](/api-reference/deals/get-competitive-intelligence) until `payload.metadata._ci_generating` is gone.

### Payload shape (once complete)

| Field                                        | Type      | Description                                                                                                                 |
| -------------------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------- |
| `schema_version`                             | `integer` | Always `1`.                                                                                                                 |
| `executive_overview.porters_five_forces`     | `object`  | `{forces: [{label, level, score, score_label}], summary}`.                                                                  |
| `executive_overview.swot`                    | `object`  | `{strengths, weaknesses, opportunities, threats}` (string arrays).                                                          |
| `executive_overview.competitive_positioning` | `object`  | Axis labels + `points: [{name, x, y, is_us, website?, x_rationale, y_rationale, supporting_stats?, market_share?}]`.        |
| `executive_overview.jobs_to_be_done`         | `object`  | `{items: [{title, us_score, benchmark_label, benchmark_score}]}`.                                                           |
| `executive_overview.strategic_groups`        | `object`  | `{groups: [{name, description, competitors}]}`.                                                                             |
| `executive_overview.feature_matrix`          | `object`  | `{features, us_label, scores, score_rationales}` — scores are `1`–`3` per competitor per feature.                           |
| `executive_overview.executive_summary`       | `object`  | `{top_competitive_moves, market_narrative, this_weeks_actions}`.                                                            |
| `executive_overview.high_impact_signals`     | array     | `{competitor, signal_type, period, text, impact_score, severity, evidence_url, affects}`.                                   |
| `executive_overview.recommended_plays`       | array     | `{role, effort, reversibility, title, objective, risk, first_24h}`.                                                         |
| `executive_overview.watchlist`               | array     | `{trigger, where_to_watch, owner_role, condition}`.                                                                         |
| `battlecards`                                | `object`  | Keyed by **exact competitor name**: `{why_buyers_choose, when_they_win, when_we_win, landmines, talk_track, proof_points}`. |
| `metadata`                                   | `object`  | `{competitor_count, model, name_detection_source, generated_at, _ci_generating?, _ci_error?, warning?, degraded?}`.         |

### Errors

| Status | Cause                                                   |
| ------ | ------------------------------------------------------- |
| `400`  | Deal has no linked account, or the account has no name. |
| `403`  | `ai.competitive_intelligence` feature disabled.         |
| `404`  | Deal not found.                                         |
| `502`  | Failed to write the placeholder brief row.              |


## OpenAPI

````yaml POST /deals/{deal_id}/competitive-intelligence/generate
openapi: 3.1.0
info:
  title: anycrm-api
  version: 0.0.1
servers: []
security: []
tags:
  - name: Customer Intelligence
    description: >-
      Company research and ICP-fit scoring — create a research run, track its
      progress, and read back scored companies as leads.
  - name: Outreach
    description: >-
      The cold-email management console — domains, mailboxes, and campaigns — as
      a thin control plane over the SalesForge stack.
  - name: AnyCard
    description: >-
      Authenticated CRUD for AnyCard, the org's digital business-card /
      lead-capture product.
  - name: AnyCard Events
    description: >-
      Event-attribution analytics for AnyCard — which captured leads converted,
      broken down by source, owner, and deal.
  - name: AnyCard Share Links
    description: >-
      Unauthenticated endpoints reached by anyone who scans a QR code or opens a
      shared AnyCard link.
  - name: AI
    description: >-
      A streaming (SSE) AI chat endpoint with account-commit actions it can take
      on the caller's behalf.
  - name: Analytics Assistant
    description: >-
      The natural-language analytics assistant — a guarded text-to-SQL loop
      (SSE) that answers ad-hoc questions over the org's CRM data as a
      least-privilege, read-only database role.
  - name: Account Readiness
    description: >-
      Account Readiness Profiles — AI-scored signals on whether an account is
      ready for outreach or expansion, computed via a Temporal workflow.
  - name: Integrations
    description: >-
      Pipedream Connect — issuing connect tokens and managing the org's
      connected third-party accounts.
  - name: Feedback
    description: >-
      User-submitted platform feedback (bug reports, feature requests) — global,
      not scoped to one organization.
  - name: Public Media
    description: >-
      Unauthenticated image reads for publicly-embeddable assets (card photos,
      inline email images) — allowlisted by key shape; everything else in the
      storage bucket stays private.
  - name: Service Health
    description: Service liveness.
paths:
  /deals/{deal_id}/competitive-intelligence/generate:
    post:
      tags:
        - Deals
      summary: Generate Competitive Intelligence
      operationId: >-
        generate_competitive_intelligence_deals__deal_id__competitive_intelligence_generate_post
      parameters:
        - name: deal_id
          in: path
          required: true
          schema:
            type: string
            description: The deal's id.
            title: Deal Id
          description: The deal's id.
      requestBody:
        content:
          application/json:
            schema:
              anyOf:
                - $ref: '#/components/schemas/CompetitiveIntelligenceGenerateRequest'
                - type: 'null'
              title: Body
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema: {}
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
      security:
        - HTTPBearer: []
components:
  schemas:
    CompetitiveIntelligenceGenerateRequest:
      properties:
        force:
          type: boolean
          title: Force
          description: Regenerate even if a completed brief already exists.
          default: false
      type: object
      title: CompetitiveIntelligenceGenerateRequest
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
  securitySchemes:
    HTTPBearer:
      type: http
      scheme: bearer

````