Metadata-Version: 2.1
Name: gptscript
Version: 0.9.5
Summary: Run gptscripts from Python apps
Author-email: Bill Maxwell <bill@acorn.io>
License: 
                                         Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
        
Project-URL: Homepage, https://github.com/gptscript-ai/py-gptscript/
Project-URL: Issues, https://github.com/gptscript-ai/py-gptscript/issues
Project-URL: Repository, https://github.com/gptscript-ai/py-gptscript.git
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: certifi==2024.2.2
Requires-Dist: charset-normalizer==3.3.2
Requires-Dist: httpx==0.27.0
Requires-Dist: idna==3.6
Requires-Dist: requests==2.31.0
Requires-Dist: tqdm==4.66.2
Requires-Dist: urllib3==2.2.1
Requires-Dist: pywin32==306; sys_platform == "win32"

# GPTScript Python Module

## Introduction

The GPTScript Python module is a library that provides a simple interface to create and run gptscripts within Python
applications, and Jupyter notebooks. It allows you to define tools, execute them, and process the responses.

## Installation

You can install the GPTScript Python module using pip.

```bash
pip install gptscript
```

On MacOS, Windows X6

### SDIST and none-any wheel installations

When installing from the sdist or the none-any wheel, the binary is not packaged by default. You must run the
install_gptscript command to install the binary.

```bash
install_gptscript
```

The script is added to the same bin directory as the python executable, so it should be in your path.

Or you can install the gptscript cli from your code by running:

```python
from gptscript.install import install

install()
```

### Using an existing gptscript cli

If you already have the gptscript cli installed, you can use it by setting the envvar:

```bash
export GPTSCRIPT_BIN="/path/to/gptscript"
```

## GPTScript

The GPTScript instance allows the caller to run gptscript files, tools, and other operations (see below). Note that the
intention is that a single GPTScript instance is all you need for the life of your application, you should
call `close()` on the instance when you are done.

## Global Options

When creating a `GTPScript` instance, you can pass the following global options. These options are also available as
run `Options`. Anything specified as a run option will take precedence over the global option.

- `APIKey`: Specify an OpenAI API key for authenticating requests. Defaults to `OPENAI_API_KEY` environment variable
- `BaseURL`: A base URL for an OpenAI compatible API (the default is `https://api.openai.com/v1`)
- `DefaultModel`: The default model to use for chat completion requests
- `DefaultModelProvider`: The default model provider to use for chat completion requests
- `Env`: Supply the environment variables. Supplying anything here means that nothing from the environment is used. The
  default is `os.environ()`. Supplying `Env` at the run/evaluate level will be treated as "additional."

## Run Options

These are optional options that can be passed to the `run` and `evaluate` functions.
None of the options is required, and the defaults will reduce the number of calls made to the Model API.
As noted above, the Global Options are also available to specify here. These options would take precedence.

- `disableCache`: Enable or disable caching. Default (False).
- `subTool`: Use tool of this name, not the first tool
- `input`: Input arguments for the tool run
- `workspace`: Directory to use for the workspace, if specified it will not be deleted on exit
- `chatState`: The chat state to continue, or null to start a new chat and return the state
- `confirm`: Prompt before running potentially dangerous commands
- `prompt`: Allow prompting of the user

## Tools

The `Tool` class represents a gptscript tool. The fields align with what you would be able to define in a normal
gptscript .gpt file.

### Fields

- `name`: The name of the tool.
- `description`: A description of the tool.
- `tools`: Additional tools associated with the main tool.
- `maxTokens`: The maximum number of tokens to generate.
- `model`: The GPT model to use.
- `cache`: Whether to use caching for responses.
- `temperature`: The temperature parameter for response generation.
- `arguments`: Additional arguments for the tool.
- `internalPrompt`: Optional boolean defaults to None.
- `instructions`: Instructions or additional information about the tool.
- `jsonResponse`: Whether the response should be in JSON format.(If you set this to True, you must say 'json' in the
  instructions as well.)

## Primary Functions

Aside from the list methods there are `exec` and `exec_file` methods that allow you to execute a tool and get the
responses. Those functions also provide a streaming version of execution if you want to process the output streams in
your code as the tool is running.

### `list_models()`

This function lists the available GPT models.

```python
from gptscript.gptscript import GPTScript


async def list_models():
    gptscript = GPTScript()
    tools = await gptscript.list_models()
    print(tools)
    gptscript.close()
```

### `parse()`

Parse a file into a Tool data structure.

```python
from gptscript.gptscript import GPTScript


async def parse_example():
    gptscript = GPTScript()
    tools = await gptscript.parse("/path/to/file")
    print(tools)
    gptscript.close()
```

### `parse_tool()`

Parse the contents that represents a GPTScript file into a Tool data structure.

```python
from gptscript.gptscript import GPTScript


async def parse_tool_example():
    gptscript = GPTScript()
    tools = await gptscript.parse_content("Instructions: Say hello!")
    print(tools)
    gptscript.close()
```

### `fmt()`

Parse convert a tool data structure into a GPTScript file.

```python
from gptscript.gptscript import GPTScript


async def fmt_example():
    gptscript = GPTScript()
    tools = await gptscript.parse_content("Instructions: Say hello!")
    print(tools)

    contents = gptscript.fmt(tools)
    print(contents)  # This would print "Instructions: Say hello!"
    gptscript.close()
```

### `evaluate()`

Executes a tool with optional arguments.

```python
from gptscript.gptscript import GPTScript
from gptscript.tool import ToolDef


async def evaluate_example():
    tool = ToolDef(instructions="Who was the president of the United States in 1928?")
    gptscript = GPTScript()

    run = gptscript.evaluate(tool)
    output = await run.text()

    print(output)

    gptscript.close()
```

### `run()`

Executes a GPT script file with optional input and arguments. The script is relative to the callers source directory.

```python
from gptscript.gptscript import GPTScript


async def evaluate_example():
    gptscript = GPTScript()

    run = gptscript.run("/path/to/file")
    output = await run.text()

    print(output)

    gptscript.close()
```

### Streaming events

GPTScript provides events for the various steps it takes. You can get those events and process them
with `event_handlers`. The `evaluate` method is used here, but the same functionality exists for the `run` method.

```python
from gptscript.gptscript import GPTScript
from gptscript.frame import RunFrame, CallFrame, PromptFrame
from gptscript.run import Run


async def process_event(run: Run, event: RunFrame | CallFrame | PromptFrame):
    print(event.__dict__)


async def evaluate_example():
    gptscript = GPTScript()

    run = gptscript.run("/path/to/file", event_handlers=[process_event])
    output = await run.text()

    print(output)

    gptscript.close()
```

### Confirm

Using the `confirm: true` option allows a user to inspect potentially dangerous commands before they are run. The caller
has the ability to allow or disallow their running. In order to do this, a caller should look for the `CallConfirm`
event.

```python
from gptscript.gptscript import GPTScript
from gptscript.frame import RunFrame, CallFrame, PromptFrame
from gptscript.run import Run, RunEventType
from gptscript.confirm import AuthResponse

gptscript = GPTScript()


async def confirm(run: Run, event: RunFrame | CallFrame | PromptFrame):
    if event.type == RunEventType.callConfirm:
        # AuthResponse also has a "message" field to specify why the confirm was denied.
        await gptscript.confirm(AuthResponse(accept=True))


async def evaluate_example():
    run = gptscript.run("/path/to/file", event_handlers=[confirm])
    output = await run.text()

    print(output)

    gptscript.close()
```

### Prompt

Using the `prompt: true` option allows a script to prompt a user for input. In order to do this, a caller should look
for the `Prompt` event. Note that if a `Prompt` event occurs when it has not explicitly been allowed, then the run will
error.

```python
from gptscript.gptscript import GPTScript
from gptscript.frame import RunFrame, CallFrame, PromptFrame
from gptscript.run import Run
from gptscript.opts import Options
from gptscript.prompt import PromptResponse

gptscript = GPTScript()


async def prompt(run: Run, event: RunFrame | CallFrame | PromptFrame):
    if isinstance(event, PromptFrame):
        # The responses field here is a dictionary of prompt fields to values.
        await gptscript.prompt(PromptResponse(id=event.id, responses={event.fields[0]: "Some value"}))


async def evaluate_example():
    run = gptscript.run("/path/to/file", opts=Options(prompt=True), event_handlers=[prompt])
    output = await run.text()

    print(output)

    gptscript.close()
```

## Example Usage

```python
from gptscript.gptscript import GPTScript
from gptscript.tool import ToolDef

# Create the GPTScript object
gptscript = GPTScript()

# Define a tool
complex_tool = ToolDef(
    tools=["sys.write"],
    jsonResponse=True,
    cache=False,
    instructions="""
    Create three short graphic artist descriptions and their muses.
    These should be descriptive and explain their point of view.
    Also come up with a made-up name, they each should be from different
    backgrounds and approach art differently.
    the JSON response format should be:
    {
        artists: [{
            name: "name"
            description: "description"
        }]
    }
    """
)

# Execute the complex tool
run = gptscript.evaluate(complex_tool)
print(await run.text())

gptscript.close()
```

### Example 2 multiple tools

In this example, multiple tool are provided to the exec function. The first tool is the only one that can exclude the
name field. These will be joined and passed into the gptscript as a single gptscript.

```python
from gptscript.gptscript import GPTScript
from gptscript.tool import ToolDef

gptscript = GPTScript()

tools = [
    ToolDef(tools=["echo"], instructions="echo hello times"),
    ToolDef(
        name="echo",
        tools=["sys.exec"],
        description="Echo's the input",
        args={"input": "the string input to echo"},
        instructions="""
        #!/bin/bash
        echo ${input}
        """,
    ),
]

run = gptscript.evaluate(tools)

print(await run.text())

gptscript.close()
```
