# Example Chat Agent

### **Example: ChatAgent**

**ChatAgent** is an implementation of `GrocAgent` designed to handle chat-based queries. It demonstrates how to use `GrocAgent` to create a chatbot capable of processing user queries and generating responses using an external model (e.g., `Modellake`).\
\
\&#xNAN;***Note:** While this example uses `Modellake` to implement chatbot functionality, users can extend `GrocAgent` to incorporate other libraries or custom logic based on their project requirements.*

### **Imports**

Ensure the following imports are included when using `GrocAgent`:

```python
from flask import Flask  # Flask is used as the web server framework
from groclake.modellake import Modellake  # (Optional) For handling chatbot logic
from groclake.utillake import GrocAgent  # Base class to define custom agents
```

### **Implementation Details**

The `ChatAgent` example is initialized with:

1. **Flask App Instance**: Registers the agent with a Flask application.
2. **Agent Name**: Identifies the agent (e.g., `"ChatAgent"`).
3. **Initial Intent and Description**: Defines the default intent (`"chat"`) and its purpose.
4. **Adaptor Configuration**: Links external dependencies through configurations.

```python
class ChatAgent(GrocAgent):
    def __init__(self, app, agent_name, initial_intent=None, intent_description=None, adaptor_config=None):
        super().__init__(app, agent_name, initial_intent, intent_description, self.default_handler, adaptor_config)
```

### **Default Handler**

The `default_handler` method processes incoming payloads to:

* Extract key components: `query_text`, `intent`, `entities`, and `metadata`.
* Construct a chat payload for the `Modellake` API.
* Retrieve and return a response from the model, with error handling for fallback responses.

```python
def default_handler(self, payload):
    try:
        query_text = payload.get('query_text', 'No query provided')
        intent = payload.get('intent', 'default_chat')
        entities = payload.get('entities', [])
        metadata = payload.get('metadata', {})

        chat_payload = {
            "messages": [
                {"role": "system", "content": "You are a helpful assistant. Only answer technical questions."},
                {"role": "user", "content": query_text}
            ],
            "token_size": 500
        }

        chat_response = Modellake().chat_complete(chat_payload)
        response_text = chat_response.get("answer", "I'm not sure how to help with that.")

        return {
            "response_text": response_text,
            "intent": intent,
            "entities": entities,
            "metadata": metadata,
            "query_text": query_text
        }
    except Exception as e:
        return {
            "response_text": f"Error: {str(e)}",
            "intent": payload.get('intent', 'default_chat'),
            "metadata": payload.get('metadata', {}),
            "query_text": payload.get('query_text', ''),
            "status": 500
        }
```

***

### **Request and Response Example**

**Request Example**

```json
{
  "groc_account_id": "",
  "header": {
    "version": "1.0",
    "message": "Request",
    "Content-Type": "application/json",
    "auth_token": "Authentication-Token",
    "apc_id": "c9d1c9b9-9f1b-4430-9bd4-6994dc1c89ee",
    "server_agent_uuid": "075fcb88-f25a-4390-a37e-e374a3c2b1df",
    "client_agent_uuid": "Client-Agent-UUID"
  },
  "body": {
    "query_text": "What is AI?",
    "intent": "chat",
    "entities": [{"ticket_id": "123314141"}],
    "metadata": {
      "context": "query generated from a support chatbot",
      "customer_id": "895985133"
    }
  }
}
```

**Response Example**

```json
{
  "body": {
    "entities": [{"ticket_id": "123314141"}],
    "intent": "chat",
    "metadata": {
      "context": "query generated from a support chatbot",
      "customer_id": "895985133"
    },
    "query_text": "What is AI?",
    "response_text": "AI, or Artificial Intelligence, refers to the simulation of human intelligence processes by machines..."
  },
  "header": {
    "apc_id": "c9d1c9b9-9f1b-4430-9bd4-6994dc1c89ee",
    "auth_token": "Authentication-Token",
    "client_agent_uuid": "Client-Agent-UUID",
    "content-type": "application/json",
    "message": "response",
    "version": "1.0"
  }
}
```

***


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.groclake.ai/grocagent/editor-1.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
