# AIConversation class
{: .no_toc }

A conversation with an AI model: the questions an add-in asks, the model's replies as they arrive, and the tools of the add-in's that the model may call. Made by [**HostAIProvider.StartConversation**](/tB/Packages/tbIDE/HostAIProvider.md#startconversation).

The IDE sends the conversation's messages to the model's endpoint and passes the reply back as events. Each [**Ask**](#ask) sends the whole conversation so far, the system prompt first, so the model sees the earlier questions and replies.

```tb check_build
Private WithEvents Chat As AIConversation

Private Sub StartChat()
    Set Chat = Host.AI.Providers.DefaultProvider.StartConversation()
    Chat.SystemPrompt = "You help with twinBASIC code. Answer briefly."
    Chat.RegisterTool "line_count", "Returns how many lines the active code file has", _
        "{""type"": ""object"", ""properties"": {}}"
    Chat.Ask "How many lines does my file have?", True
End Sub

Private Sub Chat_Chunk(ByVal Text As String)
    Host.DebugConsole.PrintText Text
End Sub

Private Sub Chat_ToolCall(ByVal ToolRequestJson As String, ByVal ResultResolver As AsyncResultResolver)
    Dim lines As Long
    If Host.ActiveEditors.Count > 0 Then
        If TypeOf Host.ActiveEditors(0) Is CodeEditor Then
            Dim ed As CodeEditor = Host.ActiveEditors(0)
            lines = UBound(Split(ed.Text, vbLf)) + 1
        End If
    End If
    ResultResolver.Resolve "{""lines"": " & lines & "}"
End Sub

Private Sub Chat_Failed(ByVal ErrorMessage As String)
    Host.DebugConsole.PrintText "The AI failed: " & ErrorMessage
End Sub
```

* TOC
{:toc}

## The events of one question

[**Ask**](#ask) returns at once. Then, in order:

1. [**Started**](#started) fires.
2. [**ThinkingChunk**](#thinkingchunk) fires for the text of the model's reasoning, if the service sends it.
3. [**Chunk**](#chunk) fires with the reply's text: as it arrives when the question was streamed, or once with the whole reply when it was not. A chunk holds one piece of the reply or several.
4. [**ToolCall**](#toolcall) fires when the model calls one of the conversation's tools. Once the add-in has answered it, the IDE sends the answer to the model, and the reply goes on.
5. [**Completed**](#completed) fires with the whole reply, and the conversation can be asked again.

[**Failed**](#failed) or [**Cancelled**](#cancelled) can take the place of the last steps.

## Properties

### State
{: .no_toc }

Whether the conversation is ready for a question. **As** [**AIConversationState**](#aiconversationstate), read-only. **Idle** when it is made, and **Closed** after [**Close**](#close).

> [!WARNING] BETA 1052
> **State** never reads **Busy**: it is **Idle** straight after [**Ask**](#ask) and in every event of the question, [**Started**](#started), [**Chunk**](#chunk) and [**ToolCall**](#toolcall) included. To know whether a question is under way, keep a flag of the add-in's own, set by **Ask** and cleared in [**Completed**](#completed), [**Failed**](#failed) and [**Cancelled**](#cancelled).

### SystemPrompt
{: .no_toc }

Instructions for the model, sent before the conversation's messages. **String**, read/write. Empty when the conversation is made.

Set it before the first [**Ask**](#ask). A value set after it does not reach the model, though **SystemPrompt** then reads it.

## Methods

### Ask
{: .no_toc }

Sends a question to the model. **Ask** returns at once, and the reply comes as [events](#the-events-of-one-question).

Syntax: *conversation*.**Ask** *Prompt*, *Stream* [, *AttachmentsJson* ]

*Prompt*
: *required* The question. **String**.

*Stream*
: *required* **True** to have the reply in pieces as the service sends it, **False** to have it in one [**Chunk**](#chunk) once it is complete. **Boolean**.

*AttachmentsJson*
: *optional* Images to send with the question, as a **String** of JSON: an array with an object for each image, whose `mimeType` is `"image/png"`, `"image/jpeg"`, `"image/webp"` or `"image/gif"`, and whose `base64` is the image's bytes as base64. An image may be at most 16 MiB, and a PNG at most 8192 pixels wide and high. An empty string sends none.

```json
[ { "mimeType": "image/png", "base64": "iVBORw0KGgoAAAANSUhEUgAA..." } ]
```

An attachment that is not one of those raises no error: [**Failed**](#failed) fires with the reason, such as *Image attachment 1: unsupported image type (use PNG, JPEG, WebP or GIF)*, and nothing is sent.

An **Ask** while the conversation is answering another question does nothing. An **Ask** after [**Close**](#close) raises no error; **Failed** fires, saying that the conversation is unknown.

### Cancel
{: .no_toc }

Stops the question under way: the IDE stops reading the reply, and [**Cancelled**](#cancelled) fires in place of [**Completed**](#completed). The conversation can then be asked again.

Syntax: *conversation*.**Cancel**

### Close
{: .no_toc }

Ends the conversation: it stops any question under way, and forgets the conversation's messages and tools. [**State**](#state) is then **Closed**, and the conversation cannot be asked again.

Syntax: *conversation*.**Close**

### RegisterTool
{: .no_toc }

Gives the model a tool that it may call while it answers: a function of the add-in's, described to the model by its name, what it does and its parameters. When the model calls it, [**ToolCall**](#toolcall) fires.

Syntax: *conversation*.**RegisterTool** *Name*, *Description*, *ParametersJson*

*Name*
: *required* The tool's name: letters, digits and `_`, not starting with a digit. **String**.

*Description*
: *required* What the tool does, for the model to read. **String**, not empty.

*ParametersJson*
: *required* The tool's parameters, as a **String** holding a JSON Schema of an object, whose `"type"` is `"object"`: `{"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}`. A tool with no parameters has `{"type": "object", "properties": {}}`.

Register every tool before the first [**Ask**](#ask). A tool registered after it does not reach the model. A tool whose name, description or parameters are not valid is left out, with no error.

Before registering a tool that reads the project's files, changes them or runs code, check the provider's [**Permissions**](/tB/Packages/tbIDE/HostAIProvider.md#permissions).

## Events

### Cancelled
{: .no_toc }

Fires when [**Cancel**](#cancel) has stopped the question.

Syntax: *conversation*_**Cancelled**()

### Chunk
{: .no_toc }

Fires with text of the reply. Join the chunks of one question, or wait for [**Completed**](#completed), which has the whole reply.

Syntax: *conversation*_**Chunk**( *Text* **As String** )

### Completed
{: .no_toc }

Fires when the reply is complete. The conversation can then be asked again.

Syntax: *conversation*_**Completed**( *Response* **As String** )

*Response*
: The whole reply's text.

### Failed
{: .no_toc }

Fires when the question failed: the service could not be reached or answered with an error, an attachment was not valid, or a tool's answer did not come within two minutes. The conversation can then be asked again.

Syntax: *conversation*_**Failed**( *ErrorMessage* **As String** )

*ErrorMessage*
: What went wrong. When the service answered with an error, `HTTP`, its status code, a colon and what it answered: *HTTP 401: ...*.

### Started
{: .no_toc }

Fires when the IDE has begun the question, before any other event of it.

Syntax: *conversation*_**Started**()

### ThinkingChunk
{: .no_toc }

Fires with text of the model's reasoning, which a model that reasons may send before its reply. It is not part of the reply.

Syntax: *conversation*_**ThinkingChunk**( *Text* **As String** )

### ToolCall
{: .no_toc }

Fires when the model calls one of the tools given to [**RegisterTool**](#registertool). The reply waits for the answer.

Syntax: *conversation*_**ToolCall**( *ToolRequestJson* **As String**, *ResultResolver* **As** [**AsyncResultResolver**](/tB/Packages/tbIDE/AsyncResultResolver.md) )

*ToolRequestJson*
: The call, as a JSON object: `name` is the tool's name, and `arguments` a string that holds the arguments as JSON in turn: `{"name":"get_number","arguments":"{\"which\":\"x\"}"}`. Parse `arguments` a second time to read them.

*ResultResolver*
: Takes the tool's result. Call its [**Resolve**](/tB/Packages/tbIDE/AsyncResultResolver.md#resolve) with the result as text, which the model receives as it is; a JSON object is usual. To return an image, call `Resolve` with the image as base64 and its MIME type, `"image/png"`, `"image/jpeg"`, `"image/webp"` or `"image/gif"`. Answer within two minutes, or the question fails.

## AIConversationState
{: #aiconversationstate }

What [**State**](#state) returns.

| Constant | Value | Description |
|----------|-------|-------------|
| **Idle**{: #AIConversationState_Idle } | 0 | Ready for a question. |
| **Busy**{: #AIConversationState_Busy } | 1 | Answering a question. |
| **Closed**{: #AIConversationState_Closed } | 2 | Closed by [**Close**](#close). |

## See Also

- [HostAIProvider.StartConversation](/tB/Packages/tbIDE/HostAIProvider.md#startconversation) method
- [AsyncResultResolver](/tB/Packages/tbIDE/AsyncResultResolver.md) class
- [HostAIProviderPermissions](/tB/Packages/tbIDE/HostAIProviderPermissions.md) class
