> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/bnares/AI-BIM-APP/llms.txt
> Use this file to discover all available pages before exploring further.

# AI Assistant

> Ask questions about your BIM models using ChatGPT integration for intelligent IFC data analysis

## Overview

The AI Assistant feature integrates OpenAI's ChatGPT to provide intelligent analysis of your IFC building models. Ask natural language questions about your project and receive instant answers based on the actual data in your IFC files.

<Info>
  The AI Assistant analyzes actual IFC data from your loaded models, ensuring accurate and contextual responses specific to your project.
</Info>

## How It Works

The AI Assistant uses a sophisticated pipeline to process your questions:

<Steps>
  <Step title="IFC Data Extraction">
    When you load an IFC file, the system reads the entire file content and extracts relevant IFC entities.
  </Step>

  <Step title="Data Filtering">
    The system filters IFC data to include only relevant entities (materials, walls, slabs, beams, and spatial relationships).
  </Step>

  <Step title="Query Processing">
    Your question is combined with the filtered IFC data and sent to ChatGPT-3.5-turbo for analysis.
  </Step>

  <Step title="Contextual Response">
    ChatGPT analyzes the IFC data and provides answers based solely on the information in your file.
  </Step>
</Steps>

## Supported Query Types

The AI Assistant can answer various types of questions about your BIM model:

<CardGroup cols={2}>
  <Card title="Material Queries" icon="brush">
    "What materials are used in this building?"

    "List all concrete materials"

    "What is the material of wall #2586?"
  </Card>

  <Card title="Building Storey Questions" icon="building">
    "How many floors does this building have?"

    "What elements are on Level 2?"

    "List all building storeys"
  </Card>

  <Card title="Element Counting" icon="hashtag">
    "How many walls are in the model?"

    "Count all slabs"

    "How many beams are used?"
  </Card>

  <Card title="Property Information" icon="list">
    "What are the properties of element #1234?"

    "Show me wall properties"

    "What is the height of Level 1?"
  </Card>
</CardGroup>

## Technical Implementation

### ChatGPT Component

The AI Assistant is implemented as a custom OpenBIM component:

<CodeGroup>
  ```typescript ChatGpt/index.ts:14-23 theme={null}
  export class ChatGpt extends OBC.Component{
    enabled: boolean = true;
    static uuid = OBC.UUID.create();
    fileData : string | null = null; 

    constructor(components:OBC.Components){
      super(components);
      components.add(ChatGpt.uuid, this);
    }
  }
  ```
</CodeGroup>

### IFC Data Storage

When an IFC file is loaded, its content is stored for AI analysis:

<CodeGroup>
  ```typescript LoadIfc/index.ts:72-82 theme={null}
  const reader = new FileReader();
  let fileCOntent : string = ""
  reader.onload = function(event){
    const myData = event.target?.result;
    if(typeof myData ==="string"){
      fileCOntent = myData;
      gpt.fileData = myData;
    }
  }
  reader.readAsText(file);
  ```
</CodeGroup>

## Data Filtering for AI Analysis

To optimize AI responses and reduce token usage, the system filters IFC data to include only relevant entities:

<CodeGroup>
  ```typescript ChatGpt/index.ts:37-59 theme={null}
  modifyDataDile = ()=>{
    if(! this.fileData) return;
    const validENtities = new Set([
      "IFCMATERIAL",
      "IfcRelAssociatesMaterial".toUpperCase(),
      "IfcBuildingStorey".toUpperCase(),
      "IfcRelContainedInSpatialStructure".toUpperCase(),
      "IFCWALL",
      "IFCSLAB",
      "IFCBEAM",
    ]);

    var result = this.fileData.split("\n").filter(line=>{
      const pattern = new RegExp("^#\\d+=(\\w+)");
      const match = line.match(/^#\d+\s*=\s*(\w+)/);
      if(!match) return false;
      const entityName = match[1].trim();
      return validENtities.has(entityName.toUpperCase());
    }).join("\n");
    return result;
  }
  ```
</CodeGroup>

### Filtered IFC Entities

The system focuses on these key IFC types for AI analysis:

<AccordionGroup>
  <Accordion title="IFCMATERIAL">
    All material definitions including names, properties, and associations with building elements.
  </Accordion>

  <Accordion title="IfcRelAssociatesMaterial">
    Relationships linking materials to building elements, enabling material-based queries.
  </Accordion>

  <Accordion title="IfcBuildingStorey">
    Floor level information including names, elevations, and spatial containment.
  </Accordion>

  <Accordion title="IfcRelContainedInSpatialStructure">
    Relationships defining which elements are contained in each building storey.
  </Accordion>

  <Accordion title="IFCWALL / IFCSLAB / IFCBEAM">
    Structural element definitions with geometric and property data.
  </Accordion>
</AccordionGroup>

## API Integration

The assistant communicates with OpenAI's API to process queries:

<CodeGroup>
  ```typescript ChatGpt/index.ts:61-92 theme={null}
  sendQuerryToGPT = async (data:GptData)=>{
    const {message, fileData} = data;
    const apiKey = import.meta.env.VITE_OPENAI_API_KEY;

    const response = await fetch("https://api.openai.com/v1/chat/completions",{
      method:"POST",
      headers:{
        "Content-Type": "application/json",
        "Authorization": `Bearer ${apiKey}`
      },
      body: JSON.stringify({
        model:"gpt-3.5-turbo",
        messages:[
          { 
            role:"system",  
            content:`Based on the given data answear question about ifc file.
                    You should only create the response based on the information given.
                    Information that is not found on given file should not be presented.
                    Please answear the questions using as few words as possible
          ` 
          },
          { 
            role: "user", 
            content: `Here is the file content:\n${this.fileData}\n\nNow answer this question: ${message} using only given content` 
          }
        ]
      })
    });
    const responseData = await response.json();
    return responseData;
  }
  ```
</CodeGroup>

### System Prompt Design

The AI Assistant uses a carefully crafted system prompt that:

<CardGroup cols={2}>
  <Card title="Ensures Accuracy" icon="check-circle">
    Instructs ChatGPT to only use information explicitly found in the IFC file data
  </Card>

  <Card title="Promotes Brevity" icon="compress">
    Requests concise answers using as few words as possible for quick insights
  </Card>

  <Card title="Prevents Hallucination" icon="shield">
    Explicitly prevents the AI from generating information not present in the file
  </Card>

  <Card title="Context-Aware" icon="brain">
    Provides full IFC context to enable accurate, project-specific responses
  </Card>
</CardGroup>

## User Interface

The AI Assistant panel provides a clean interface for interaction:

<CodeGroup>
  ```typescript ChatGpt/src/user-interface.ts:42-56 theme={null}
  return BUI.html`
    <bim-toolbar-section label="AI Panel" icon="material-symbols:inventory" style="width:100%">
      <div style="display: flex; flex-direction:column; gap: 0.375rem; min-width:350px">
        <bim-panel-section  fixed>
          <bim-text-input name="name" id="querryDataField" label="Write Question" vertical></bim-text-input>
          ${textArea}
          <div style="display: flex; gap:0.375rem">
            <bim-button name="querry" label="Querry" icon="bx:show-alt" @click=${(e) => onAddClick(e)}></bim-button>
            <bim-button label="Reset" icon="bx:show-alt" @click=${() => resetTextInputs()}></bim-button>
          </div>
        </bim-panel-section>
      </div>
    </bim-toolbar-section>
  `
  ```
</CodeGroup>

### Interface Components

<Steps>
  <Step title="Question Input">
    Text input field where you type your natural language question about the IFC model.
  </Step>

  <Step title="Response Display">
    A text area that displays the AI-generated answer with dark theme styling (background: rgb(46, 51, 56)).
  </Step>

  <Step title="Query Button">
    Submits your question to the AI for processing and displays the response.
  </Step>

  <Step title="Reset Button">
    Clears both the input field and response area for a fresh query.
  </Step>
</Steps>

## Query Processing Flow

<CodeGroup>
  ```typescript ChatGpt/src/user-interface.ts:14-26 theme={null}
  const onAddClick = async (e:Event)=>{
    const btn = e.target as BUI.Button;
    const panelSection = btn.closest("bim-panel-section");
    const querry = panelSection?.value.name;
    
    if(!modelData.fileData){
      alert("No file data, cant answear");
      return;
    }
    
    const querryResponse = await modelData.getQuerry({message:querry, fileData:modelData.fileData});
    textArea.innerText = querryResponse.choices[0].message.content;
  }
  ```
</CodeGroup>

## Enhanced IFC Data Extraction

The LoadIfc component extracts comprehensive property data for AI analysis:

<CodeGroup>
  ```typescript LoadIfc/index.ts:23-61 theme={null}
  AddIfcFileDataToGenerallString = async (model: FragmentsGroup, type: number, backupType?: number)=>{
    const indexer = this.components.get(OBC.IfcRelationsIndexer);
    let generallString: string = "";
    let wallsData = await model.getAllPropertiesOfType(type);
    if(!wallsData && backupType) wallsData = await model.getAllPropertiesOfType(backupType);
    if(wallsData==null || Object.keys(wallsData).length==0) return;
    
    for(const [expressId, propeties] of Object.entries(wallsData)){
      generallString += JSON.stringify(propeties);
      
      // Get building storey information
      const levelOfThisWall = indexer.getEntitiesWithRelation(model, "ContainsElements", parseInt(expressId));
      for(var propOfWall of levelOfThisWall){
        const property = await model.getProperties(propOfWall);
        if(property.type === WEBIFC.IFCBUILDINGSTOREY){
          generallString += JSON.stringify(property);
        }
      }

      // Get property sets and quantities
      const propertiesRelations = indexer.getEntityRelations(model,parseInt(expressId),"IsDefinedBy");
      for(const relID of propertiesRelations){
        const relatedEntity = await model.getProperties(relID);
        if(!relatedEntity) continue;
        if(relatedEntity.type === WEBIFC.IFCPROPERTYSET || relatedEntity.type === WEBIFC.IFCELEMENTQUANTITY){
          generallString += JSON.stringify(relatedEntity);
        }
      }
    }
    return generallString;
  }
  ```
</CodeGroup>

### Extracted Data Types

The system extracts three key data categories:

<Tabs>
  <Tab title="Element Properties">
    Complete property data for each IFC element including geometric and descriptive attributes.
  </Tab>

  <Tab title="Spatial Relationships">
    Building storey containment showing which floor each element belongs to.
  </Tab>

  <Tab title="Property Sets">
    IFC property sets (IFCPROPERTYSET) and element quantities (IFCELEMENTQUANTITY) for detailed specifications.
  </Tab>
</Tabs>

## Performance Optimization

<Warning>
  **Token Usage**: The system logs the data size before and after filtering. Typical reduction is 60-80% of original file size, significantly reducing API costs and response time.
</Warning>

<CodeGroup>
  ```typescript ChatGpt/index.ts:87-88 theme={null}
  console.log("number of words: ", this.fileData?.length);
  console.log("number of words after short: ", this.modifyDataDile()?.length);
  ```
</CodeGroup>

## Example Queries

Here are effective questions you can ask the AI Assistant:

<AccordionGroup>
  <Accordion title="Material Analysis">
    * "What types of concrete are used in this project?"
    * "List all materials and their quantities"
    * "Which elements use steel reinforcement?"
  </Accordion>

  <Accordion title="Spatial Organization">
    * "How many building storeys are there?"
    * "What is the name and elevation of each floor?"
    * "Which elements are located on the ground floor?"
  </Accordion>

  <Accordion title="Element Information">
    * "What are the properties of element #2586?"
    * "How many walls are on Level 2?"
    * "List all beams and their dimensions"
  </Accordion>

  <Accordion title="Quantitative Analysis">
    * "What is the total count of slabs?"
    * "How many different wall types exist?"
    * "Count all structural elements by type"
  </Accordion>
</AccordionGroup>

## Configuration

### API Key Setup

The AI Assistant requires an OpenAI API key configured in your environment:

<CodeGroup>
  ```bash .env theme={null}
  VITE_OPENAI_API_KEY=your_openai_api_key_here
  ```
</CodeGroup>

<Tip>
  Get your API key from [OpenAI Platform](https://platform.openai.com/api-keys). The system uses the GPT-3.5-turbo model for optimal balance of speed and accuracy.
</Tip>

## Limitations and Best Practices

<Warning>
  **Data Dependency**: The AI can only answer questions about data explicitly present in the loaded IFC file. It cannot infer or calculate information not in the file.
</Warning>

<Note>
  **File Required**: You must load an IFC file before using the AI Assistant. If no file is loaded, you'll receive an alert: "No file data, cant answear".
</Note>

<Tip>
  **Query Optimization**: Ask specific questions about elements, materials, or spatial relationships for the most accurate responses. Vague questions may result in incomplete answers.
</Tip>

## Future Enhancements

The AI Assistant is continuously evolving with planned features:

* Support for GPT-4 for more complex analysis
* Multi-file comparison queries
* Automated clash detection analysis
* Cost estimation based on materials and quantities
* Compliance checking against building codes
